diff --git a/cmake/WKWebViewSupport.cmake b/cmake/WKWebViewSupport.cmake index 1ddeb91f..4d67bbc8 100644 --- a/cmake/WKWebViewSupport.cmake +++ b/cmake/WKWebViewSupport.cmake @@ -18,7 +18,7 @@ function(webfront_add_wkwebview_tests) add_executable(wkwebview_lifecycle "${webtest_source_dir}/WKWebViewLifecycle.cpp" "${webtest_source_dir}/WKWebViewHeaderConsumer.cpp") target_link_libraries(wkwebview_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) - foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings translucent-background hidden-scheduling hidden-secondary redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download choose-in-blank choose-in-srcdoc close-with-open-panel close-with-save-panel script-dialogs close-with-script-dialog sandboxed-script-dialog load-reveal present-timeout) + foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings translucent-background hidden-scheduling hidden-secondary secondary-scheduling redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download choose-in-blank choose-in-srcdoc close-with-open-panel close-with-save-panel script-dialogs close-with-script-dialog sandboxed-script-dialog load-reveal present-timeout) add_test(NAME WKWebViewLifecycle-${mode} COMMAND wkwebview_lifecycle ${mode}) webfront_set_browser_test_properties("WKWebViewLifecycle-${mode}" "${webtest_source_dir}" 90) endforeach() diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 41e781cd..7e5ee597 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -16,6 +16,9 @@ these entries stays in the GitHub releases and the Git history. ### Added - Open the inspectors from the WebFront tab's menu of the developer environment: each panel shows in a floating window of the page and can be detached to a native secondary window (WebKitGTK, WKWebView, WebView2) or, with `trustLoopbackClients`, a tab of the system browser; the choice and the place are kept per project (#680, ADR-027, `docs/DEVELOPER_ENVIRONMENT.md`). +- See in the **Functions** panel of the inspectors what the application registered: each `cppFunction` with its signature written in TypeScript, the file and line of its registration, whether it receives the calling `UI`, its calls, failures, last error and durations, then the JavaScript functions that C++ calls; sort, search, and choose the refresh period (#681, ADR-027, `docs/DEVELOPER_ENVIRONMENT.md`). +- See in the **Browsers and tasks** panel the connected browsers (embedded view or external browser, local client, pending writes and calls), the running tasks of the server and the application's terminal commands (#681, ADR-027). +- Read the same registry from C++ with `app.registeredFunctions()` (#681, ADR-027). - Declare what the inspectors show with `app.watch(name, source)`, whose handle removes the watch when it is destroyed; the Watches panel follows their registrations and removals. Outside the developer environment and in a distribution build, `watch` registers nothing (#680, ADR-027). - Embed a plain interface directory (HTML, JavaScript, CSS, vendored files) from CMake with `webfront_embed_directory(app ui CLASS AppUI)`, without the developer environment: the build regenerates the provider when a file changes, and `fs::DocumentRootFirstFSWith` lets a development root serve in front of it (#675, `docs/EMBEDDED_ASSETS.md`). - Set from the configuration `Referrer-Policy` (`contentPolicy.referrerPolicy`: `"no-referrer"` forbids explicitly that a capability in your URLs leaves in `Referer`), `X-Content-Type-Options: nosniff` (`noSniff`) and the `Cache-Control` of HTML pages (`htmlCacheControl`), on files, route and generated replies unless a reply sets its own (#674, `docs/CONTENT_POLICY.md`). @@ -29,11 +32,13 @@ these entries stays in the GitHub releases and the Git history. - The test helpers, `webfront_add_jasmine_test` included, export the real `XDG_DATA_HOME` and `XDG_CACHE_HOME` as `WEBFRONT_TEST_REAL_XDG_DATA_HOME` and `WEBFRONT_TEST_REAL_XDG_CACHE_HOME`, so an application under test can keep the throwaway WebKitGTK profile away from the programs it starts ([#664](https://github.com/ambroise-leclerc/WebFront/issues/664), `docs/CONSUMER_TESTING.md`). ### Changed +- The inspectors show where each `cppFunction` was registered; existing calls of `cppFunction` and `Space::cppFunction` compile unchanged (#681, ADR-027). - `WebFront.js` opens its WebSocket on the directory of the page (`ws://host/dir/` instead of `ws://host`), which tells the server a page's space (#671) and lets an application be deployed under a sub-path of a site (#672). - A request whose path holds a control character (`%00`...) is refused with 400, as a `..` already was, instead of being looked up as a file (#672). - A `+` in the path of a file request is a literal `+`, as for the routes, the spaces and `ui.path()`: `/a+b.html` serves `a+b.html`, no longer `a b.html`, which `/a%20b.html` names (#672). ### Fixed +- A closed WKWebView secondary window, or one that another window covered, no longer leaves its page suspended and connected to the application: on macOS 14+ a secondary window is never suspended while inactive (#681, `docs/WKWEBVIEW.md`). - An invalid content policy (an origin of `bridgeAllowedOrigins` or `navigationAllowedOrigins`, a `referrerPolicy`, a `htmlCacheControl`) throws `std::invalid_argument` before the server binds its port, as documented, instead of an "address already in use" error when that port is taken (#674). - `DeveloperBrowserIntegration-workspace` gives the relaunched bootstrap page the same 60 s to start as the first one, instead of 10 s, which a loaded runner exceeded while the page verified its cached environment (#660). - Applications started from the terminal of a Snap-packaged editor (VSCodium) now run on WebKitGTK without cleaning the environment by hand; `WEBFRONT_KEEP_SNAP_ENVIRONMENT=1` opts out (#662, `docs/WEBKITGTK.md`). diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index f77fc9bd..cf0e47cd 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -469,7 +469,31 @@ environment's `mount`, not to the embedded bootstrap page): The **Watches** panel lists the application's watches (`app.watch(name, source)`, declared after `bootstrap()`): their name, the kind of their root and where they were declared. It asks C++ for the revision of their table every 250 ms (Pause stops it), reads the list again when it changed, and adds or removes the watches that appeared or disappeared. - Their contents, and the other panels, come with the next versions of the environment. + Their contents come with the next versions of the environment. + + The **Functions** panel lists what the application registered with `cppFunction`, the functions of its spaces included + (with the path of their space): the name, the signature as TypeScript declares it (`(a: number, b: string) => + Promise`; the calling `UI` is not a parameter of JavaScript), the file and line of the registration, the number + of calls and of failures, the last error, and the mean and longest duration. **Caller** tells whether the function + receives the calling `UI`: one that does not cannot check `ui.isLocalClient()`, which a callback that writes the project, + starts a process or exposes a sensitive state must do itself (ADR-027, section 2). **Answer** tells a function that + returns a task (`ResultTask`), whose Promise settles when the task completes. A second table lists the JavaScript + functions that C++ called (`jsFunction`, `jsFunctionSender`, `broadcast`, a broadcast counting once) with the failures + of the typed calls. WebFront's own functions (`webfront.developer.*`, `webfront.commands.*`) are hidden until the + checkbox asks for them. A header sorts by its column (a second click reverses), the search field keeps the rows that + hold every word typed, and the values are read again every 250 ms, 1 s or 5 s, as chosen, until Pause. + + The counters cost an atomic increment per call whether or not an inspector is open (about 12 ns measured, see + `introspection_benchmark`); the durations are measured only while this panel reads, and for five seconds after its + last read, so a function shows `–` until one of its calls was timed. A distribution build records nothing. + `app.registeredFunctions()` gives the same registry to C++ code. + + The **Browsers and tasks** panel lists the connected browsers: whether each is an embedded view or an external browser, + whether it is a local client (`ui.isLocalClient()`), its state, the path its bridge was opened from and its space, the + frames not yet written to it, the typed calls of C++ whose result it has not returned, and its calls that a C++ + callback has not answered yet. It also gives the number of running tasks of the server's scope (connections, bridge + loops and the application's coroutines) and the application's terminal commands (`webfront::Commands`). The other + panels come with the next versions of the environment. The tab is a button (`aria-expanded`, `aria-haspopup="menu"`, 44 px target), its menu a `menu` of `menuitem`s of 44 px, and the window a non-modal dialog. The interface stays in the preview diff --git a/docs/WKWEBVIEW.md b/docs/WKWEBVIEW.md index 42c2935c..eddd0037 100644 --- a/docs/WKWEBVIEW.md +++ b/docs/WKWEBVIEW.md @@ -209,3 +209,6 @@ retained lifecycle cases. Hidden sessions require macOS 14+ and use the public `WKPreferences::inactiveSchedulingPolicy` value `None` so asynchronous bridge and Worker work continues after the load event. Visible sessions retain macOS 13.3 support. +On macOS 14+, a secondary window (`openSecondaryWindow()`) uses the same policy, visible or not: closing it hides it +before its view is released, and an occluded window is inactive all along, so a suspended page would keep its +connection after its window closed. The first visible window keeps WebKit's default policy. diff --git a/docs/adr/ADR-027-inspecteurs-de-l-etat-de-l-application.md b/docs/adr/ADR-027-inspecteurs-de-l-etat-de-l-application.md index 91750435..12f99421 100644 --- a/docs/adr/ADR-027-inspecteurs-de-l-etat-de-l-application.md +++ b/docs/adr/ADR-027-inspecteurs-de-l-etat-de-l-application.md @@ -4,6 +4,7 @@ | Version | Date | État | Auteur | Évolution | Révision Git | | --- | --- | --- | --- | --- | --- | +| 1.2 | 2026-11-26 | Proposée | Ambroise Leclerc | Registre introspectable (#681) : pages `webfront.inspector.functions`, `jsFunctions` et `browsers` (section 7) ; enregistrements tenus par les gestionnaires, donc retirés avec une fonction d'espace ; fonctions `webfront.inspector.*` non listées ; durée mesurée pendant une fenêtre de 5 s après chaque lecture des fonctions ; appels vers JavaScript comptés par nom, 1 024 noms au plus, seulement une fois l'environnement monté ; `BasicWF::registeredFunctions()` pour l'application. | À renseigner après intégration. | | 1.1 | 2026-11-25 | Proposée | Ambroise Leclerc | Hôte détachable (#680) : `webfront.inspector.embedded()` dit à la page hôte si elle peut tourner dans un frontend intégré (vue prouvée, ou frontend actif qui transmet la preuve), ce qui décide de l'onglet du navigateur système ; `webfront.inspector.closeWindow(panneau, hôte)` ferme la fenêtre d'un panneau rattaché ; une fenêtre par panneau et par page hôte, qui seule le rattache ; choix et place conservés dans `inspector-window.json`, lus avec le jeton de leurs octets par `webfront.inspector.readPreferences()`. | À renseigner après intégration. | | 1.0 | 2026-11-25 | Proposée | Ambroise Leclerc | Décision initiale (#678, épique #677) : inspecteurs réservés à l'environnement développeur, accès réservé aux vues prouvées sauf autorisation explicite, nœuds d'arbre sur les types existants du pont, lecture et différences paginées, opérations entières sous le verrou ou sur l'exécuteur de l'application, modification à la demande de l'application, page unique `inspector.html` dans un conteneur choisi sur l'accès effectif. | À renseigner après intégration. | @@ -639,6 +640,60 @@ générées, le nombre d'appels et d'échecs, la dernière erreur et la durée m atomiques relâchés ; la durée n'est mesurée que pendant qu'un inspecteur est ouvert, pour qu'une application sans inspecteur n'en paie pas le coût. +**Ce qui est enregistré.** À chaque `cppFunction` (de l'application ou d'un espace, `Space::cppFunction`), WebFront +garde un enregistrement : le nom, la signature, le fichier et la ligne, le chemin de l'espace propriétaire (vide pour +l'application), si le premier paramètre est l'appelant (`UI`), et si la fonction rend un émetteur (`ResultTask`), donc +répond plus tard. L'enregistrement appartient au gestionnaire de la fonction : un enregistrement refusé (nom déjà pris) +ou une fonction d'espace libérée avec son espace disparaît du registre sans autre retrait. Les fonctions +`webfront.inspector.*` ne sont pas enregistrées : leurs compteurs ne mesureraient que l'inspecteur. Les autres fonctions +réservées (`webfront.developer.*`, `webfront.commands.*`) le sont, et le panneau les masque par défaut. + +**Signature.** Elle s'écrit `(a: number, b: string) => Promise` : les types sont ceux que JavaScript donne ou +reçoit par le pont (`boolean`, `number`, `string`, le tableau typé d'un conteneur de nombres, `Uint8Array` pour un +`std::bitset`, `[A, B]` pour un tuple ou une paire, `T[]` pour une liste, `void`, et `unknown` pour un type que le pont +ne transporte pas) ; l'appelant `UI` n'est pas un paramètre de JavaScript et n'y figure pas ; le résultat est toujours +une `Promise`, celle de la valeur de la tâche pour une fonction différée. Les noms des paramètres, que C++ ne donne pas, +sont `a`, `b`, … La signature est bornée à 512 octets. + +**Compteurs.** Chaque appel reçu incrémente `appels` ; un appel qui ne rend pas de résultat incrémente `échecs` et +remplace la dernière erreur (texte borné à 256 octets, caractères de contrôle rendus visibles) : arguments mal formés, +exception du callback, résultat qui ne s'encode pas, et, pour une fonction différée, tâche qui échoue ou qui est arrêtée +(déconnexion du navigateur, arrêt de l'application : le code `webfront.cancelled`). La durée va de la réception à la +réponse, donc jusqu'à la fin de la tâche pour une fonction différée. + +**Coût.** Sans inspecteur, un appel coûte un incrément atomique relâché et la lecture d'un drapeau, sans horloge ni +verrou : une douzaine de nanosecondes mesurées (`introspection_benchmark`, Release), contre plusieurs microsecondes +pour un appel du pont. Chaque lecture de `functions` ouvre la mesure des durées pour cinq secondes ; le premier appel +qui suit cette fenêtre, et qui lit l'horloge de toute façon, la referme. Un appel mesuré coûte deux lectures d'horloge +(environ 70 ns). Une construction de distribution n'enregistre rien et ne compte rien. + +**Fonctions JavaScript appelées par C++.** Une fois l'environnement développeur monté, chaque appel de `jsFunction` +(typé ou non), chaque démarrage d'un `jsFunctionSender` et chaque `broadcast` (compté une fois, quel que soit le nombre +de navigateurs) incrémente le compteur de son nom ; un appel typé dont le futur ou l'émetteur se termine en erreur +incrémente ses échecs (une annulation locale n'est pas un échec). Les noms sont comptés un à un jusqu'à 1 024 ; les +appels des noms suivants sont comptés ensemble, pour qu'une application qui fabrique ses noms ne fasse pas croître la +table sans borne. Avant le montage de l'environnement, et en distribution, aucun appel n'est compté. + +**Pages.** Trois fonctions réservées, soumises au prédicat de la section 2, rendent des pages bornées comme celles de +la section 3 (au plus 1 000 lignes, réduites à `responseBudget`, chaque ligne bornée de sorte qu'une page d'une ligne +tienne dans `minPageBytes`) : + +- `webfront.inspector.functions(après, nombre)` rend `(lignes, suivant)`. Une ligne est le tuple `(identifiant, nom, + signature, fichier:ligne, espace, drapeaux, appels, échecs, dernière erreur, durée moyenne en ms, durée maximale en + ms)` ; les drapeaux valent 1 (reçoit l'appelant), 2 (réponse différée), 4 (au moins un appel mesuré : sans ce bit les + durées ne signifient rien). Le curseur est l'identifiant de la dernière ligne servie, stable sous les retraits ; +- `webfront.inspector.jsFunctions(après, nombre)` rend `(lignes, suivant)`, une ligne étant `(identifiant, nom, appels, + échecs des appels typés)` ; +- `webfront.inspector.browsers(à partir de, nombre)` rend `(lignes, suivant, tâches)`. Une ligne est `(identifiant, + drapeaux, chemin, espace, écritures en attente, résultats attendus d'appels typés de C++, appels du navigateur sans + réponse)` ; les drapeaux valent 1 (vue prouvée), 2 (client local, `isLocalClient`), 4 (démarré), 8 (fermé, en cours de + libération), 16 (la connexion qui demande). L'identifiant d'une connexion peut valoir 0 : le curseur est donc le + premier identifiant de la page suivante, 0 à la fin. `tâches` est le nombre de tâches de la portée du serveur qui ne + sont pas terminées (connexions, boucles du pont, coroutines de l'application). + +Les commandes de l'application (`Commands.hpp`) se lisent par `webfront.commands.list`, qui existe déjà et garde le +contrôle d'origine (section 2). L'application lit le même registre sans le pont par `BasicWF::registeredFunctions()`. + ### 8. Une page, trois conteneurs Les inspecteurs sont une seule page de l'environnement, `inspector.html`, qui parle à C++ par le pont. diff --git a/docs/adr/README.md b/docs/adr/README.md index c023b84a..6d3100cf 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -69,7 +69,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-024](ADR-024-tls-integre.md) | Optional integrated TLS 1.3 server | Proposed | 2026-11-21 | 1.0 | | [ADR-025](ADR-025-mcp-http-dans-l-application.md) | The application serves MCP over Streamable HTTP on its own loopback listener, with a session Bearer token, strict Host/Origin checks, per-instance discovery and no automation in distribution builds; the webfront-agent launcher is removed; amends ADR-019 | Accepted (delivery in progress) | 2026-11-21 | 1.3 — 2026-11-22 | | [ADR-026](ADR-026-configuration-mcp-persistante.md) | Stable MCP client configuration with explicit development security modes | Accepted | 2026-11-22 | 1.2 — 2026-11-22 | -| [ADR-027](ADR-027-inspecteurs-de-l-etat-de-l-application.md) | Application state inspectors in the developer environment only: reserved `webfront.inspector.*` functions refused to unproven views unless the application trusts loopback clients, tree nodes on existing bridge types with paged reads and paged differences, observer operations run whole under the application's lock or on its executor, writes only when the application provides them, one `inspector.html` page, shown in a floating window of the page and, for a detached panel only, in the first container that grants access (a native secondary window, else a system-browser tab) | Proposed | 2026-11-25 | 1.1 — 2026-11-25 | +| [ADR-027](ADR-027-inspecteurs-de-l-etat-de-l-application.md) | Application state inspectors in the developer environment only: reserved `webfront.inspector.*` functions refused to unproven views unless the application trusts loopback clients, tree nodes on existing bridge types with paged reads and paged differences, observer operations run whole under the application's lock or on its executor, writes only when the application provides them, one `inspector.html` page, shown in a floating window of the page and, for a detached panel only, in the first container that grants access (a native secondary window, else a system-browser tab); an introspectable registry of the registered C++ functions, of the JavaScript functions C++ calls and of the connected browsers, counted with relaxed atomics and timed only while an inspector reads | Proposed | 2026-11-25 | 1.2 — 2026-11-26 | Numbering follows the reading topics; milestones and individual file histories provide the chronology, which does not follow the numerical order. diff --git a/include/webfront/Broadcast.hpp b/include/webfront/Broadcast.hpp index 52d7ca85..290ef08f 100644 --- a/include/webfront/Broadcast.hpp +++ b/include/webfront/Broadcast.hpp @@ -88,6 +88,11 @@ class Broadcast { void operator()(auto&&... ts) const { msg::FunctionCall command; auto frame = detail::encodeCall(command, name, std::forward(ts)...); + // One call for the inspectors, whatever the number of browsers it reaches (ADR-027, section 7). + if constexpr (requires { webFront.jsCallCounter(name); }) { + if (const auto counter = webFront.jsCallCounter(name)) + counter->called(); + } // The sending may be deferred until a starting browser's onUIStarted handlers return: it owns what it uses. webFront.sendToStartedLinks(detail::BroadcastCall{std::move(frame).share(), name, maxPending}); } diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 24b02746..23c21eac 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -224,6 +224,25 @@ class DeveloperAppWithNetwork : public BasicWFpage(revision, after, count, inspect::responseBudget); }); + // What the application registered and runs (section 7): pages of rows, each within the answer's budget. + this->template reservedCppFunction( + "webfront.inspector.functions", + [functions = this->inspectedFunctions()](Caller ui, double after, double count) { + admit(ui); + return functions->page(after, count, inspect::responseBudget); + }); + this->template reservedCppFunction( + "webfront.inspector.jsFunctions", + [calls = this->inspectedJsCalls()](Caller ui, double after, double count) { + admit(ui); + return calls->page(after, count, inspect::responseBudget); + }); + this->template reservedCppFunction( + "webfront.inspector.browsers", + [this](Caller ui, double from, double count) { + admit(ui); + return inspect::browserPage(this->inspectedBrowsers(ui), from, count, this->inspectedTasks(), inspect::responseBudget); + }); // A secondary window of the panel for the host page, with the proof of the view (section 8); opening it again brings it to the front. // The window is opened on the interface thread, where openSecondaryWindow() does not hold the server's thread. this->template reservedCppFunction, Caller, std::string, std::string, double, double>( diff --git a/include/webfront/Introspection.hpp b/include/webfront/Introspection.hpp new file mode 100644 index 00000000..80ed0202 --- /dev/null +++ b/include/webfront/Introspection.hpp @@ -0,0 +1,763 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-26 +// +// WebFront — core +// Role: What an application registered and runs, kept for the inspectors (ADR-027, section 7): C++ functions, JavaScript calls, browsers. +// Thread: thread-safe | Alloc: heap-init +// LLM: internal; the counters are relaxed atomics on the call path, read the cost notes before adding work there + +#pragma once + +#include "Watches.hpp" +#include "weblink/Messages.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::inspect { + +/// False in a distribution build (WEBFRONT_DISTRIBUTION): nothing is recorded there, and no call is counted. +#if defined(WEBFRONT_DISTRIBUTION) && WEBFRONT_DISTRIBUTION +inline constexpr bool introspection = false; +#else +inline constexpr bool introspection = true; +#endif + +/// A signature is written in at most this many bytes; a longer one ends with "…". +inline constexpr std::size_t maxSignatureBytes = 512; +/// The names of the JavaScript functions that C++ calls are counted one by one up to this many; the calls of the names +/// that follow are counted together, so that an application that builds its names cannot grow the table without bound. +inline constexpr std::size_t maxJsFunctionNames = 1024; +/// A duration is measured while an inspector read the functions less than this long ago. +inline constexpr std::chrono::seconds timingWindow{5}; + +// --- TypeScript names ------------------------------------------------------------------------------------------ + +namespace detail { +template +struct typescript_tuple : std::false_type { }; + +template +[[nodiscard]] std::string typescriptName(); + +template +struct typescript_tuple> : std::true_type { + static std::string write() { + std::string text = "["; + static_cast(((text += (text.size() > 1 ? ", " : "") + typescriptName()), ...)); + return text + "]"; + } +}; +template +struct typescript_tuple> : typescript_tuple> { }; + +template +[[nodiscard]] constexpr std::string_view typedArrayName() noexcept { + using E = std::remove_cv_t; + if constexpr (std::is_same_v) + return "Uint8Array"; + else if constexpr (std::is_same_v) + return "Int8Array"; + else if constexpr (std::is_same_v) + return "Uint16Array"; + else if constexpr (std::is_same_v) + return "Int16Array"; + else if constexpr (std::is_same_v) + return "Uint32Array"; + else if constexpr (std::is_same_v) + return "Int32Array"; + else if constexpr (std::is_same_v) + return "BigUint64Array"; + else if constexpr (std::is_same_v) + return "BigInt64Array"; + else if constexpr (std::is_same_v) + return "Float32Array"; + else + return "Float64Array"; +} + +template +[[nodiscard]] std::string typescriptName() { + using U = std::remove_cvref_t; + if constexpr (std::is_void_v) + return "void"; + else if constexpr (std::is_same_v) + return "boolean"; + else if constexpr (std::is_arithmetic_v) + return "number"; + else if constexpr (std::is_convertible_v) + return "string"; + else if constexpr (msg::is_bitset_v) + return "Uint8Array"; + else if constexpr (msg::is_numeric_array_v) + return std::string{typedArrayName>()}; + else if constexpr (typescript_tuple::value) + return typescript_tuple::write(); + else if constexpr (msg::is_vector_v) + return typescriptName() + "[]"; + else + return "unknown"; +} +} // namespace detail + +/** + * The TypeScript type that JavaScript gives or receives for the C++ type T on the bridge: `boolean`, `number`, `string`, + * the typed array of a vector, array or span of numbers (`Uint8Array` for a `std::bitset`, packed), `[A, B]` for a tuple + * or a pair, `T[]` for a list, `void`, and `unknown` for a type the bridge does not carry. + */ +template +[[nodiscard]] std::string typescriptType() { + return detail::typescriptName(); +} + +/// The signature of a function as a page declares it: `(a: number, b: string) => Promise`. A call from JavaScript +/// always returns a Promise, also for a function that returns nothing. +[[nodiscard]] inline std::string typescriptSignature(const std::vector& parameters, std::string_view result) { + std::string text = "("; + for (std::size_t i = 0; i < parameters.size(); ++i) { + if (i != 0) + text += ", "; + // a, b, ... z, then a1, b1, ...: a name the declaration needs and the C++ signature does not give + text += static_cast('a' + i % 26); + if (i >= 26) + text += std::to_string(i / 26); + text += ": " + parameters[i]; + } + return boundedText(text + ") => Promise<" + std::string(result) + ">", maxSignatureBytes); +} + +// --- Numbers of a page ----------------------------------------------------------------------------------------- + +namespace detail { +/// A cursor or a count given by a page: a whole number from 0 to 2^53, else std::invalid_argument. +[[nodiscard]] inline std::uint64_t pageNumber(double value, std::string_view what) { + if (!std::isfinite(value) || value < 0 || value > maxExactNumber || std::trunc(value) != value) + throw std::invalid_argument("The inspectors' " + std::string(what) + " must be a whole number from 0 to 2^53"); + return static_cast(value); +} + +/// The bytes an encoded string takes at most: its header (a 16-bit length for these bounded texts) and its bytes. +[[nodiscard]] constexpr std::size_t encodedText(std::size_t bytes) noexcept { + return 3 + bytes; +} +inline constexpr std::size_t encodedNumber = 9; +inline constexpr std::size_t encodedTuple = 2; +/// What a page may give to its rows: the budget without the answer's header. +[[nodiscard]] constexpr std::size_t rowsRoom(std::size_t budget) noexcept { + return budget > responseHeaderBytes ? budget - responseHeaderBytes : 0; +} +} // namespace detail + +// --- C++ functions --------------------------------------------------------------------------------------------- + +/** + * @brief Whether the durations of the calls are measured: only while an inspector reads the functions, so that an + * application nobody inspects reads no clock on a call. A read opens the gate for timingWindow; the first call after the + * window, which reads the clock anyway, closes it. + */ +class TimingGate { +public: + using Clock = std::chrono::steady_clock; + + /// An inspector read the functions: the calls are timed for `window` from now. + void observe(Clock::duration window = timingWindow) noexcept { + until.store((Clock::now() + window).time_since_epoch().count(), std::memory_order_relaxed); + open.store(true, std::memory_order_relaxed); + } + + /// The start of a call to time, or nothing when no inspector is reading: one relaxed load in that case. + [[nodiscard]] std::optional begin() noexcept { + if (!open.load(std::memory_order_relaxed)) + return std::nullopt; + const auto now = Clock::now(); + if (now.time_since_epoch().count() > until.load(std::memory_order_relaxed)) { + // A read that opens the gate at this very moment may be undone: its next read, a period later, opens it again. + open.store(false, std::memory_order_relaxed); + return std::nullopt; + } + return now; + } + + [[nodiscard]] bool isOpen() const noexcept { + return open.load(std::memory_order_relaxed); + } + +private: + std::atomic open{false}; + std::atomic until{0}; +}; + +/// What is kept of one registered C++ function: what it is, and what happened to its calls. Owned by its handler: the +/// record of a function that is released (a space's, with its space) goes with it. +struct FunctionRecord { + std::uint64_t id = 0; + std::string name; // as it was registered + std::string label; // the name as the inspectors show it (boundedText) + std::string signature; // TypeScript, bounded + std::string location; // "file:line" of the registration, bounded + std::string scope; // the path of the space that owns it, empty for the application's + bool takesCaller = false; // its first parameter is the calling UI + bool deferred = false; // it returns a sender (a ResultTask): the answer comes when it completes + std::shared_ptr gate; + + std::atomic calls{0}; + std::atomic failures{0}; + + /// The durations measured so far, read as one state: their number, their sum and the longest. + struct Durations { + std::uint64_t count = 0; + std::uint64_t totalNanoseconds = 0; + std::uint64_t maxNanoseconds = 0; + }; + + /// The record itself, kept alive: what a call answered later holds until its answer, so that its measure outlives a + /// function released meanwhile without keeping that function registered. Null once the record is being destroyed. + [[nodiscard]] std::shared_ptr keep() const noexcept { + return storage.lock(); + } + + /// A call failed: counted, and its message kept, bounded and made visible. Never throws. + void fail(std::string_view message) noexcept { + failures.fetch_add(1, std::memory_order_relaxed); + try { + auto text = boundedText(message); + std::scoped_lock lock{errorMutex}; + error = std::move(text); + } catch (...) { } // without memory for the message, the count alone tells the failure + } + + /// A call was timed. Only the calls made while an inspector reads come here: the lock is not on the path of the others. + void timed(TimingGate::Clock::duration duration) noexcept { + const auto nanoseconds = static_cast(std::max(0, std::chrono::duration_cast(duration).count())); + std::scoped_lock lock{durationMutex}; + ++measured.count; + measured.totalNanoseconds += nanoseconds; + measured.maxNanoseconds = std::max(measured.maxNanoseconds, nanoseconds); + } + + [[nodiscard]] Durations durations() const { + std::scoped_lock lock{durationMutex}; + return measured; + } + + [[nodiscard]] std::string lastError() const { + std::scoped_lock lock{errorMutex}; + return error; + } + +private: + friend class FunctionRegistry; + std::weak_ptr storage; // set by the registry that created the record + mutable std::mutex errorMutex; + std::string error; + mutable std::mutex durationMutex; + Durations measured; +}; + +/** + * @brief One call of a registered function: counted when it starts, timed until it ends when an inspector is reading. + * Without a record (a distribution build, a function of WebFront's own inspectors) it does nothing. Move-only, so that a + * call answered later carries it to its answer. + */ +class CallMeasure { +public: + CallMeasure() = default; + /// A call that ends before its handler returns: the handler owns the record meanwhile, and the measure shares nothing + /// (no reference count is touched on the call path). + explicit CallMeasure(FunctionRecord* function) noexcept : record(function) { + begin(); + } + /// A call answered later: the measure keeps the record until the answer, even if the function is released meanwhile. + explicit CallMeasure(std::shared_ptr function) noexcept : record(function.get()), owner(std::move(function)) { + begin(); + } + CallMeasure(CallMeasure&& other) noexcept + : record(std::exchange(other.record, nullptr)), owner(std::move(other.owner)), start(std::exchange(other.start, std::nullopt)) { } + CallMeasure& operator=(CallMeasure&& other) noexcept { + if (this != &other) { + finish(); + record = std::exchange(other.record, nullptr); + owner = std::move(other.owner); + start = std::exchange(other.start, std::nullopt); + } + return *this; + } + CallMeasure(const CallMeasure&) = delete; + CallMeasure& operator=(const CallMeasure&) = delete; + ~CallMeasure() { + finish(); + } + + /// The call failed with this message (an exception's, or what stopped it). + void failed(std::string_view message) const noexcept { + if (record) + record->fail(message); + } + +private: + void begin() noexcept { + if (!record) + return; + record->calls.fetch_add(1, std::memory_order_relaxed); + if (record->gate) + start = record->gate->begin(); + } + + void finish() noexcept { + if (record && start) + record->timed(TimingGate::Clock::now() - *start); + record = nullptr; + owner.reset(); + start.reset(); + } + + FunctionRecord* record = nullptr; + std::shared_ptr owner; + std::optional start; +}; + +/// A registered function as the application reads it (BasicWF::registeredFunctions): a copy, taken at one moment. +struct FunctionInfo { + std::uint64_t id = 0; + std::string name; // exactly as it was registered + std::string label; // the name as the inspectors show it: control characters visible, 256 bytes at most + std::string signature; + std::string location; + std::string scope; + bool takesCaller = false; + bool deferred = false; + std::uint64_t calls = 0; + std::uint64_t failures = 0; + std::string lastError; + std::uint64_t timedCalls = 0; + std::chrono::nanoseconds totalDuration{0}; + std::chrono::nanoseconds maxDuration{0}; +}; + +/// The bits of a function's flags, in a row of webfront.inspector.functions. +namespace function_flag { +inline constexpr unsigned takesCaller = 1; // receives the calling UI: it can check ui.isLocalClient() (ADR-027, section 2) +inline constexpr unsigned deferred = 2; // answers when the sender it returned completes +inline constexpr unsigned timed = 4; // at least one of its calls was timed: the durations mean something +} // namespace function_flag + +/// A function as webfront.inspector.functions describes it: (identifier, name, signature, "file:line", space, flags, +/// calls, failures, last error, mean duration in milliseconds, longest duration in milliseconds). +using FunctionRow = std::tuple; +/// A page of functions: (rows, next). `next` is the cursor of the following page, 0 at the end. +using FunctionPage = std::tuple, double>; + +/** + * @brief The C++ functions of an application, as cppFunction registered them. A record lives as long as its handler: the + * registry only lists those that still do. Thread-safe. + */ +class FunctionRegistry { +public: + /** + * Prepares the record of a function about to be registered, without listing it: its registration is the pointer + * returned, which the function's handler keeps, and publish() lists it once the registration is accepted. The record + * leaves the table when that registration is released, whether or not an inspector ever reads (an application that + * creates and destroys spaces does not grow the table), even while a call answered later still holds the record + * through keep(): what is listed is what is registered. + */ + [[nodiscard]] std::shared_ptr + prepare(std::string_view name, std::string signature, bool takesCaller, bool deferred, const std::source_location& location, std::string_view scope = {}) { + auto data = std::make_shared(); + data->storage = data; + data->name = std::string(name); + data->label = boundedText(name); + data->signature = std::move(signature); + data->location = locationText(location); + data->scope = std::string(scope); + data->takesCaller = takesCaller; + data->deferred = deferred; + data->gate = gate; + auto* const record = data.get(); + return std::shared_ptr(record, [data = std::move(data), weak = std::weak_ptr(table)](FunctionRecord* released) { + if (const auto owner = weak.lock()) { + std::scoped_lock lock{owner->mutex}; + owner->entries.erase(released->id); + } + }); + } + + /// Lists a prepared record: the registration it describes was accepted. It gets its identifier now. + void publish(const std::shared_ptr& registration) { + std::scoped_lock lock{table->mutex}; + if (registration->id != 0) + return; + registration->id = table->nextId++; + table->entries.emplace(registration->id, registration); + } + + /// Prepares and lists a record at once. + [[nodiscard]] std::shared_ptr + add(std::string_view name, std::string signature, bool takesCaller, bool deferred, const std::source_location& location, std::string_view scope = {}) { + auto registration = prepare(name, std::move(signature), takesCaller, deferred, location, scope); + publish(registration); + return registration; + } + + /// The entries of the table: the functions registered now, and those being released at this very moment. + [[nodiscard]] std::size_t size() const { + std::scoped_lock lock{table->mutex}; + return table->entries.size(); + } + + /// The functions that are still registered, in the order of their registration. + [[nodiscard]] std::vector list() const { + std::vector functions; + for (const auto& record : alive(0)) + functions.push_back(snapshot(*record)); + return functions; + } + + /// The function registered under that name (and in that space), if it still is. + [[nodiscard]] std::optional find(std::string_view name, std::string_view scope = {}) const { + for (const auto& record : alive(0)) + if (record->name == name && record->scope == scope) + return snapshot(*record); + return std::nullopt; + } + + /** + * The page that webfront.inspector.functions(after, count) answers: the functions whose identifier is greater than + * `after`, in the order of the identifiers, at most `count` (1 000 at most) and as many as fit `budget` bytes. Reading + * it tells that an inspector is open: the calls are timed for timingWindow. Throws std::invalid_argument for a number + * that is not a whole number from 0 to 2^53. + */ + [[nodiscard]] FunctionPage page(double after, double count, std::size_t budget) const { + const auto from = detail::pageNumber(after, "cursor"); + const auto wanted = std::min(detail::pageNumber(count, "count"), maxPageCount); + const auto room = detail::rowsRoom(budget); + gate->observe(); + std::vector rows; + std::size_t used = 0; + std::uint64_t last = 0; + bool more = false; + for (const auto& record : alive(from)) { + // The row first, then its cost: what is counted is what is sent (a path made visible is longer than it was). + auto shown = row(snapshot(*record)); + const auto bytes = encodedSize(shown); + if (rows.size() == wanted || used + bytes > room) { + more = true; + break; + } + used += bytes; + last = record->id; + rows.push_back(std::move(shown)); + } + return {std::move(rows), more && last != 0 ? static_cast(last) : 0.0}; + } + + /// Opens or closes the timing as a read of the functions does, for `window` (a test closes it with a negative one). + void observe(TimingGate::Clock::duration window = timingWindow) noexcept { + gate->observe(window); + } + + [[nodiscard]] bool timing() const noexcept { + return gate->isOpen(); + } + + /// The largest number of bytes a row takes encoded: a page of one always fits minPageBytes. + static constexpr std::size_t maxRowBytes = detail::encodedTuple + 6 * detail::encodedNumber + 4 * detail::encodedText(maxTextBytes) + + detail::encodedText(maxSignatureBytes); + static_assert(maxRowBytes + responseHeaderBytes <= minPageBytes); + + [[nodiscard]] static FunctionRow row(const FunctionInfo& info) { + const auto milliseconds = [](std::chrono::nanoseconds duration) { + return std::chrono::duration(duration).count(); + }; + const unsigned flags = (info.takesCaller ? function_flag::takesCaller : 0u) | (info.deferred ? function_flag::deferred : 0u) + | (info.timedCalls != 0 ? function_flag::timed : 0u); + const double mean = info.timedCalls != 0 ? milliseconds(info.totalDuration) / static_cast(info.timedCalls) : 0.0; + return {static_cast(info.id), + info.label, + info.signature, + info.location, + boundedText(info.scope), + static_cast(flags), + static_cast(info.calls), + static_cast(info.failures), + info.lastError, + mean, + milliseconds(info.maxDuration)}; + } + +private: + /// The records still owned by a handler whose identifier is greater than `after`. One being released at this moment + /// is skipped: its release removes its entry. + [[nodiscard]] std::vector> alive(std::uint64_t after) const { + std::vector> records; + { + std::scoped_lock lock{table->mutex}; + // Room first: once a registration is held here, nothing may throw under the lock, since releasing what + // would then be its last owner takes this same lock. + records.reserve(table->entries.size()); + for (auto entry = table->entries.upper_bound(after); entry != table->entries.end(); ++entry) + if (auto record = entry->second.lock()) + records.push_back(std::move(record)); + } + return records; // released, if these were the last owners, outside the table's lock + } + + [[nodiscard]] static FunctionInfo snapshot(const FunctionRecord& record) { + FunctionInfo info; + info.id = record.id; + info.name = record.name; + info.label = record.label; + info.signature = record.signature; + info.location = record.location; + info.scope = record.scope; + info.takesCaller = record.takesCaller; + info.deferred = record.deferred; + info.calls = record.calls.load(std::memory_order_relaxed); + info.failures = record.failures.load(std::memory_order_relaxed); + info.lastError = record.lastError(); + const auto durations = record.durations(); + info.timedCalls = durations.count; + info.totalDuration = std::chrono::nanoseconds{static_cast(durations.totalNanoseconds)}; + info.maxDuration = std::chrono::nanoseconds{static_cast(durations.maxNanoseconds)}; + return info; + } + + /// An upper bound of the encoded size of a row, from the texts it holds. + [[nodiscard]] static std::size_t encodedSize(const FunctionRow& shown) noexcept { + return detail::encodedTuple + 6 * detail::encodedNumber + detail::encodedText(std::get<1>(shown).size()) + + detail::encodedText(std::get<2>(shown).size()) + detail::encodedText(std::get<3>(shown).size()) + + detail::encodedText(std::get<4>(shown).size()) + detail::encodedText(std::get<8>(shown).size()); + } + + /// Shared with the records, which remove their own entry and may outlive the registry. + struct Table { + std::mutex mutex; + std::map> entries; + std::uint64_t nextId = 1; + }; + std::shared_ptr gate = std::make_shared(); + std::shared_ptr table = std::make_shared
(); +}; + +// --- JavaScript functions called by C++ ------------------------------------------------------------------------ + +/// The calls C++ made to one JavaScript function, and those of its typed calls that failed. +struct JsCallCounter { + std::uint64_t id = 0; + std::string label; + std::atomic calls{0}; + std::atomic failures{0}; + + void called() noexcept { + calls.fetch_add(1, std::memory_order_relaxed); + } + void failed() noexcept { + failures.fetch_add(1, std::memory_order_relaxed); + } +}; + +/// A JavaScript function as webfront.inspector.jsFunctions describes it: (identifier, name, calls, failures of the typed calls). +using JsFunctionRow = std::tuple; +/// A page of JavaScript functions: (rows, next). +using JsFunctionPage = std::tuple, double>; + +/** + * @brief The JavaScript functions that C++ called (jsFunction, typed or not, jsFunctionSender, broadcast), by name. It exists + * only once the developer environment enabled the inspectors: before, and in a distribution build, no call is counted. + * A broadcast counts once, whatever the number of browsers it reaches. Thread-safe. + */ +class JsCallRegistry { +public: + /// The counter of that name, created at its first call. Past maxJsFunctionNames names, the counter of all the others. + [[nodiscard]] std::shared_ptr counter(std::string_view name) { + { + std::shared_lock lock{mutex}; + if (const auto found = byName.find(name); found != byName.end()) + return found->second; + } + std::unique_lock lock{mutex}; + if (const auto found = byName.find(name); found != byName.end()) + return found->second; + if (byName.size() >= maxJsFunctionNames) { + if (!others) + others = append("(other names)"); + return others; + } + auto created = append(boundedText(name)); + byName.emplace(std::string(name), created); + return created; + } + + /// The page that webfront.inspector.jsFunctions(after, count) answers, as FunctionRegistry::page. + [[nodiscard]] JsFunctionPage page(double after, double count, std::size_t budget) const { + const auto from = detail::pageNumber(after, "cursor"); + const auto wanted = std::min(detail::pageNumber(count, "count"), maxPageCount); + const auto room = detail::rowsRoom(budget); + std::vector rows; + std::size_t used = 0; + std::uint64_t last = 0; + bool more = false; + std::shared_lock lock{mutex}; + for (std::size_t index = static_cast(std::min(from, byId.size())); index < byId.size(); ++index) { + const auto& entry = *byId[index]; + const auto bytes = detail::encodedTuple + 3 * detail::encodedNumber + detail::encodedText(entry.label.size()); + if (rows.size() == wanted || used + bytes > room) { + more = true; + break; + } + used += bytes; + last = entry.id; + rows.emplace_back(static_cast(entry.id), + entry.label, + static_cast(entry.calls.load(std::memory_order_relaxed)), + static_cast(entry.failures.load(std::memory_order_relaxed))); + } + return {std::move(rows), more && last != 0 ? static_cast(last) : 0.0}; + } + + [[nodiscard]] std::size_t size() const { + std::shared_lock lock{mutex}; + return byId.size(); + } + +private: + std::shared_ptr append(std::string label) { + auto created = std::make_shared(); + created->id = byId.size() + 1; + created->label = std::move(label); + byId.push_back(created); + return created; + } + + mutable std::shared_mutex mutex; + std::map, std::less<>> byName; + std::vector> byId; // the identifier is the rank, from 1 + std::shared_ptr others; +}; + +/** + * @brief Where the bridge's call objects find the counters of an application: empty until the developer environment + * enables the inspectors, then the registry for good. Shared with the call objects, so that one built before the + * environment was mounted counts the calls it starts afterwards, and one that outlives the application reads nothing freed. + */ +class JsCallSource { +public: + /// Creates the registry, once; the calls made from now on are counted. + std::shared_ptr enable() { + std::scoped_lock lock{mutex}; + if (!owned) { + owned = std::make_shared(); + active.store(owned.get(), std::memory_order_release); + } + return owned; + } + + /// The counter of that name, null while nothing counts: one atomic load in that case. + [[nodiscard]] std::shared_ptr counter(std::string_view name) const { + if (auto* registry = active.load(std::memory_order_acquire)) + return registry->counter(name); + return nullptr; + } + + [[nodiscard]] std::shared_ptr registry() const { + std::scoped_lock lock{mutex}; + return owned; + } + +private: + mutable std::mutex mutex; + std::shared_ptr owned; // set once, never replaced: `active` stays valid as long as this source + std::atomic active{nullptr}; +}; + +// --- Browsers -------------------------------------------------------------------------------------------------- + +/// A connected browser, as the application knows it at one moment. +struct BrowserInfo { + std::uint64_t id = 0; + bool embeddedView = false; // it proved that it is the view of an embedded frontend + bool localClient = false; // UI::isLocalClient + bool started = false; // its onUIStarted handlers have returned + bool closed = false; // its connection closed, and is about to be released + bool caller = false; // it is the page that asks + std::string path; // UI::path + std::string space; // the path of its space, empty outside the spaces + std::size_t pendingWrites = 0; // frames queued for it and not yet written to the network + std::size_t pendingResults = 0; // typed calls of C++ whose result it has not returned + std::size_t pendingCalls = 0; // its calls that a C++ callback has not answered yet +}; + +/// The bits of a browser's flags, in a row of webfront.inspector.browsers. +namespace browser_flag { +inline constexpr unsigned embeddedView = 1; +inline constexpr unsigned localClient = 2; +inline constexpr unsigned started = 4; +inline constexpr unsigned closed = 8; +inline constexpr unsigned caller = 16; +} // namespace browser_flag + +/// A browser as webfront.inspector.browsers describes it: (identifier, flags, path, space, pending writes, pending +/// results of typed C++ calls, pending answers of C++ callbacks). +using BrowserRow = std::tuple; +/// A page of browsers: (rows, next, tasks of the server's scope). `next` is the first identifier of the following page. +using BrowserPage = std::tuple, double, double>; + +inline constexpr std::size_t maxBrowserRowBytes = detail::encodedTuple + 5 * detail::encodedNumber + 2 * detail::encodedText(maxTextBytes); +static_assert(maxBrowserRowBytes + responseHeaderBytes <= minPageBytes); + +/** + * The page that webfront.inspector.browsers(from, count) answers, from the browsers in the order of their identifiers: + * those whose identifier is at least `from` (a connection's identifier may be 0, so the cursor is the first one to serve), + * at most `count` and as many as fit `budget`. `next` is 0 at the end. + */ +[[nodiscard]] inline BrowserPage browserPage(const std::vector& browsers, double from, double count, std::size_t tasks, std::size_t budget) { + const auto first = detail::pageNumber(from, "cursor"); + const auto wanted = std::min(detail::pageNumber(count, "count"), maxPageCount); + const auto room = detail::rowsRoom(budget); + std::vector rows; + std::size_t used = 0; + double next = 0; + for (const auto& browser : browsers) { + if (browser.id < first) + continue; + const auto path = boundedText(browser.path); + const auto space = boundedText(browser.space); + const auto bytes = detail::encodedTuple + 5 * detail::encodedNumber + detail::encodedText(path.size()) + detail::encodedText(space.size()); + if (rows.size() == wanted || used + bytes > room) { + next = static_cast(browser.id); + break; + } + used += bytes; + const unsigned flags = (browser.embeddedView ? browser_flag::embeddedView : 0u) | (browser.localClient ? browser_flag::localClient : 0u) + | (browser.started ? browser_flag::started : 0u) | (browser.closed ? browser_flag::closed : 0u) + | (browser.caller ? browser_flag::caller : 0u); + rows.emplace_back(static_cast(browser.id), + static_cast(flags), + path, + space, + static_cast(browser.pendingWrites), + static_cast(browser.pendingResults), + static_cast(browser.pendingCalls)); + } + return {std::move(rows), next, static_cast(tasks)}; +} + +} // namespace webfront::inspect diff --git a/include/webfront/JsFunction.hpp b/include/webfront/JsFunction.hpp index 6541f757..ec63d5dc 100644 --- a/include/webfront/JsFunction.hpp +++ b/include/webfront/JsFunction.hpp @@ -9,6 +9,7 @@ #pragma once #include "http/WebSocket.hpp" +#include "Introspection.hpp" #include "tooling/HexDump.hpp" #include "weblink/CallFrame.hpp" #include "weblink/WebLink.hpp" @@ -43,16 +44,24 @@ class JsFunction { // A browser whose connection closed is gone: a call to it is dropped, and a typed call fails. // The link is shared while used: a release on the server thread cannot destroy it meanwhile. const auto link = webFront.findLink(webLinkId, generation); + // Counted for the inspectors while the developer environment is mounted (ADR-027, section 7); null otherwise. + std::shared_ptr counter; + if constexpr (requires { webFront.jsCallCounter(name); }) + counter = webFront.jsCallCounter(name); + if (counter) + counter->called(); if constexpr (std::is_same_v) { if (link) link->sendFrame(std::move(frame)); } else { if (!link) { + if (counter) + counter->failed(); std::promise closed; closed.set_exception(std::make_exception_ptr(detail::disconnectedError())); return closed.get_future(); } - auto [callId, result] = link->template expectResult(); + auto [callId, result] = link->template expectResult(std::move(counter)); command.setCallId(callId); if (callId != 0) link->sendFrame(std::move(frame)); diff --git a/include/webfront/JsFunctionSender.hpp b/include/webfront/JsFunctionSender.hpp index 273140d3..0712d05b 100644 --- a/include/webfront/JsFunctionSender.hpp +++ b/include/webfront/JsFunctionSender.hpp @@ -9,6 +9,7 @@ #pragma once #include "http/WebSocket.hpp" +#include "Introspection.hpp" #include "weblink/CallFrame.hpp" #include "weblink/PendingCalls.hpp" @@ -44,9 +45,11 @@ template class BrowserCallSender { using Registry = PendingCalls; using Socket = websocket::WebSocket; - std::weak_ptr pending; - std::weak_ptr socket; - std::vector payload; + std::weak_ptr pending; + std::weak_ptr socket; + std::vector payload; + std::shared_ptr counters; // where the inspectors' count of this function is found, or null + std::string name; template struct State : std::enable_shared_from_this> { @@ -70,11 +73,32 @@ class BrowserCallSender { std::exception_ptr error; msg::CallId id{}; std::optional> stopCallback; + std::shared_ptr counters; + std::string name; + std::shared_ptr counter; - State(Receiver r, std::weak_ptr calls, std::weak_ptr ws, std::vector data) - : receiver(std::move(r)), pending(std::move(calls)), socket(std::move(ws)), payload(std::move(data)) { } + State(Receiver r, + std::weak_ptr calls, + std::weak_ptr ws, + std::vector data, + std::shared_ptr source, + std::string function) + : receiver(std::move(r)), + pending(std::move(calls)), + socket(std::move(ws)), + payload(std::move(data)), + counters(std::move(source)), + name(std::move(function)) { } void start() noexcept { + // A call is made when its sender starts, not when it is built: the counter is looked for now, so that a sender + // built before the developer environment was mounted counts the calls it starts afterwards. + try { + if (counters) + counter = counters->counter(name); + } catch (...) { } // without memory for a counter, the call is made and not counted + if (counter) + counter->called(); // Completion is deferred until callback construction and dispatch are finished: // registering a previously stopped token may invoke OnStop inline. try { @@ -189,6 +213,8 @@ class BrowserCallSender { deliverValue(); break; case Outcome::error: + if (counter) + counter->failed(); ex::set_error(std::move(receiver), std::move(error)); break; case Outcome::stopped: @@ -221,16 +247,21 @@ class BrowserCallSender { using sender_concept = ex::sender_tag; using completion_signatures = typename CallCompletions::type; - BrowserCallSender(std::weak_ptr calls, std::weak_ptr ws, std::vector data) - : pending(std::move(calls)), socket(std::move(ws)), payload(std::move(data)) { } + BrowserCallSender(std::weak_ptr calls, + std::weak_ptr ws, + std::vector data, + std::shared_ptr source = {}, + std::string function = {}) + : pending(std::move(calls)), socket(std::move(ws)), payload(std::move(data)), counters(std::move(source)), name(std::move(function)) { } template auto connect(Receiver receiver) && { - return Operation{std::make_shared>(std::move(receiver), pending, socket, std::move(payload))}; + return Operation{ + std::make_shared>(std::move(receiver), pending, socket, std::move(payload), std::move(counters), std::move(name))}; } template auto connect(Receiver receiver) const& { - return Operation{std::make_shared>(std::move(receiver), pending, socket, payload)}; + return Operation{std::make_shared>(std::move(receiver), pending, socket, payload, counters, name)}; } }; } // namespace webfront::detail @@ -244,10 +275,13 @@ class JsFunctionSender { std::string name; std::weak_ptr> pending; std::weak_ptr> socket; + std::shared_ptr counters; public: /// The connection of a browser that is gone leaves the references empty: started calls report an error. JsFunctionSender(std::string_view functionName, WebFront& wf, WebLinkId id, WebLinkGeneration generation) : name(functionName) { + if constexpr (requires { wf.jsCallSource(); }) + counters = wf.jsCallSource(); if (const auto link = wf.findLink(id, generation)) { pending = link->pendingResults(); socket = link->socket(); @@ -264,7 +298,7 @@ class JsFunctionSender { const auto* data = static_cast(buffers[i].data()); payload.insert(payload.end(), data, data + buffers[i].size()); } - return detail::BrowserCallSender{pending, socket, std::move(payload)}; + return detail::BrowserCallSender{pending, socket, std::move(payload), counters, name}; } }; } // namespace webfront diff --git a/include/webfront/Space.hpp b/include/webfront/Space.hpp index 2f25c3bb..e13a1786 100644 --- a/include/webfront/Space.hpp +++ b/include/webfront/Space.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -97,17 +98,25 @@ class BasicSpace { /// @throws std::invalid_argument for a name starting with `webfront.inspector.`: a space can neither hide a function of /// the inspectors from its pages nor pose as one (ADR-027, section 1) template - bool cppFunction(std::string functionName, auto&& function) { + bool cppFunction(std::string functionName, auto&& function, std::source_location location = std::source_location::current()) { if (inspect::isReservedName(functionName)) throw std::invalid_argument("webfront::BasicSpace::cppFunction(): names starting with 'webfront.inspector.' are reserved to WebFront"); - auto handler = std::make_shared(app.template makeCppHandler(std::forward(function))); - std::scoped_lock lock{state->mutex}; - return state->functions.try_emplace(std::move(functionName), std::move(handler)).second; + // The inspectors list it with the path of this space, until the space releases it (ADR-027, section 7). + const auto record = app.template recordFunction(functionName, location, state->path); + auto handler = std::make_shared(app.template makeCppHandler(std::forward(function), record)); + bool added = false; + { + std::scoped_lock lock{state->mutex}; + added = state->functions.try_emplace(std::move(functionName), std::move(handler)).second; + } + if (added) + app.publishFunction(record); // listed only once the space accepted it + return added; } /// As BasicWF::cppFunction, deducing the signature from the callable. template - bool cppFunction(std::string functionName, Function&& function) { + bool cppFunction(std::string functionName, Function&& function, std::source_location location = std::source_location::current()) { using Callable = std::remove_cvref_t; static_assert(detail::has_callable_traits, "webfront::BasicSpace::cppFunction: could not deduce this callable's signature. Generic " @@ -115,7 +124,7 @@ class BasicSpace { "cppFunction(name, callable)."); using Traits = detail::callable_traits; using Args = typename detail::caller_aware_args::type; - return detail::ApplyArgs::invoke(*this, std::move(functionName), std::forward(function)); + return detail::ApplyArgs::invoke(*this, std::move(functionName), std::forward(function), location); } /// Whether the pages of this space reach a C++ function of that name: the space's own or the application's. diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index daa955ce..7381974a 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -16,6 +16,7 @@ #include "dom/Document.hpp" #include "frontend/Frontend.hpp" #include "http/HTTPServer.hpp" +#include "Introspection.hpp" #include "JsFunction.hpp" #include "JsFunctionSender.hpp" #include "networking/TCPNetworkingStdnet.hpp" @@ -423,8 +424,26 @@ struct ApplyArgs; template struct ApplyArgs> { template - static bool invoke(Self& self, std::string functionName, Function&& function) { - return self.template cppFunction(std::move(functionName), std::forward(function)); + static bool invoke(Self& self, std::string functionName, Function&& function, const std::source_location& location) { + return self.template cppFunction(std::move(functionName), std::forward(function), location); + } +}; + +/// The TypeScript type of what a callback that answers later resolves its Promise with: the result of a task +/// (ResultTask), the single value of another sender when its completions can be read without an environment, else `unknown`. +template +struct DeferredTypescript { + static std::string name() { + if constexpr (requires { typename deferred_value_t::type; }) + return inspect::typescriptType::type>(); + else + return "unknown"; + } +}; +template +struct DeferredTypescript> { + static std::string name() { + return inspect::typescriptType(); } }; @@ -447,17 +466,23 @@ void rejectWithBridgeCode(Link& link, msg::CallId callId, std::string_view code, link.sendFrame(makeFailureFrame(callId, makeBridgeError(code, message))); } -/// A self-contained return message carrying `value`, or the failure of its encoding (a string over the message size). +/// A self-contained return message carrying `value`; throws when the value cannot be encoded (a string over the message size). template -websocket::Frame makeValueFrame(msg::CallId callId, const Value& value) { +websocket::Frame encodeValueFrame(msg::CallId callId, const Value& value) { msg::FunctionReturn result; result.setCallId(callId); websocket::Frame frame{std::span(reinterpret_cast(result.header().data()), result.header().size())}; + if constexpr (!std::is_void_v) + result.encodeParameter(value, frame); + frame.freeze(); + return frame; +} + +/// A self-contained return message carrying `value`, or the failure of its encoding. +template +websocket::Frame makeValueFrame(msg::CallId callId, const Value& value) { try { - if constexpr (!std::is_void_v) - result.encodeParameter(value, frame); - frame.freeze(); - return frame; + return encodeValueFrame(callId, value); } catch (const std::exception& error) { return makeFailureFrame(callId, error); } @@ -473,12 +498,16 @@ websocket::Frame makeVoidFrame(msg::CallId callId) { return frame; } +/// `record`, when the function has one, counts each call and its failure, whether it comes from the arguments, from the +/// callback or from the encoding of its value (ADR-027, section 7). template -auto makeCppFunctionResponder(Callable&& callable) { - return [callable = std::forward(callable)](std::span data, auto& link, msg::CallId callId, auto&&... caller) mutable { +auto makeCppFunctionResponder(Callable&& callable, std::shared_ptr record = {}) { + return [callable = std::forward(callable), + record = std::move(record)](std::span data, auto& link, msg::CallId callId, auto&&... caller) mutable { msg::FunctionReturn result; result.setCallId(callId); - websocket::Frame frame{std::span(reinterpret_cast(result.header().data()), result.header().size())}; + websocket::Frame frame{std::span(reinterpret_cast(result.header().data()), result.header().size())}; + const inspect::CallMeasure measure{record.get()}; // the handler owns the record while it runs // A failure may come from the callback or from encoding its value (a string over the wire // limit), which can leave 'result' partly encoded: failures are sent in a fresh message. try { @@ -490,8 +519,10 @@ auto makeCppFunctionResponder(Callable&& callable) { frame.freeze(); } } catch (const std::exception& error) { + measure.failed(error.what()); frame = makeFailureFrame(callId, error); } catch (...) { + measure.failed("Unknown C++ exception"); frame = makeFailureFrame(callId, std::runtime_error{"Unknown C++ exception"}); } if (callId != 0) @@ -1065,7 +1096,8 @@ class BasicWF { /// inspectors' callbacks are WebFront's or none (ADR-027, section 1). template void reservedCppFunction(std::string functionName, auto&& function) { - if (!registerCppFunction(functionName, std::forward(function))) + // No record: the inspectors do not list their own functions, whose calls would be those of the inspector itself. + if (!cppFunctions.try_emplace(functionName, makeCppHandler(std::forward(function))).second) throw std::logic_error("webfront: the reserved function " + functionName + " is already registered"); } @@ -1216,13 +1248,14 @@ class BasicWF { * @tparam Args parameters of the CppFunction * @param functionName * @param function + * @param location where the function is registered, which the inspectors show (ADR-027, section 7): leave its default * @return false when a function of that name was already registered, which stays registered * @throws std::invalid_argument for a name starting with `webfront.inspector.`, reserved to WebFront (ADR-027) */ template - bool cppFunction(std::string functionName, auto&& function) { + bool cppFunction(std::string functionName, auto&& function, std::source_location location = std::source_location::current()) { refuseReservedName(functionName); - return registerCppFunction(std::move(functionName), std::forward(function)); + return registerCppFunction(std::move(functionName), std::forward(function), location); } /** @@ -1236,11 +1269,12 @@ class BasicWF { * * @param functionName * @param function + * @param location where the function is registered, which the inspectors show (ADR-027, section 7): leave its default * @return false when a function of that name was already registered, which stays registered * @throws std::invalid_argument for a name starting with `webfront.inspector.`, reserved to WebFront (ADR-027) */ template - bool cppFunction(std::string functionName, Function&& function) { + bool cppFunction(std::string functionName, Function&& function, std::source_location location = std::source_location::current()) { using Callable = std::remove_cvref_t; static_assert(detail::has_callable_traits, "webfront::BasicWF::cppFunction: could not deduce this callable's signature. Generic " @@ -1248,7 +1282,29 @@ class BasicWF { "cppFunction(name, callable)."); using Traits = detail::callable_traits; using Args = typename detail::caller_aware_args::type; - return detail::ApplyArgs::invoke(*this, std::move(functionName), std::forward(function)); + return detail::ApplyArgs::invoke(*this, std::move(functionName), std::forward(function), location); + } + + /** + * @brief The C++ functions registered now, the application's and its spaces', in the order of their registration: name, + * signature written in TypeScript, where each was registered, whether it receives the calling UI or answers later, and + * the counts of its calls (ADR-027, section 7). A copy taken at one moment; callable from any thread. The functions of + * WebFront's own inspectors (`webfront.inspector.*`) are not listed. Empty in a distribution build, which records nothing. + */ + [[nodiscard]] std::vector registeredFunctions() const { + return functionRegistry->list(); + } + + /// The counter of the calls C++ makes to the JavaScript function `functionName`, null while no inspector can read it + /// (outside the developer environment, and in a distribution build). For the bridge's own call objects. + [[nodiscard]] std::shared_ptr jsCallCounter(std::string_view functionName) const { + return jsCalls ? jsCalls->counter(functionName) : nullptr; + } + + /// Where a call object that may start its calls later finds that counter then (JsFunctionSender); null in a + /// distribution build. It stays valid after the application is gone. + [[nodiscard]] const std::shared_ptr& jsCallSource() const noexcept { + return jsCalls; } /** @@ -1291,8 +1347,45 @@ class BasicWF { } template - bool registerCppFunction(std::string functionName, auto&& function) { - return cppFunctions.try_emplace(std::move(functionName), makeCppHandler(std::forward(function))).second; + bool registerCppFunction(std::string functionName, auto&& function, const std::source_location& location) { + if (cppFunctions.contains(functionName)) + return false; + // The record is listed once the registration is accepted: nothing reads a function that is not registered. + const auto record = recordFunction(functionName, location); + const bool added = + cppFunctions.try_emplace(std::move(functionName), makeCppHandler(std::forward(function), record)).second; + if (added) + publishFunction(record); + return added; + } + + /// Lists the record of a function whose registration was accepted (null in a distribution build). + void publishFunction(const std::shared_ptr& record) { + if (record) + functionRegistry->publish(record); + } + + /// What the inspectors keep of a function about to be registered (ADR-027, section 7), owned by its handler and not + /// listed until publishFunction(): a registration that is refused, or a function released with its space, takes its + /// record with it. Null in a distribution build. `scope` is the path of the space that registers it. + template + [[nodiscard]] std::shared_ptr + recordFunction(std::string_view functionName, const std::source_location& location, std::string_view scope = {}) { + if constexpr (inspect::introspection) { + constexpr bool caller = detail::takes_caller::value; + constexpr bool deferred = detail::deferred_result; + std::vector parameters{inspect::typescriptType()...}; + if (caller) + parameters.erase(parameters.begin()); // the calling UI does not come from JavaScript + std::string result; + if constexpr (deferred) + result = detail::DeferredTypescript>::name(); + else + result = inspect::typescriptType(); + return functionRegistry->prepare(functionName, inspect::typescriptSignature(parameters, result), caller, deferred, location, scope); + } else { + return nullptr; + } } public: @@ -1645,7 +1738,7 @@ class BasicWF { /// request is admitted (DeveloperAppWithNetwork, a friend), then checked on the interface thread with isCurrentShowSession(): /// a request admitted for one run never opens or closes a window of the next one. struct ShowSession { - std::uint64_t epoch{}; + std::uint64_t epoch{}; std::optional session; }; [[nodiscard]] ShowSession currentShowSession() const { @@ -1675,9 +1768,62 @@ class BasicWF { std::scoped_lock lock{watchRegistryMutex}; if (!watchRegistry) watchRegistry = std::make_shared(); + if (jsCalls) + jsCalls->enable(); return watchRegistry; } + /// For the inspectors' functions (DeveloperAppWithNetwork): what cppFunction registered, and the calls made to JavaScript. + [[nodiscard]] const std::shared_ptr& inspectedFunctions() const noexcept { + return functionRegistry; + } + [[nodiscard]] std::shared_ptr inspectedJsCalls() const { + return jsCalls ? jsCalls->registry() : nullptr; + } + + /// The browsers connected now, in the order of their identifiers, as the inspectors show them; `caller` is the one that asks. + [[nodiscard]] std::vector inspectedBrowsers(const UI& caller) const { + struct Seen { + inspect::BrowserInfo info; + std::shared_ptr> link; + std::shared_ptr calls; + }; + std::vector seen; + { + std::scoped_lock lock{linksMutex}; + seen.reserve(webLinks.size()); + for (const auto& [id, connection] : webLinks) { + inspect::BrowserInfo info; + info.id = id; + info.embeddedView = !connection.closed && connection.viewAssociated; + info.localClient = !connection.closed && (connection.viewAssociated || (trustLoopbackClients && connection.loopbackPeer)); + info.started = connection.stage == Connection::Stage::started; + info.closed = connection.closed; + info.caller = caller == UI{const_cast(*this), id, connection.generation}; + info.path = connection.path; + info.space = connection.space ? connection.space->path : std::string{}; + seen.push_back({std::move(info), connection.link, connection.deferredCalls}); + } + } + // Outside linksMutex: each count takes the lock of what it counts. + std::vector browsers; + browsers.reserve(seen.size()); + for (auto& [info, link, calls] : seen) { + if (link) { + info.pendingWrites = link->pendingWrites(); + info.pendingResults = link->pendingResultCount(); + } + info.pendingCalls = calls ? calls->pending() : 0; + browsers.push_back(std::move(info)); + } + return browsers; + } + + /// The tasks of the server's scope that have not ended: connections, bridge loops and the application's coroutines. + [[nodiscard]] std::size_t inspectedTasks() const noexcept { + return httpServer.taskScope().activeTasks(); + } + // The constructor has already bound and listened; this thread services the queued I/O. // Launch server only once or restart if previous thread ended void startServerThread() { @@ -1818,14 +1964,14 @@ class BasicWF { /// The type-erased handler of a C++ function, as cppFunction registers it. template - CppHandler makeCppHandler(auto&& function) { + CppHandler makeCppHandler(auto&& function, std::shared_ptr record = {}) { if constexpr (detail::deferred_result) - return makeDeferredHandler(std::forward(function)); + return makeDeferredHandler(std::forward(function), std::move(record)); else if constexpr (detail::takes_caller::value) - return makeCallerHandler(std::forward(function)); + return makeCallerHandler(std::forward(function), std::move(record)); else { auto callable = detail::makeCppFunctionHandler(std::forward(function)); - auto responder = detail::makeCppFunctionResponder(std::move(callable)); + auto responder = detail::makeCppFunctionResponder(std::move(callable), std::move(record)); return [responder](std::span data, WebLink& link, msg::CallId callId, UI) mutable { responder(data, link, callId); }; @@ -1836,11 +1982,11 @@ class BasicWF { /// call is owned by the connection (its closure stops the work and drops the late answer) and by the server scope /// (shutdown stops and joins it). The answer is sent on the server context. template - CppHandler makeDeferredHandler(auto&& function) { + CppHandler makeDeferredHandler(auto&& function, std::shared_ptr record) { // Naming the value type checks the contract at registration: one value at most, one kind of value completion. using DeferredValue [[maybe_unused]] = detail::deferred_value_t; - const auto start = [this](auto invoke, WebLink& link, msg::CallId callId, UI caller) { - this->startDeferred(std::move(invoke), link, callId, caller); + const auto start = [this, record = std::move(record)](auto invoke, WebLink& link, msg::CallId callId, UI caller) { + this->startDeferred(std::move(invoke), link, callId, caller, record); }; if constexpr (detail::takes_caller::value) { auto handler = registerDeferredHandler(std::forward(function)); @@ -1875,7 +2021,7 @@ class BasicWF { /// Claims the call identifier, then calls the callback and hands the sender it returned to a task that answers when it /// completes. The claim comes first: a call refused as a duplicate, or on a closed connection, never runs the callback. template - void startDeferred(Invoke invoke, WebLink& link, msg::CallId callId, UI caller) { + void startDeferred(Invoke invoke, WebLink& link, msg::CallId callId, UI caller, const std::shared_ptr& record) { const auto [calls, generation] = deferredCallsOf(caller); const auto key = calls ? calls->reserve(callId) : 0; if (key == 0) { @@ -1883,21 +2029,26 @@ class BasicWF { // reception drops such a call before it gets here, and this claim is the last guard. return; } + // The call is counted now and timed until its answer: the measure goes with the task that answers. + // It holds the record, not the registration: a space that releases the function meanwhile unlists it at once. + inspect::CallMeasure measure{record ? record->keep() : nullptr}; std::optional> sender; try { sender.emplace(invoke()); } catch (const std::exception& error) { + measure.failed(error.what()); calls->finish(callId, key); if (callId != 0) link.sendFrame(detail::makeFailureFrame(callId, error)); return; } catch (...) { + measure.failed("Unknown C++ exception"); calls->finish(callId, key); if (callId != 0) link.sendFrame(detail::makeFailureFrame(callId, std::runtime_error{"Unknown C++ exception"})); return; } - const auto handle = spawn(respondLater(caller, generation, calls, callId, key, std::move(*sender))); + const auto handle = spawn(respondLater(caller, generation, calls, callId, key, std::move(*sender), std::move(measure))); if (handle.stopRequested()) { // The server refused the task (it is shutting down): it never runs, so nothing would release the identifier. calls->finish(callId, key); @@ -1930,8 +2081,13 @@ class BasicWF { /// completed stopped by something other than this call's own stop request. When that request was made (the /// connection closed, the application is stopping) nothing is sent: nobody is left to read it. template - Task - respondLater(UI caller, WebLinkGeneration generation, std::shared_ptr calls, msg::CallId callId, std::uint64_t key, Sender sender) { + Task respondLater(UI caller, + WebLinkGeneration generation, + std::shared_ptr calls, + msg::CallId callId, + std::uint64_t key, + Sender sender, + inspect::CallMeasure measure) { struct Finish { detail::DeferredCalls& calls; msg::CallId callId; @@ -1951,14 +2107,20 @@ class BasicWF { if constexpr (sizeof...(values) == 0) return detail::makeVoidFrame(callId); else - return detail::makeValueFrame(callId, values...); + // A value that cannot be encoded throws here: the call then fails as its callback's exception would, + // and is counted so, as on the path of a callback that answers at once. + return detail::encodeValueFrame(callId, values...); }); answer.emplace(co_await std::move(framed)); } catch (const std::exception& error) { + // A call stopped by its browser's disconnection or by the shutdown is a failure too: it gave no result. + measure.failed(error.what()); answer.emplace(detail::makeFailureFrame(callId, error)); } catch (...) { + measure.failed("Unknown C++ exception"); answer.emplace(detail::makeFailureFrame(callId, std::runtime_error{"Unknown C++ exception"})); } + measure = {}; // the call ends with its answer, not with this task if (token.stop_requested() || callId == 0) co_return; if (const auto link = findLink(caller.id(), generation)) @@ -1966,10 +2128,10 @@ class BasicWF { } template - CppHandler makeCallerHandler(auto&& function) { + CppHandler makeCallerHandler(auto&& function, std::shared_ptr record) { auto adapted = detail::adaptCaller(std::forward(function)); auto callable = detail::makeCppFunctionHandler(std::move(adapted)); - auto responder = detail::makeCppFunctionResponder(std::move(callable)); + auto responder = detail::makeCppFunctionResponder(std::move(callable), std::move(record)); return [responder](std::span data, WebLink& link, msg::CallId callId, UI caller) mutable { responder(data, link, callId, caller); }; @@ -1989,13 +2151,17 @@ class BasicWF { const bool ptyPagesAllowed; bool developerEnvironment = false; mutable std::mutex watchRegistryMutex; - std::shared_ptr watchRegistry; // set once by enableInspectors(), read by watch() from any thread - std::atomic launched{false}; // start() was called - std::atomic showThread{}; // the thread inside this application's Frontend::open(), if any - std::atomic showEpoch{0}; // odd while show() runs its frontend, changes at each entry and exit - std::atomic showRunning{false}; // a show() of this application is in progress - std::atomic shown{false}; // show() was called, whether or not its server still runs - mutable std::mutex linksMutex; // guards webLinks, read from any thread + std::shared_ptr watchRegistry; // set once by enableInspectors(), read by watch() from any thread + // What cppFunction registered (ADR-027, section 7); shared with the records' owners, which may outlive a registration. + std::shared_ptr functionRegistry = std::make_shared(); + // The counters of the calls to JavaScript, empty until enableInspectors(); null in a distribution build. Never replaced. + const std::shared_ptr jsCalls = inspect::introspection ? std::make_shared() : nullptr; + std::atomic launched{false}; // start() was called + std::atomic showThread{}; // the thread inside this application's Frontend::open(), if any + std::atomic showEpoch{0}; // odd while show() runs its frontend, changes at each entry and exit + std::atomic showRunning{false}; // a show() of this application is in progress + std::atomic shown{false}; // show() was called, whether or not its server still runs + mutable std::mutex linksMutex; // guards webLinks, read from any thread struct Connection { std::shared_ptr> link; WebLinkGeneration generation; diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index f8aa5e82..4a758ee3 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -522,12 +522,16 @@ struct Session { send(configuration.get(), "setWebsiteDataStore:", sharedDataStore ? sharedDataStore : send(type("WKWebsiteDataStore"), "nonPersistentDataStore")); // Hidden content otherwise suspends once its load event completes. Use the public macOS 14+ preference // so asynchronous bridge/Worker work and close requests keep progressing without a visible native window. - if (!options.visible) { + // A secondary window too: closing it hides it before its view is released, and an occluded one is inactive all + // along; suspended, its page would not end when the view is released, and its connection would outlive the window. + if (!options.visible || secondary) { const auto preferences = send(configuration.get(), "preferences"); const auto selector = sel_registerName("setInactiveSchedulingPolicy:"); - if (!send(preferences, "respondsToSelector:", selector)) + if (send(preferences, "respondsToSelector:", selector)) + send(preferences, "setInactiveSchedulingPolicy:", 2L); // WKInactiveSchedulingPolicyNone + else if (!options.visible) throw std::runtime_error("WKWebView: hidden sessions require macOS 14 or later (inactiveSchedulingPolicy)"); - send(preferences, "setInactiveSchedulingPolicy:", 2L); // WKInactiveSchedulingPolicyNone + // A visible secondary window on macOS 13 keeps the default policy, the only one that system has. } if (!options.launch.secret.empty()) { // At the start of every document, in the main frame only: the script itself checks the origin. @@ -1172,6 +1176,10 @@ struct WindowHooks { dispatch_get_main_queue(), nullptr, +[](void*) { + // A block of the main queue has no autorelease pool of its own: without an event, the loop's pool is not + // drained, and what the window's closure autoreleased would keep its view, hence its page and its + // connection, until the next event of the application. + Object pool(send(type("NSAutoreleasePool"), "new")); reapSecondaryWindows(); }); } @@ -1249,6 +1257,9 @@ inline void open(std::string_view address, std::string_view port, std::string_vi dispatch_get_main_queue(), &host, +[](void* context) { + // Its own pool, as for the reaping above: the work posted to the interface + // thread (closing a secondary window) releases what it autoreleased when it ends. + Object pool(send(type("NSAutoreleasePool"), "new")); static_cast(context)->drain(); }); }, diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index 4cdefb46..a4919654 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -1267,6 +1267,9 @@ class Server { networking::TaskScope& taskScope() noexcept { return tasks; } + [[nodiscard]] const networking::TaskScope& taskScope() const noexcept { + return tasks; + } /** @brief Starts an application coroutine on the server context and owns it through shutdown. */ TaskHandle startTask(Task task) { diff --git a/include/webfront/networking/Tasks.hpp b/include/webfront/networking/Tasks.hpp index d3edb303..9e400a00 100644 --- a/include/webfront/networking/Tasks.hpp +++ b/include/webfront/networking/Tasks.hpp @@ -62,17 +62,39 @@ class TaskScope { } }; + /// Counts a task from its spawn until its operation state is destroyed, as the scope tracks it: it lives in the + /// task's sender. Move-only. + class Counted { + public: + explicit Counted(std::atomic& active) noexcept : count(&active) { + count->fetch_add(1, std::memory_order_relaxed); + } + Counted(Counted&& other) noexcept : count(std::exchange(other.count, nullptr)) { } + Counted(const Counted&) = delete; + Counted& operator=(const Counted&) = delete; + Counted& operator=(Counted&&) = delete; + ~Counted() { + if (count) + count->fetch_sub(1, std::memory_order_relaxed); + } + void operator()() const noexcept { } + + private: + std::atomic* count; + }; + ex::counting_scope tasks; using JoinOperation = ex::connect_result_t().join())), Joined>; std::atomic_bool joined{false}; std::unique_ptr joining; // A connection has its own stop source. This token links it to server shutdown // using standard stop callbacks, without relying on an implementation's fused tokens. - ex::inplace_stop_source stopSource; - std::mutex spawningMutex; - std::condition_variable spawningFinished; - std::size_t activeSpawns = 0; - bool closed = false; + ex::inplace_stop_source stopSource; + std::mutex spawningMutex; + std::condition_variable spawningFinished; + std::size_t activeSpawns = 0; + bool closed = false; + std::atomic running{0}; public: /** @brief Prevents any further task from associating with this scope. */ @@ -92,9 +114,15 @@ class TaskScope { // spawn associates synchronously. Observe that decision so a close // racing this call cannot leave the caller with an apparently live handle. bool associated = false; - ex::spawn(std::move(sender), SpawnToken{tasks.get_token(), &associated}); + ex::spawn(ex::then(std::move(sender), Counted{running}), SpawnToken{tasks.get_token(), &associated}); return associated; } + + /// The tasks spawned in this scope whose operation has not been destroyed yet: what a join would wait for. A count + /// read at one moment, for diagnostics (the inspectors, ADR-027). + [[nodiscard]] std::size_t activeTasks() const noexcept { + return running.load(std::memory_order_relaxed); + } /** @brief Cancels all associated tasks and each connection linked to this scope. */ void requestStop() noexcept { stopSource.request_stop(); diff --git a/include/webfront/weblink/PendingCalls.hpp b/include/webfront/weblink/PendingCalls.hpp index 19d928da..8138ad50 100644 --- a/include/webfront/weblink/PendingCalls.hpp +++ b/include/webfront/weblink/PendingCalls.hpp @@ -140,6 +140,12 @@ class PendingCalls { } } + /// The calls whose result the browser has not returned yet (a cancelled call counts until its late reply). + [[nodiscard]] std::size_t size() const { + std::lock_guard lock(mutex); + return pending.size(); + } + private: // The wire reserves zero for calls without a result, including at counter wrap. msg::CallId takeNextId() noexcept { @@ -149,7 +155,7 @@ class PendingCalls { return candidate; } - std::mutex mutex; + mutable std::mutex mutex; std::map pending; msg::CallId nextCallId{1}; bool closed{}; diff --git a/include/webfront/weblink/WebLink.hpp b/include/webfront/weblink/WebLink.hpp index f6a926db..e138419f 100644 --- a/include/webfront/weblink/WebLink.hpp +++ b/include/webfront/weblink/WebLink.hpp @@ -9,6 +9,7 @@ #pragma once #include "../http/WebSocket.hpp" +#include "../Introspection.hpp" #include "../tooling/Logger.hpp" #include "Messages.hpp" #include "PendingCalls.hpp" @@ -264,14 +265,19 @@ class WebLink { ws->writeLatest(std::move(frame), key, maxPending); } + /// `counter`, when the inspectors count the calls of that function, is told a call whose future fails (ADR-027, section 7). template - std::pair> expectResult() { + std::pair> expectResult(std::shared_ptr counter = {}) { auto promise = std::make_shared>(); auto future = promise->get_future(); msg::CallId callId{}; + const auto failed = [counter = std::move(counter)]() noexcept { + if (counter) + counter->failed(); + }; try { callId = pending->add({.complete = - [promise](const msg::FunctionReturn& result) { + [promise, failed](const msg::FunctionReturn& result) { try { if constexpr (std::is_void_v) { detail::decodeReturn(result); @@ -279,19 +285,27 @@ class WebLink { } else promise->set_value(detail::decodeReturn(result)); } catch (...) { + failed(); promise->set_exception(std::current_exception()); } }, .reject = - [promise](std::exception_ptr error) { + [promise, failed](std::exception_ptr error) { + failed(); promise->set_exception(std::move(error)); }}); } catch (...) { + failed(); promise->set_exception(std::current_exception()); } return {callId, std::move(future)}; } + /// The typed calls of C++ whose result this browser has not returned yet. + [[nodiscard]] std::size_t pendingResultCount() const { + return pending->size(); + } + auto pendingResults() const noexcept { return std::weak_ptr(pending); } diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index d7588dd6..053c5807 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -25,7 +25,8 @@ "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", "js/developer/environment/inspector-host.mjs": "bffcef61b8a5778f53adfea5096c5d5fa277868bbaa39e60142a3493210076fb", - "js/developer/environment/inspector.mjs": "b30d3cf9b0512ba5805a4b873fc11a9399813e88f728c4778116bb5b2ac3475a", + "js/developer/environment/inspector.mjs": "47d631dbc0cd3e8a4ef3c2e4883b303804694f790e87dd06799257ec3828d1a8", + "js/developer/environment/inspector-registry.mjs": "431153f7d7eb562262361f2f8eb60d8690f42cdfbf5ed9586270270d9e2b6038", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", @@ -53,7 +54,7 @@ "js/developer/tools/archive.mjs": "da63bb9d796ddfd24ed945b15c53f66a0400eb177886fd4f1c8fd10cafb5a91b", "js/developer/tools/distribution.mjs": "43dfdccc912693db46fd095fd78ae79325abab672d99f89fd569914ef3499cad", "js/developer/scripts/build.mjs": "a6b64a8a75c9a30118e7f5c843a0feee89ee1372ccd19b7e468c816b23fd1367", - "js/developer/webfront.project.json": "3f4966abb1b3de480ba23f1470835c727f9f2e6507299d5ef522f5c6ba009813", + "js/developer/webfront.project.json": "1c6ac7dbb4282692f3f23d3e598d00735dfc99b72d7f1072f7438d29beceb7c1", "js/core/bootstrap/bootstrap.bundle.mjs": "18a0567efa928fddbaa3f8d16a4d1e8440f21709ff2e3058d10ba406b2e9b66d", "js/developer/environment/packages.bundle.mjs": "5598a590a9e859a4128075387a6c32963b2246ca120c2d7775851c780ad437f2", "include/webfront/system/DeveloperReleaseData.hpp": "8b3c8800211c13b1984e794de6110d56238e9fb1cfb16afbc2868d57eb91c70e" diff --git a/js/developer/environment/inspector-registry.mjs b/js/developer/environment/inspector-registry.mjs new file mode 100644 index 00000000..8420ce00 --- /dev/null +++ b/js/developer/environment/inspector-registry.mjs @@ -0,0 +1,520 @@ +// The panels of the C++ registry (#681, ADR-027 section 7): the functions that the application registered with their +// signature and their activity, the JavaScript functions that C++ calls, the connected browsers, the tasks of the server's +// scope and the application's terminal commands. Each is read by pages from webfront.inspector.*, at a chosen period, and +// shown in a table that can be sorted and searched. + +// --- Rows ------------------------------------------------------------------------------------------------------ + +export const functionsFunction = 'webfront.inspector.functions'; +export const jsFunctionsFunction = 'webfront.inspector.jsFunctions'; +export const browsersFunction = 'webfront.inspector.browsers'; +export const commandsFunction = 'webfront.commands.list'; + +/** The periods the panels offer, in milliseconds; the first is the default (ADR-027: 250 ms). */ +export const periods = [250, 1000, 5000]; + +const count = value => Number.isSafeInteger(value) && value >= 0; +const duration = value => typeof value === 'number' && Number.isFinite(value) && value >= 0; +const texts = (...values) => values.every(value => typeof value === 'string'); + +/** A row of webfront.inspector.functions as an object; null when it is not one. */ +export function readFunctionRow(tuple) { + if (!Array.isArray(tuple) || tuple.length !== 11) return null; + const [id, name, signature, location, scope, flags, calls, failures, lastError, mean, longest] = tuple; + if (!count(id) || id === 0 || !texts(name, signature, location, scope, lastError) || !count(flags) || !count(calls) || !count(failures) + || !duration(mean) || !duration(longest)) return null; + const timed = (flags & 4) !== 0; + return {id, name, signature, location, scope, takesCaller: (flags & 1) !== 0, deferred: (flags & 2) !== 0, timed, calls, failures, lastError, + // Without a timed call the durations are unknown, not zero: they sort after every measured one. + mean: timed ? mean : null, longest: timed ? longest : null}; +} + +/** A row of webfront.inspector.jsFunctions as an object; null when it is not one. */ +export function readJsFunctionRow(tuple) { + if (!Array.isArray(tuple) || tuple.length !== 4) return null; + const [id, name, calls, failures] = tuple; + if (!count(id) || id === 0 || typeof name !== 'string' || !count(calls) || !count(failures)) return null; + return {id, name, calls, failures}; +} + +/** A row of webfront.inspector.browsers as an object; null when it is not one. */ +export function readBrowserRow(tuple) { + if (!Array.isArray(tuple) || tuple.length !== 7) return null; + const [id, flags, path, space, pendingWrites, pendingResults, pendingCalls] = tuple; + if (!count(id) || !count(flags) || !texts(path, space) || !count(pendingWrites) || !count(pendingResults) || !count(pendingCalls)) return null; + return {id, embeddedView: (flags & 1) !== 0, localClient: (flags & 2) !== 0, started: (flags & 4) !== 0, closed: (flags & 8) !== 0, + caller: (flags & 16) !== 0, path, space, pendingWrites, pendingResults, pendingCalls}; +} + +/** How many pages a listing reads before it gives up: a cursor that does not advance must not loop for ever. */ +export const listingPages = 1000; + +const unreadable = () => new Error('The inspectors gave a page that this environment does not read'); + +/** + * Every row of a paged function, page after page: `name(cursor, 200)` answers `[rows, next, ...rest]`, and `next` is the + * cursor of the following page, 0 at the end. Resolves with `{rows, rest}`, `rest` being what the first page gave after + * its cursor (the number of tasks, for the browsers). `active()` is asked before each page: once false, the listing stops + * and resolves with null. Throws for an answer that is not a page, or whose cursor does not advance. + */ +export async function listRows(bridge, name, readRow, {active = () => true} = {}) { + const rows = []; + let cursor = 0, rest = []; + for (let page = 0; page < listingPages; ++page) { + if (!active()) return null; + const answer = await bridge.cppFunction(name)(cursor, 200); + if (!Array.isArray(answer) || answer.length < 2 || !Array.isArray(answer[0]) || !count(answer[1])) throw unreadable(); + const read = answer[0].map(readRow); + if (read.includes(null)) throw unreadable(); + rows.push(...read); + if (page === 0) rest = answer.slice(2); + const next = answer[1]; + if (next === 0) return {rows, rest}; + if (next <= cursor) throw unreadable(); + cursor = next; + } + throw unreadable(); +} + +/** The application's terminal commands, [{name, help}]; empty when it registers none (no webfront::Commands). */ +export async function listCommands(bridge) { + let json; + try { json = await bridge.cppFunction(commandsFunction)(); } + catch (error) { + if (error?.code === 'webfront.notFound') return []; + throw error; + } + const parsed = JSON.parse(json); + if (!Array.isArray(parsed)) throw unreadable(); + return parsed.filter(command => typeof command?.name === 'string').map(({name, help}) => ({name, help: typeof help === 'string' ? help : ''})); +} + +// --- Sorting, searching, formatting ---------------------------------------------------------------------------- + +/** + * `rows` sorted by `key`, ascending or descending: numbers by value, texts without regard to case, booleans false first. + * A value that is unknown (null) comes last in both directions, and rows that compare equal keep the order of their + * identifiers, so that a table whose values do not change does not move. + */ +export function sortRows(rows, key, descending = false) { + const direction = descending ? -1 : 1; + const compare = (a, b) => { + const left = a[key], right = b[key]; + if (left === null || left === undefined || right === null || right === undefined) { + if ((left ?? null) === (right ?? null)) return 0; + return (left ?? null) === null ? 1 : -1; + } + if (typeof left === 'string') return direction * left.localeCompare(right, undefined, {sensitivity: 'base', numeric: true}); + return direction * (Number(left) - Number(right)); + }; + return [...rows].sort((a, b) => compare(a, b) || a.id - b.id); +} + +/** The rows of which one of `fields` contains every word of `search`, without regard to case; all of them for an empty search. */ +export function filterRows(rows, search, fields) { + const words = search.toLowerCase().split(/\s+/).filter(Boolean); + if (!words.length) return rows; + return rows.filter(row => { + const text = fields.map(field => String(row[field] ?? '')).join('\n').toLowerCase(); + return words.every(word => text.includes(word)); + }); +} + +/** Whether a function is one of WebFront's own (the environment's callbacks, the terminal's commands, the DOM bridge). */ +export const ownFunction = name => name.startsWith('webfront.') || name.startsWith('wfDom.') || name.startsWith('wfBind.'); + +/** A duration in milliseconds as a short text: microseconds under a millisecond, seconds from a second; "–" when unknown. */ +export function formatDuration(milliseconds) { + if (milliseconds === null || milliseconds === undefined) return '–'; + if (milliseconds < 1) return `${Math.round(milliseconds * 1000)} µs`; + if (milliseconds < 10) return `${milliseconds.toFixed(2)} ms`; + if (milliseconds < 1000) return `${Math.round(milliseconds)} ms`; + return `${(milliseconds / 1000).toFixed(2)} s`; +} + +export const formatPeriod = period => period < 1000 ? `${period} ms` : `${period / 1000} s`; + +// --- Periodic reads -------------------------------------------------------------------------------------------- + +/** + * Reads at a period: `read({active})` is awaited, its result given to `onData` (unless it is null, or the poller was paused + * or stopped meanwhile), a failure to `onError`, then the next read is scheduled `period` later. One read at a time: a slow + * read delays the next one, it is never doubled. `setPeriod` applies from the next wait; `pause`, `resume`, `stop`. + */ +export function createPoller({read, onData, onError = () => {}, period = periods[0], timers = globalThis}) { + let timer = null, paused = false, stopped = false, running = null, current = period; + const active = () => !paused && !stopped; + async function once() { + const data = await read({active}); + if (active() && data !== null && data !== undefined) onData(data); + } + function run() { + running = once().catch(error => { if (active()) onError(error); }).finally(() => { + running = null; + schedule(); + }); + return running; + } + function schedule() { + if (!active() || timer !== null || running !== null) return; + timer = timers.setTimeout(() => { + timer = null; + run(); + }, current); + } + const cancel = () => { + timers.clearTimeout(timer); + timer = null; + }; + return { + get paused() { return paused; }, + get period() { return current; }, + /** Reads now, then at each period. */ + start: () => run(), + setPeriod(value) { + current = value; + if (timer !== null) { + cancel(); + schedule(); + } + }, + pause() { + paused = true; + cancel(); + }, + resume() { + if (!paused) return; + paused = false; + schedule(); + }, + stop() { + stopped = true; + cancel(); + }, + /** Resolves once the read in progress, if any, is over. */ + settled: () => running ?? Promise.resolve(), + }; +} + +// --- Tables ---------------------------------------------------------------------------------------------------- + +/** + * A table whose columns sort: `columns` are {key, label, text(row), title(row)?, numeric?, className?}. `render(rows)` + * shows the rows sorted by the chosen column, each kept by its identifier so that an update changes only the cells whose + * text changed and moves a row only when the order changes. A click on a header sorts by it, a second click reverses. + */ +export function createTable(page, {columns, caption, sort = columns[0].key, descending = false, onSort = () => {}}) { + const table = page.createElement('table'); + table.className = 'registry'; + const title = page.createElement('caption'); + title.textContent = caption; + const head = page.createElement('thead'); + const headRow = page.createElement('tr'); + const body = page.createElement('tbody'); + const headers = new Map(); + const state = {sort, descending}; + let shown = []; + const mark = () => { + for (const [key, header] of headers) + header.setAttribute('aria-sort', key === state.sort ? (state.descending ? 'descending' : 'ascending') : 'none'); + }; + for (const column of columns) { + const header = page.createElement('th'); + header.scope = 'col'; + if (column.numeric) header.className = 'numeric'; + const button = page.createElement('button'); + button.type = 'button'; + button.textContent = column.label; + button.addEventListener('click', () => { + if (state.sort === column.key) state.descending = !state.descending; + else { + state.sort = column.key; + // Counts and durations are read from the largest: that is what one looks for. + state.descending = Boolean(column.numeric); + } + mark(); + render(shown); + onSort({...state}); + }); + header.append(button); + headers.set(column.key, header); + headRow.append(header); + } + head.append(headRow); + table.append(title, head, body); + mark(); + + function render(rows) { + shown = rows; + const sorted = sortRows(rows, state.sort, state.descending); + const existing = new Map([...body.children].map(row => [row.dataset.id, row])); + const kept = new Set(sorted.map(row => String(row.id))); + for (const [id, row] of existing) if (!kept.has(id)) row.remove(); + sorted.forEach((data, index) => { + const id = String(data.id); + let row = existing.get(id); + if (!row) { + row = page.createElement('tr'); + row.dataset.id = id; + for (const column of columns) { + const cell = page.createElement('td'); + cell.className = [column.numeric ? 'numeric' : '', column.className ?? ''].join(' ').trim(); + row.append(cell); + } + } + columns.forEach((column, cell) => { + const text = column.text(data); + if (row.children[cell].textContent !== text) row.children[cell].textContent = text; + const hint = column.title?.(data) ?? ''; + if (row.children[cell].title !== hint) row.children[cell].title = hint; + }); + if (body.children[index] !== row) body.insertBefore(row, body.children[index] ?? null); + }); + } + return {element: table, render, get sort() { return {...state}; }, get rows() { return [...body.children]; }}; +} + +export const functionColumns = [ + {key: 'name', label: 'Name', text: row => row.scope ? `${row.name} (${row.scope})` : row.name, className: 'name'}, + {key: 'signature', label: 'Signature', text: row => row.signature, className: 'code'}, + {key: 'calls', label: 'Calls', text: row => String(row.calls), numeric: true}, + {key: 'failures', label: 'Failures', text: row => String(row.failures), numeric: true}, + {key: 'mean', label: 'Mean', text: row => formatDuration(row.mean), numeric: true, + title: row => row.timed ? '' : 'No call was timed: durations are measured while this panel is open'}, + {key: 'longest', label: 'Longest', text: row => formatDuration(row.longest), numeric: true}, + {key: 'takesCaller', label: 'Caller', text: row => row.takesCaller ? 'UI' : '–', + title: row => row.takesCaller ? 'Receives the calling UI: it can check ui.isLocalClient()' + : 'Does not receive the calling UI: it cannot check ui.isLocalClient()'}, + {key: 'deferred', label: 'Answer', text: row => row.deferred ? 'later' : 'at once', + title: row => row.deferred ? 'Returns a task (ResultTask): the Promise settles when it completes' : ''}, + {key: 'location', label: 'Registered at', text: row => row.location, className: 'location'}, + {key: 'lastError', label: 'Last error', text: row => row.lastError, className: 'error-text'}, +]; + +export const jsFunctionColumns = [ + {key: 'name', label: 'Name', text: row => row.name, className: 'name'}, + {key: 'calls', label: 'Calls', text: row => String(row.calls), numeric: true}, + {key: 'failures', label: 'Failures of typed calls', text: row => String(row.failures), numeric: true}, +]; + +const browserState = row => row.closed ? 'closed' : row.started ? 'started' : 'starting'; + +export const browserColumns = [ + {key: 'id', label: 'Id', text: row => row.caller ? `${row.id} (this page)` : String(row.id), numeric: true}, + {key: 'embeddedView', label: 'Kind', text: row => row.embeddedView ? 'embedded view' : 'external browser', + title: row => row.embeddedView ? 'Proved that it is a view of the application' : 'Did not prove that it is a view of the application'}, + {key: 'localClient', label: 'Local client', text: row => row.localClient ? 'yes' : 'no', + title: row => row.localClient ? 'ui.isLocalClient() is true: admitted to the inspectors and to the system services' + : 'ui.isLocalClient() is false'}, + {key: 'state', label: 'State', text: browserState}, + {key: 'path', label: 'Path', text: row => row.path, className: 'code'}, + {key: 'space', label: 'Space', text: row => row.space || '–', className: 'code'}, + {key: 'pendingWrites', label: 'Pending writes', text: row => String(row.pendingWrites), numeric: true, + title: () => 'Frames queued for this browser and not yet written to the network'}, + {key: 'pendingResults', label: 'Awaited results', text: row => String(row.pendingResults), numeric: true, + title: () => 'Typed calls of C++ (jsFunction) whose result this browser has not returned'}, + {key: 'pendingCalls', label: 'Unanswered calls', text: row => String(row.pendingCalls), numeric: true, + title: () => 'Calls of this browser that a C++ callback has not answered yet'}, +]; + +export const commandColumns = [ + {key: 'name', label: 'Command', text: row => row.name, className: 'name'}, + {key: 'help', label: 'Help', text: row => row.help}, +]; + +export const registryStyles = ` +.toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px;margin:0 0 8px} +.toolbar input[type=search]{flex:1 1 160px;min-width:0;min-height:32px;padding:0 8px;border:1px solid #46536a;border-radius:4px;background:#0f131b;color:inherit;font:inherit} +.toolbar select{min-height:32px;padding:0 6px;border:1px solid #46536a;border-radius:4px;background:#2f3a50;color:inherit;font:inherit} +.toolbar label{display:flex;align-items:center;gap:6px;color:#a9b3c4;font-size:12px} +.toolbar :focus-visible{outline:2px solid #d7fa85;outline-offset:1px} +.scroll{overflow-x:auto;margin:0 0 16px} +table.registry{border-collapse:collapse;width:100%;font-size:13px} +table.registry caption{text-align:left;font-weight:600;padding:4px 0} +table.registry th,table.registry td{padding:4px 8px;border-bottom:1px solid #2f3a50;text-align:left;vertical-align:top;white-space:nowrap} +table.registry th{position:sticky;top:0;background:#202737;padding:0} +table.registry th button{width:100%;min-height:32px;padding:0 8px;border:0;background:none;color:inherit;font:inherit;font-weight:600;text-align:inherit;cursor:pointer} +table.registry th button:focus-visible{outline:2px solid #d7fa85;outline-offset:-2px} +table.registry th[aria-sort=ascending] button::after{content:" ▲";color:#d7fa85} +table.registry th[aria-sort=descending] button::after{content:" ▼";color:#d7fa85} +table.registry .numeric{text-align:right;font-variant-numeric:tabular-nums} +table.registry .name{font-weight:600} +table.registry .code{font-family:ui-monospace,monospace;font-size:12px;color:#d7fa85} +table.registry .location{color:#a9b3c4;font-size:12px} +table.registry .error-text{color:#ffbd2e;white-space:normal;overflow-wrap:anywhere;min-width:12em} +.summary{margin:0 0 8px}`; + +// --- Panels ---------------------------------------------------------------------------------------------------- + +const periodKey = 'webfront.inspector.period'; + +/** The period this viewer chose last, among those offered; the default when none is kept or the storage is unavailable. */ +export function keptPeriod(view) { + try { + const kept = Number(view.localStorage?.getItem(periodKey)); + return periods.includes(kept) ? kept : periods[0]; + } catch { return periods[0]; } +} + +function keepPeriod(view, period) { + try { view.localStorage?.setItem(periodKey, String(period)); } + catch { /* a convenience only: the choice lasts as long as the page */ } +} + +/** The message of a failed read: why a page that is not admitted is refused, else what failed. */ +export function readFailure(error, what) { + return error?.code === 'webfront.inspector.denied' + ? 'The inspectors answer only a view of the application: this page is not admitted.' + : error?.code === 'webfront.notFound' + ? 'The WebFront library of this application does not have this inspector: update it.' + : `${what} cannot be read: ${error?.message ?? error}`; +} + +/** + * The controls shared by the panels: a search field, the period of the reads and a pause. `onSearch(text)` follows the + * field; the period and the pause drive `poller` once `attach(poller)` gave it. + */ +export function createToolbar(page, view, {onSearch, searchLabel}) { + const bar = page.createElement('div'); + bar.className = 'toolbar'; + const search = page.createElement('input'); + search.type = 'search'; + search.placeholder = searchLabel; + search.setAttribute('aria-label', searchLabel); + search.addEventListener('input', () => onSearch(search.value)); + const periodLabel = page.createElement('label'); + periodLabel.textContent = 'Refresh every '; + const period = page.createElement('select'); + period.className = 'period'; + const chosen = keptPeriod(view); + for (const value of periods) { + const option = page.createElement('option'); + option.value = String(value); + option.textContent = formatPeriod(value); + option.selected = value === chosen; + period.append(option); + } + periodLabel.append(period); + const pause = page.createElement('button'); + pause.type = 'button'; + pause.className = 'pause'; + pause.textContent = 'Pause'; + bar.append(search, periodLabel); + let poller = null; + period.addEventListener('change', () => { + const value = Number(period.value); + keepPeriod(view, value); + poller?.setPeriod(value); + }); + pause.addEventListener('click', () => { + if (!poller) return; + if (poller.paused) poller.resume(); else poller.pause(); + pause.textContent = poller.paused ? 'Resume' : 'Pause'; + }); + return {element: bar, search, period, pause, chosen, attach(value) { poller = value; }}; +} + +const scrolling = (page, table) => { + const box = page.createElement('div'); + box.className = 'scroll'; + box.append(table.element); + return box; +}; + +/** + * The panel of the functions: the C++ functions with their signature and their counters, then the JavaScript functions that + * C++ called. WebFront's own functions (the environment's callbacks, the terminal's) are hidden unless asked for. + */ +export async function showFunctionsPanel({page, view, header, body, status, bridge}) { + let search = '', own = false, failed = false, data = {functions: [], jsFunctions: []}; + const functions = createTable(page, {columns: functionColumns, caption: 'C++ functions (cppFunction)'}); + const jsFunctions = createTable(page, {columns: jsFunctionColumns, caption: 'JavaScript functions called by C++ (jsFunction)'}); + const show = () => { + const visible = own ? data.functions : data.functions.filter(row => !ownFunction(row.name)); + const found = filterRows(visible, search, ['name', 'scope', 'signature', 'location', 'lastError']); + functions.render(found); + const calls = filterRows(own ? data.jsFunctions : data.jsFunctions.filter(row => !ownFunction(row.name)), search, ['name']); + jsFunctions.render(calls); + // A failed read stays told until a read succeeds: filtering what was read earlier must not hide it. + if (failed) return; + status.classList.remove('error'); + const hidden = data.functions.length - visible.length; + status.textContent = `${found.length} of ${visible.length} C++ functions` + + (hidden ? `, ${hidden} of WebFront's own hidden` : '') + `; ${calls.length} JavaScript functions called.`; + }; + const toolbar = createToolbar(page, view, {searchLabel: 'Search the functions', onSearch: text => { search = text; show(); }}); + const ownLabel = page.createElement('label'); + const ownBox = page.createElement('input'); + ownBox.type = 'checkbox'; + ownBox.className = 'own'; + ownBox.addEventListener('change', () => { own = ownBox.checked; show(); }); + ownLabel.append(ownBox, 'WebFront\'s own functions'); + toolbar.element.append(ownLabel); + header.insertBefore(toolbar.pause, header.children[1] ?? null); + body.append(toolbar.element, scrolling(page, functions), scrolling(page, jsFunctions)); + const poller = createPoller({ + async read({active}) { + const listed = await listRows(bridge, functionsFunction, readFunctionRow, {active}); + if (!listed) return null; + const called = await listRows(bridge, jsFunctionsFunction, readJsFunctionRow, {active}); + return called && {functions: listed.rows, jsFunctions: called.rows}; + }, + onData: read => { data = read; failed = false; show(); }, + onError: error => { + failed = true; + status.classList.add('error'); + status.textContent = readFailure(error, 'The functions'); + }, + period: toolbar.chosen, + timers: view, + }); + toolbar.attach(poller); + view.addEventListener('pagehide', () => poller.stop()); + await poller.start(); + return {poller, toolbar, functions, jsFunctions, own: ownBox}; +} + +/** The panel of the browsers and the tasks: who is connected and what waits, the tasks of the server's scope, the commands. */ +export async function showBrowsersPanel({page, view, header, body, status, bridge}) { + let search = '', failed = false, data = {browsers: [], tasks: 0, commands: []}; + const browsers = createTable(page, {columns: browserColumns, caption: 'Connected browsers'}); + const commands = createTable(page, {columns: commandColumns, caption: 'Terminal commands of the application (webfront::Commands)'}); + const summary = page.createElement('p'); + summary.className = 'summary'; + const show = () => { + browsers.render(filterRows(data.browsers.map(row => ({...row, state: browserState(row)})), search, ['id', 'path', 'space', 'state'])); + // The commands have no identifier of their own: their rank in the list, which is sorted by name, is one. + commands.render(filterRows(data.commands.map((command, index) => ({...command, id: index + 1})), search, ['name', 'help'])); + summary.textContent = `${data.browsers.length} connected ${data.browsers.length === 1 ? 'browser' : 'browsers'}, ` + + `${data.tasks} running ${data.tasks === 1 ? 'task' : 'tasks'} in the server's scope, ` + + `${data.commands.length} terminal ${data.commands.length === 1 ? 'command' : 'commands'}.`; + // A failed read stays told until a read succeeds. + if (failed) return; + status.classList.remove('error'); + status.textContent = ''; + }; + const toolbar = createToolbar(page, view, {searchLabel: 'Search the browsers and the commands', onSearch: text => { search = text; show(); }}); + header.insertBefore(toolbar.pause, header.children[1] ?? null); + body.append(toolbar.element, summary, scrolling(page, browsers), scrolling(page, commands)); + const poller = createPoller({ + async read({active}) { + const listed = await listRows(bridge, browsersFunction, readBrowserRow, {active}); + if (!listed) return null; + const tasks = listed.rest[0]; + if (!count(tasks)) throw unreadable(); + return {browsers: listed.rows, tasks, commands: await listCommands(bridge)}; + }, + onData: read => { data = read; failed = false; show(); }, + onError: error => { + failed = true; + status.classList.add('error'); + status.textContent = readFailure(error, 'The browsers'); + }, + period: toolbar.chosen, + timers: view, + }); + toolbar.attach(poller); + view.addEventListener('pagehide', () => poller.stop()); + await poller.start(); + return {poller, toolbar, browsers, commands, summary}; +} diff --git a/js/developer/environment/inspector.mjs b/js/developer/environment/inspector.mjs index a024af1e..3d16167f 100644 --- a/js/developer/environment/inspector.mjs +++ b/js/developer/environment/inspector.mjs @@ -1,8 +1,10 @@ // The page of the inspectors (#680, ADR-027 section 8): inspector.html?panel= shows one panel and talks to C++ through the // bridge. In a window or a tab of its own it opens its own connection; in the floating window of a page (?frame=1) it opens // none and borrows that page's bridge, since the adapters give the proof of the view to the main frame only. The panel of the -// watches lists them by webfront.inspector.watches and follows the registrations and removals (section 3, "Découverte"). +// watches lists them by webfront.inspector.watches and follows the registrations and removals (section 3, "Découverte"). The +// panels of the functions and of the browsers are in inspector-registry.mjs (#681, section 7). import {inspectorPanels as panels, panelTitle, inspectorChannel as channelName} from './menu.mjs'; +import {showFunctionsPanel, showBrowsersPanel, registryStyles} from './inspector-registry.mjs'; // --- Bridge ---------------------------------------------------------------------------------------------------- @@ -196,8 +198,6 @@ ul.watches .location{grid-column:1/3;color:#a9b3c4;font-size:12px;overflow-wrap: ul.watches .writable{color:#8fd0ff;font-size:12px}`; const placeholders = { - 'cpp.functions': 'The functions that the application registered come with the next versions of the environment.', - 'cpp.browsers': 'The connected browsers and the running tasks come with the next versions of the environment.', 'typescript.packages': 'The tree of the locked packages comes with the next versions of the environment.', 'typescript.bridge': 'The state of the bridge in the page comes with the next versions of the environment.', }; @@ -254,7 +254,7 @@ export async function main(view = window) { page.title = `WebFront inspector: ${panelTitle(id)}`; reloadWhenRestored(view); const style = page.createElement('style'); - style.textContent = styles; + style.textContent = styles + registryStyles; page.head.append(style); const header = page.createElement('header'); const heading = page.createElement('h1'); @@ -299,6 +299,10 @@ export async function main(view = window) { attach.addEventListener('click', () => attachAgain(view, bridge, id, attachStatus, {host: params.get('host')})); } + if (id === 'cpp.functions' || id === 'cpp.browsers') { + const show = id === 'cpp.functions' ? showFunctionsPanel : showBrowsersPanel; + return {bridge, ...await show({page, view, header, body, status, bridge})}; + } if (id !== 'cpp.watches') { status.textContent = placeholders[id]; return {bridge}; diff --git a/js/developer/tools/bundle-inputs.json b/js/developer/tools/bundle-inputs.json index 999c8ca1..cdd1b0f4 100644 --- a/js/developer/tools/bundle-inputs.json +++ b/js/developer/tools/bundle-inputs.json @@ -26,6 +26,7 @@ "js/developer/environment/menu.mjs", "js/developer/environment/inspector-host.mjs", "js/developer/environment/inspector.mjs", + "js/developer/environment/inspector-registry.mjs", "js/developer/environment/inspector.html", "js/developer/environment/tarball.mjs", "js/developer/environment/commands.mjs", diff --git a/js/developer/webfront.project.json b/js/developer/webfront.project.json index 98ebdb78..d88082ec 100644 --- a/js/developer/webfront.project.json +++ b/js/developer/webfront.project.json @@ -33,6 +33,7 @@ "test/developer/specs/timers-specs.mjs", "test/developer/specs/workspace-specs.mjs", "test/developer/specs/inspector-specs.mjs", + "test/developer/specs/inspector-registry-specs.mjs", "test/developer/specs/files-specs.mjs", "test/developer/specs/dependencies-specs.mjs", "test/developer/specs/distribution-specs.mjs" diff --git a/test/developer/specs/inspector-registry-specs.mjs b/test/developer/specs/inspector-registry-specs.mjs new file mode 100644 index 00000000..0ebf24ef --- /dev/null +++ b/test/developer/specs/inspector-registry-specs.mjs @@ -0,0 +1,458 @@ +// Specs of the registry panels of the inspectors (#681, ADR-027 section 7): the rows of the functions, of the JavaScript +// calls and of the browsers, their paged reading, sorting, searching, and the periodic reads. The functions of a real +// application are read in test/web/suite/specs/webfront-specs.mjs. +import {readFunctionRow, readJsFunctionRow, readBrowserRow, listRows, listCommands, listingPages, sortRows, filterRows, ownFunction, + formatDuration, formatPeriod, periods, createPoller, createTable, functionColumns, keptPeriod, readFailure, + showFunctionsPanel, showBrowsersPanel, functionsFunction, jsFunctionsFunction, browsersFunction, + commandsFunction} from '../../../js/developer/environment/inspector-registry.mjs'; +import {main} from '../../../js/developer/environment/inspector.mjs'; + +const functionTuple = (id, name, {signature = '() => Promise', location = `app.cpp:${id}`, scope = '', flags = 0, calls = 0, failures = 0, + lastError = '', mean = 0, longest = 0} = {}) => [id, name, signature, location, scope, flags, calls, failures, lastError, mean, longest]; + +/** Timers that run only when the spec says so: `fire()` runs the pending one, `delays` are those that were asked. */ +function manualTimers() { + let pending = null, next = 1; + const delays = []; + return { + delays, + get pending() { return pending !== null; }, + setTimeout(run, delay) { + delays.push(delay); + pending = {id: next, run}; + return next++; + }, + clearTimeout(id) { if (pending?.id === id) pending = null; }, + fire() { + const {run} = pending; + pending = null; + run(); + }, + }; +} + +/** A bridge that answers each function from `answers[name](...arguments)`, and records the calls. */ +function fakeBridge(answers) { + const calls = []; + return {calls, cppFunction: name => async (...args) => { + calls.push([name, ...args]); + if (!answers[name]) throw Object.assign(new Error(`C++ function '${name}' was not found`), {code: 'webfront.notFound'}); + return answers[name](...args); + }}; +} + +/** Pages of `size` rows of `tuples`, by a cursor that is the identifier of the last row served, as C++ answers. */ +const paged = (tuples, size, ...rest) => (after, count) => { + const remaining = tuples().filter(([id]) => id > after); + const served = remaining.slice(0, Math.min(size, count)); + return [served, remaining.length > served.length ? served.at(-1)[0] : 0, ...rest]; +}; + +/** A view for a panel: the real document's elements, its own timers, storage and listeners. */ +function panelView(timers, storage = new Map()) { + const listeners = new Map(); + return { + setTimeout: (run, delay) => timers.setTimeout(run, delay), + clearTimeout: id => timers.clearTimeout(id), + localStorage: {getItem: key => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, value)}, + addEventListener: (name, handler) => listeners.set(name, handler), + listeners, + storage, + }; +} + +function panelParts() { + const header = document.createElement('header'); + header.append(document.createElement('h1')); + const body = document.createElement('main'); + const status = document.createElement('p'); + body.append(status); + return {page: document, header, body, status}; +} + +const cells = row => [...row.children].map(cell => cell.textContent); +const column = (table, index) => table.rows.map(row => row.children[index].textContent); + +describe('The registry panels of the inspectors', () => { + describe('rows', () => { + it('read a function with its flags, and leave unknown the durations that were never measured', () => { + const row = readFunctionRow(functionTuple(3, 'save', {signature: '(a: string) => Promise', location: 'app.cpp:12', scope: '/s/a/', + flags: 1 | 2 | 4, calls: 9, failures: 2, lastError: 'disk full', mean: 1.5, longest: 4})); + expect(row).toEqual({id: 3, name: 'save', signature: '(a: string) => Promise', location: 'app.cpp:12', scope: '/s/a/', + takesCaller: true, deferred: true, timed: true, calls: 9, failures: 2, lastError: 'disk full', mean: 1.5, longest: 4}); + const untimed = readFunctionRow(functionTuple(4, 'load', {calls: 3})); + expect(untimed.timed).toBeFalse(); + expect(untimed.mean).toBeNull(); + expect(untimed.longest).toBeNull(); + }); + + it('refuse what is not a row', () => { + expect(readFunctionRow(null)).toBeNull(); + expect(readFunctionRow(functionTuple(0, 'zero'))).toBeNull(); + expect(readFunctionRow(functionTuple(1, 'short').slice(0, 10))).toBeNull(); + expect(readFunctionRow(functionTuple(1, 7))).toBeNull(); + expect(readFunctionRow(functionTuple(1, 'negative', {calls: -1}))).toBeNull(); + expect(readJsFunctionRow([1, 'draw', 2])).toBeNull(); + expect(readJsFunctionRow([1, 'draw', 2, 0])).toEqual({id: 1, name: 'draw', calls: 2, failures: 0}); + expect(readBrowserRow([0, 1, '/', '', 0, 0])).toBeNull(); + }); + + it('read a browser, whose identifier may be 0', () => { + expect(readBrowserRow([0, 1 | 2 | 4 | 16, '/', '', 1, 2, 3])).toEqual({id: 0, embeddedView: true, localClient: true, started: true, + closed: false, caller: true, path: '/', space: '', pendingWrites: 1, pendingResults: 2, pendingCalls: 3}); + expect(readBrowserRow([7, 8, '/sub/', '/s/a/', 0, 0, 0])).toEqual(jasmine.objectContaining({id: 7, embeddedView: false, closed: true, space: '/s/a/'})); + }); + }); + + describe('paged reading', () => { + it('follows the cursor to the end, and keeps what the first page gives beside its rows', async () => { + const tuples = [1, 2, 3, 4, 5].map(id => functionTuple(id, `f${id}`)); + const bridge = fakeBridge({[functionsFunction]: paged(() => tuples, 2, 'rest')}); + const listed = await listRows(bridge, functionsFunction, readFunctionRow); + expect(listed.rows.map(row => row.name)).toEqual(['f1', 'f2', 'f3', 'f4', 'f5']); + expect(listed.rest).toEqual(['rest']); + expect(bridge.calls).toEqual([[functionsFunction, 0, 200], [functionsFunction, 2, 200], [functionsFunction, 4, 200]]); + }); + + it('stops when the panel is paused, having read no further', async () => { + const tuples = [1, 2, 3].map(id => functionTuple(id, `f${id}`)); + const bridge = fakeBridge({[functionsFunction]: paged(() => tuples, 1)}); + let reads = 0; + expect(await listRows(bridge, functionsFunction, readFunctionRow, {active: () => ++reads <= 2})).toBeNull(); + expect(bridge.calls.length).toBe(2); + }); + + it('refuses a page it does not read, and a cursor that does not advance', async () => { + await expectAsync(listRows(fakeBridge({[functionsFunction]: () => 'nope'}), functionsFunction, readFunctionRow)).toBeRejectedWithError(/does not read/); + await expectAsync(listRows(fakeBridge({[functionsFunction]: () => [[[1, 2]], 0]}), functionsFunction, readFunctionRow)) + .toBeRejectedWithError(/does not read/); + const stuck = fakeBridge({[functionsFunction]: () => [[functionTuple(1, 'f')], 1]}); + await expectAsync(listRows(stuck, functionsFunction, readFunctionRow)).toBeRejectedWithError(/does not read/); + expect(stuck.calls.length).toBeLessThan(listingPages); + }); + + it('lists the commands of the application, and none when it registers no command', async () => { + const bridge = fakeBridge({[commandsFunction]: () => JSON.stringify([{name: 'deploy', help: 'ships'}, {name: 'seed'}, {help: 'nameless'}])}); + expect(await listCommands(bridge)).toEqual([{name: 'deploy', help: 'ships'}, {name: 'seed', help: ''}]); + expect(await listCommands(fakeBridge({}))).toEqual([]); + const denied = fakeBridge({[commandsFunction]: () => { throw Object.assign(new Error('refused'), {code: 'webfront.inspector.denied'}); }}); + await expectAsync(listCommands(denied)).toBeRejectedWithError(/refused/); + }); + }); + + describe('sorting and searching', () => { + const rows = [ + {id: 1, name: 'beta', calls: 5, mean: 2, takesCaller: true}, + {id: 2, name: 'Alpha', calls: 50, mean: null, takesCaller: false}, + {id: 3, name: 'gamma10', calls: 5, mean: 0.5, takesCaller: true}, + {id: 4, name: 'gamma2', calls: 0, mean: null, takesCaller: false}, + ]; + const ids = sorted => sorted.map(row => row.id); + + it('sort texts without regard to case and numbers by value, in both directions', () => { + expect(ids(sortRows(rows, 'name'))).toEqual([2, 1, 4, 3]); + expect(ids(sortRows(rows, 'name', true))).toEqual([3, 4, 1, 2]); + expect(ids(sortRows(rows, 'calls', true))).toEqual([2, 1, 3, 4]); + expect(ids(sortRows(rows, 'calls'))).toEqual([4, 1, 3, 2]); + expect(ids(sortRows(rows, 'takesCaller', true))).toEqual([1, 3, 2, 4]); + }); + + it('keep the unknown durations last in both directions, and never change the rows given', () => { + expect(ids(sortRows(rows, 'mean'))).toEqual([3, 1, 2, 4]); + expect(ids(sortRows(rows, 'mean', true))).toEqual([1, 3, 2, 4]); + expect(ids(rows)).toEqual([1, 2, 3, 4]); + }); + + it('search every word in the fields given, without regard to case', () => { + const functions = [{id: 1, name: 'saveFile', signature: '(a: string) => Promise', location: 'files.cpp:3'}, + {id: 2, name: 'loadFile', signature: '() => Promise', location: 'files.cpp:9'}, + {id: 3, name: 'ping', signature: '() => Promise', location: 'net.cpp:1'}]; + const names = (search, fields = ['name', 'signature', 'location']) => filterRows(functions, search, fields).map(row => row.name); + expect(names('')).toEqual(['saveFile', 'loadFile', 'ping']); + expect(names('FILE')).toEqual(['saveFile', 'loadFile']); + expect(names('file void')).toEqual(['saveFile']); + expect(names('files.cpp', ['name'])).toEqual([]); + expect(names(' ')).toEqual(['saveFile', 'loadFile', 'ping']); + }); + + it('tell WebFront\'s own functions from the application\'s', () => { + expect(['webfront.developer.read', 'webfront.commands.list', 'wfDom.ready', 'wfBind.exchange'].every(ownFunction)).toBeTrue(); + expect(['save', 'webfrontier', 'app.webfront.x'].some(ownFunction)).toBeFalse(); + }); + + it('write a duration and a period shortly', () => { + expect(formatDuration(null)).toBe('–'); + expect(formatDuration(0.0425)).toBe('43 µs'); + expect(formatDuration(1.234)).toBe('1.23 ms'); + expect(formatDuration(125.4)).toBe('125 ms'); + expect(formatDuration(2500)).toBe('2.50 s'); + expect(periods.map(formatPeriod)).toEqual(['250 ms', '1 s', '5 s']); + }); + }); + + describe('periodic reads', () => { + it('read at once, then one period after each read ends, never two at a time', async () => { + const timers = manualTimers(); + const read = [], shown = []; + let release = null; + const poller = createPoller({read: () => { read.push(read.length); return new Promise(resolve => { release = resolve; }); }, + onData: data => shown.push(data), period: 250, timers}); + const started = poller.start(); + expect(read.length).toBe(1); + expect(timers.pending).toBeFalse(); // nothing is scheduled while a read is in progress + release('first'); + await started; + expect(shown).toEqual(['first']); + expect(timers.delays).toEqual([250]); + timers.fire(); + expect(read.length).toBe(2); + release('second'); + await poller.settled(); + expect(shown).toEqual(['first', 'second']); + poller.stop(); + }); + + it('follow the period chosen, from the wait in progress', async () => { + const timers = manualTimers(); + const poller = createPoller({read: async () => 'data', onData: () => {}, period: 250, timers}); + await poller.start(); + expect(timers.delays).toEqual([250]); + poller.setPeriod(5000); + expect(poller.period).toBe(5000); + expect(timers.delays).toEqual([250, 5000]); + timers.fire(); + await poller.settled(); + expect(timers.delays).toEqual([250, 5000, 5000]); + poller.stop(); + }); + + it('stop asking while paused, show nothing read after the pause, and ask again once resumed', async () => { + const timers = manualTimers(); + const shown = [], seen = []; + let release = null; + const poller = createPoller({read: ({active}) => new Promise(resolve => { release = () => { seen.push(active()); resolve('late'); }; }), + onData: data => shown.push(data), period: 250, timers}); + const started = poller.start(); + poller.pause(); + release(); + await started; + expect(seen).toEqual([false]); + expect(shown).toEqual([]); + expect(timers.pending).toBeFalse(); + poller.resume(); + expect(timers.pending).toBeTrue(); + poller.stop(); + expect(timers.pending).toBeFalse(); + }); + + it('report a failed read and keep reading', async () => { + const timers = manualTimers(); + const errors = [], shown = []; + let fail = true; + const poller = createPoller({read: async () => { if (fail) throw new Error('lost'); return 'back'; }, + onData: data => shown.push(data), onError: error => errors.push(error.message), period: 250, timers}); + await poller.start(); + expect(errors).toEqual(['lost']); + fail = false; + timers.fire(); + await poller.settled(); + expect(shown).toEqual(['back']); + poller.stop(); + }); + + it('say why a page that is not admitted is refused, and when the library is too old', () => { + expect(readFailure({code: 'webfront.inspector.denied'}, 'The functions')).toContain('not admitted'); + expect(readFailure({code: 'webfront.notFound'}, 'The functions')).toContain('update it'); + expect(readFailure(new Error('closed'), 'The functions')).toBe('The functions cannot be read: closed'); + }); + + it('keep the period a viewer chose, and fall back on the default', () => { + expect(keptPeriod({localStorage: {getItem: () => '1000'}})).toBe(1000); + expect(keptPeriod({localStorage: {getItem: () => '123'}})).toBe(250); + expect(keptPeriod({localStorage: {getItem: () => { throw new Error('blocked'); }}})).toBe(250); + expect(keptPeriod({})).toBe(250); + }); + }); + + describe('table', () => { + const rows = () => [1, 2, 3].map(id => readFunctionRow(functionTuple(id, ['save', 'load', 'ping'][id - 1], {calls: [5, 50, 0][id - 1]}))); + + it('sorts by the header clicked, largest first for a number, and reverses on a second click', () => { + const sorts = []; + const table = createTable(document, {columns: functionColumns, caption: 'Functions', onSort: sort => sorts.push(sort)}); + table.render(rows()); + expect(column(table, 0)).toEqual(['load', 'ping', 'save']); + const header = label => [...table.element.querySelectorAll('th')].find(th => th.textContent === label); + expect(header('Name').getAttribute('aria-sort')).toBe('ascending'); + header('Calls').querySelector('button').click(); + expect(column(table, 0)).toEqual(['load', 'save', 'ping']); + expect(header('Calls').getAttribute('aria-sort')).toBe('descending'); + expect(header('Name').getAttribute('aria-sort')).toBe('none'); + header('Calls').querySelector('button').click(); + expect(column(table, 0)).toEqual(['ping', 'save', 'load']); + expect(sorts).toEqual([{sort: 'calls', descending: true}, {sort: 'calls', descending: false}]); + }); + + it('updates the cells that changed and keeps the rows that stay', () => { + const table = createTable(document, {columns: functionColumns, caption: 'Functions'}); + table.render(rows()); + const [load, ping, save] = table.rows; + const updated = rows(); + updated[0] = readFunctionRow(functionTuple(1, 'save', {calls: 6, failures: 1, lastError: 'disk full', flags: 4, mean: 0.5, longest: 2})); + updated.splice(2, 1); // ping is gone + table.render(updated); + expect(table.rows).toEqual([load, save]); + expect(ping.isConnected || ping.parentNode).toBeFalsy(); + expect(cells(save).slice(2, 6)).toEqual(['6', '1', '500 µs', '2.00 ms']); + expect(cells(save).at(-1)).toBe('disk full'); + expect(cells(load)[4]).toBe('–'); + expect(load.children[4].title).toContain('while this panel is open'); + }); + }); + + describe('functions panel', () => { + const setup = async (tuples, calls = () => [[1, 'draw', 3, 0], [2, 'webfront.commands.output', 9, 0]]) => { + const timers = manualTimers(); + const view = panelView(timers); + const bridge = fakeBridge({[functionsFunction]: paged(tuples, 200), [jsFunctionsFunction]: paged(calls, 200)}); + const parts = panelParts(); + const panel = await showFunctionsPanel({...parts, view, bridge}); + return {timers, view, bridge, panel, ...parts}; + }; + + it('shows the application\'s functions, hides WebFront\'s own unless asked, and searches', async () => { + const tuples = () => [functionTuple(1, 'webfront.developer.read'), functionTuple(2, 'saveFile', {calls: 4}), functionTuple(3, 'ping', {calls: 9})]; + const {panel, status, body} = await setup(tuples); + expect(column(panel.functions, 0)).toEqual(['ping', 'saveFile']); + expect(column(panel.jsFunctions, 0)).toEqual(['draw']); + expect(status.textContent).toContain('2 of 2 C++ functions, 1 of WebFront\'s own hidden; 1 JavaScript functions called.'); + panel.own.checked = true; + panel.own.dispatchEvent(new Event('change')); + expect(column(panel.functions, 0)).toEqual(['ping', 'saveFile', 'webfront.developer.read']); + expect(column(panel.jsFunctions, 0)).toEqual(['draw', 'webfront.commands.output']); + panel.toolbar.search.value = 'FILE'; + panel.toolbar.search.dispatchEvent(new Event('input')); + expect(column(panel.functions, 0)).toEqual(['saveFile']); + expect(status.textContent).toContain('1 of 3 C++ functions'); + expect(body.querySelectorAll('table.registry').length).toBe(2); + panel.poller.stop(); + }); + + it('updates the values at the period chosen, which the viewer keeps', async () => { + let calls = 1; + const {panel, timers, view, bridge} = await setup(() => [functionTuple(1, 'ping', {calls})]); + expect(column(panel.functions, 2)).toEqual(['1']); + expect(timers.delays).toEqual([250]); + calls = 2; + timers.fire(); + await panel.poller.settled(); + expect(column(panel.functions, 2)).toEqual(['2']); + panel.toolbar.period.value = '1000'; + panel.toolbar.period.dispatchEvent(new Event('change')); + expect(timers.delays.at(-1)).toBe(1000); + expect(view.storage.get('webfront.inspector.period')).toBe('1000'); + calls = 3; + timers.fire(); + await panel.poller.settled(); + expect(column(panel.functions, 2)).toEqual(['3']); + // Paused, it asks nothing more; the page that hides stops it for good. + const asked = bridge.calls.length; + panel.toolbar.pause.click(); + expect(panel.toolbar.pause.textContent).toBe('Resume'); + expect(timers.pending).toBeFalse(); + panel.toolbar.pause.click(); + expect(panel.toolbar.pause.textContent).toBe('Pause'); + expect(timers.pending).toBeTrue(); + view.listeners.get('pagehide')(); + expect(timers.pending).toBeFalse(); + expect(bridge.calls.length).toBe(asked); + }); + + it('says why a page that is not admitted reads nothing', async () => { + const timers = manualTimers(); + const bridge = fakeBridge({[functionsFunction]: () => { throw Object.assign(new Error('refused'), {code: 'webfront.inspector.denied'}); }}); + const parts = panelParts(); + const panel = await showFunctionsPanel({...parts, view: panelView(timers), bridge}); + expect(parts.status.textContent).toContain('not admitted'); + expect(parts.status.classList.contains('error')).toBeTrue(); + panel.poller.stop(); + }); + + it('keeps a failed read told while the rows read earlier are searched, until a read succeeds', async () => { + let lost = false; + const tuples = () => [functionTuple(1, 'saveFile'), functionTuple(2, 'ping')]; + const timers = manualTimers(); + const bridge = fakeBridge({[functionsFunction]: (...args) => { if (lost) throw new Error('connection lost'); return paged(tuples, 200)(...args); }, + [jsFunctionsFunction]: paged(() => [], 200)}); + const parts = panelParts(); + const panel = await showFunctionsPanel({...parts, view: panelView(timers), bridge}); + lost = true; + timers.fire(); + await panel.poller.settled(); + expect(parts.status.textContent).toBe('The functions cannot be read: connection lost'); + panel.toolbar.search.value = 'ping'; + panel.toolbar.search.dispatchEvent(new Event('input')); + expect(column(panel.functions, 0)).toEqual(['ping']); + expect(parts.status.textContent).toBe('The functions cannot be read: connection lost'); + expect(parts.status.classList.contains('error')).toBeTrue(); + lost = false; + timers.fire(); + await panel.poller.settled(); + expect(parts.status.classList.contains('error')).toBeFalse(); + expect(parts.status.textContent).toContain('1 of 2 C++ functions'); + panel.poller.stop(); + }); + }); + + describe('browsers panel', () => { + it('shows the browsers, the tasks of the scope and the commands, and searches them', async () => { + const timers = manualTimers(); + const browsers = () => [[0, 1 | 2 | 4 | 16, '/', '', 0, 1, 2], [3, 4, '/sub/', '/s/alice/', 5, 0, 0]]; + const bridge = fakeBridge({ + [browsersFunction]: (from, count) => [browsers().filter(([id]) => id >= from).slice(0, count), 0, 7], + [commandsFunction]: () => JSON.stringify([{name: 'deploy', help: 'ships the project'}]), + }); + const parts = panelParts(); + const panel = await showBrowsersPanel({...parts, view: panelView(timers), bridge}); + expect(panel.summary.textContent).toBe('2 connected browsers, 7 running tasks in the server\'s scope, 1 terminal command.'); + // In the order of the identifiers; each row tells what the browser is. + expect(panel.browsers.rows.map(cells)).toEqual([ + ['0 (this page)', 'embedded view', 'yes', 'started', '/', '–', '0', '1', '2'], + ['3', 'external browser', 'no', 'started', '/sub/', '/s/alice/', '5', '0', '0'], + ]); + expect(panel.commands.rows.map(cells)).toEqual([['deploy', 'ships the project']]); + panel.toolbar.search.value = 'alice'; + panel.toolbar.search.dispatchEvent(new Event('input')); + expect(column(panel.browsers, 0)).toEqual(['3']); + expect(panel.commands.rows.length).toBe(0); + panel.poller.stop(); + }); + + it('refuses a page without the number of tasks', async () => { + const bridge = fakeBridge({[browsersFunction]: () => [[], 0]}); + const parts = panelParts(); + const panel = await showBrowsersPanel({...parts, view: panelView(manualTimers()), bridge}); + expect(parts.status.textContent).toContain('does not read'); + panel.poller.stop(); + }); + }); + + describe('page', () => { + it('shows the functions panel for inspector.html?panel=cpp.functions, with the bridge of its host in a frame', async () => { + const frame = document.createElement('iframe'); + document.body.append(frame); + try { + const timers = manualTimers(); + const bridge = Object.assign(fakeBridge({[functionsFunction]: paged(() => [functionTuple(1, 'ping', {calls: 2})], 200), + [jsFunctionsFunction]: paged(() => [], 200)}), {ready: Promise.resolve()}); + const view = {...panelView(timers), document: frame.contentDocument, parent: {webfrontInspectorHost: {bridge}}, + location: {href: 'http://localhost/webfront/developer/environment/inspector.html?panel=cpp.functions&frame=1'}}; + const shown = await main(view); + expect(frame.contentDocument.title).toBe('WebFront inspector: C++ state: Functions'); + expect([...frame.contentDocument.querySelectorAll('table.registry tbody tr')].map(row => row.children[0].textContent)).toEqual(['ping']); + expect(frame.contentDocument.querySelector('header .pause')).not.toBeNull(); + shown.poller.stop(); + } finally { frame.remove(); } + }); + }); +}); diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 8a6d1881..5cf5b6a6 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -80,7 +80,7 @@ list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServe 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 StorageTests.cpp NativeStorageTests.cpp PtyTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp ProfileLeaseTests.cpp SafePathTests.cpp UISubscribersTests.cpp) -list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp WatchTests.cpp BroadcastTests.cpp SpaceTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) +list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp WatchTests.cpp IntrospectionTests.cpp BroadcastTests.cpp SpaceTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationDiscoveryTests.cpp AutomationMcpHttpTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp HostLoopTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp DeferredCallTests.cpp) list(APPEND TESTS_LIST Main.cpp ScenarioIsolation.cpp FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp UIExecutorTests.cpp NativeWindowTests.cpp WindowRegistryTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) if(WEBFRONT_USE_MDDLOG) @@ -481,6 +481,10 @@ endforeach() add_executable(gzip_cache_benchmark EXCLUDE_FROM_ALL GzipCacheBenchmark.cpp) target_link_libraries(gzip_cache_benchmark PRIVATE WebFront_test_hardening WebFront_warnings WebFront_options WebFront) +# Manual timing evidence for the cost of the inspectors' counters on a call (ADR-027, section 7); never a timing-based test. +add_executable(introspection_benchmark EXCLUDE_FROM_ALL IntrospectionBenchmark.cpp) +target_link_libraries(introspection_benchmark PRIVATE WebFront_test_hardening WebFront_warnings WebFront_options WebFront) + add_test(NAME TransportBenchmarksAreManual COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckManualTransportBenchmarks.cmake) diff --git a/test/unit/InspectorDistribution.cpp b/test/unit/InspectorDistribution.cpp index c854f58f..2b7fba10 100644 --- a/test/unit/InspectorDistribution.cpp +++ b/test/unit/InspectorDistribution.cpp @@ -36,12 +36,23 @@ const Scenario inspectorsAbsent{"A distribution build registers no inspector fun for (const auto* name : {"webfront.inspector.containers", "webfront.inspector.embedded", "webfront.inspector.watches", + "webfront.inspector.functions", + "webfront.inspector.jsFunctions", + "webfront.inspector.browsers", "webfront.inspector.readPreferences", "webfront.inspector.savePreferences", "webfront.inspector.openWindow", "webfront.inspector.closeWindow"}) require(!app.hasCppFunction(name)); }); + then("nothing is recorded of the functions or of the calls to JavaScript", [&] { + app.cppFunction("ping", [](int value) { + return value; + }); + require(app.hasCppFunction("ping")); + require(app.registeredFunctions().empty()); + require(app.jsCallCounter("draw") == nullptr); + }); then("a watch registers nothing: its handle is empty", [&] { int value = 0; auto watch = app.watch("value", [&value]() -> const int& { diff --git a/test/unit/IntrospectionBenchmark.cpp b/test/unit/IntrospectionBenchmark.cpp new file mode 100644 index 00000000..879777f7 --- /dev/null +++ b/test/unit/IntrospectionBenchmark.cpp @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-26 +// +// WebFront — tests/unit +// Role: Benchmark of what the inspectors' registry adds to a call: the counters of a cppFunction and of a call to JavaScript. +// Thread: worker-safe | Alloc: unrestricted +// LLM: measures only; never fails on timing + +// Manual Release benchmark (ADR-027, section 7): the cost per call of the counters when no inspector is open, which is +// what every application pays, and of the timing while one is open. + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace webfront; + +constexpr std::uint64_t iterations = 20'000'000; + +/// Nanoseconds per iteration of `body`, the best of five runs. +template +double measure(Body body) { + double best = 1e300; + for (int run = 0; run < 5; ++run) { + const auto start = std::chrono::steady_clock::now(); + for (std::uint64_t i = 0; i < iterations; ++i) + body(i); + const auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + best = std::min(best, elapsed / static_cast(iterations)); + } + return best; +} + +volatile std::uint64_t sink = 0; +} // namespace + +int main() { + inspect::FunctionRegistry registry; + const auto record = registry.add("benchmark", "() => Promise", false, false, std::source_location::current()); + inspect::FunctionRecord* const none = nullptr; + + const double baseline = measure([&](std::uint64_t i) { + const inspect::CallMeasure call{none}; + sink = i; + }); + const double counted = measure([&](std::uint64_t i) { + const inspect::CallMeasure call{record.get()}; + sink = i; + }); + registry.observe(std::chrono::hours{1}); + const double timed = measure([&](std::uint64_t i) { + const inspect::CallMeasure call{record.get()}; + sink = i; + }); + + inspect::JsCallRegistry calls; + static_cast(calls.counter("draw")); + const double jsCall = measure([&](std::uint64_t i) { + calls.counter("draw")->called(); + sink = i; + }); + + std::printf("call without a record (distribution build, inspectors' own functions): %7.2f ns\n", baseline); + std::printf("call counted, no inspector open (one counter, one flag read): %7.2f ns (+%.2f ns)\n", counted, counted - baseline); + std::printf("call counted and timed, an inspector open (two clock reads): %7.2f ns (+%.2f ns)\n", timed, timed - baseline); + std::printf("call to JavaScript counted by name, developer environment mounted: %7.2f ns\n", jsCall); + return 0; +} diff --git a/test/unit/IntrospectionTests.cpp b/test/unit/IntrospectionTests.cpp new file mode 100644 index 00000000..f7640f61 --- /dev/null +++ b/test/unit/IntrospectionTests.cpp @@ -0,0 +1,669 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-26 +// +// WebFront — tests/unit +// Role: What an application registered and runs, as the inspectors read it: functions, their counters, JavaScript calls, browsers. +// Thread: bridge-io | Alloc: unrestricted +// LLM: tests of ADR-027 section 7 with the injectable networking mock; the access rules are in ViewAssociationTests.cpp + +#include "InjectableNetworking.hpp" +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace webfront::bdd; +using namespace webfront; + +namespace { + +using IntroSocket = testing::InjectableSocket; + +const std::string introUpgradeRequest = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; + +struct IntroNet : testing::InjectableNetworking { + static inline bool accepted{}; + static auto Accept(Acceptor&) { + return networking::ex::then(networking::ex::just(), []() -> Socket { + if (std::exchange(accepted, true)) + throw std::system_error(std::make_error_code(std::errc::operation_canceled)); + return Socket{}; + }); + } +}; + +using IntroApp = BasicWF; + +std::vector introGates; + +testing::ManualSender introGate() { + return testing::ManualSender([](testing::ManualSender::Completion completion) { + introGates.push_back(std::move(completion)); + }); +} + +/// Completes with a string that no message can carry: its encoding fails once the task has answered. +ResultTask introTooLong() { + co_await introGate(); + co_return std::string(http::maxMessageSize() + 1, 'x'); +} + +ResultTask introLater(std::string value) { + co_await introGate(); + co_return "later:" + value; +} + +int introTwice(int value) { + return 2 * value; +} + +/// The application with one browser, which calls its functions. +struct IntroFresh { + IntroFresh() { + IntroSocket::reset(); + introGates.clear(); + IntroNet::accepted = false; + } +}; + +struct IntroBrowser { + ~IntroBrowser() { + app.shutdown(); + IntroSocket::reset(); + introGates.clear(); + } + void connect() { + IntroSocket::receive(std::as_bytes(std::span(introUpgradeRequest))); + msg::Handshake handshake; + IntroSocket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + } + template + void call(const std::string& name, msg::CallId callId, const Arguments&... arguments) { + msg::FunctionCall<> message; + message.setCallId(callId); + websocket::Frame frame{std::span(reinterpret_cast(message.header().data()), message.header().size())}; + message.encodeParameter(name, frame); + (message.encodeParameter(arguments, frame), ...); + frame.freeze(); + IntroSocket::receive(testing::clientFrame(testing::messagePayload(frame))); + } + [[nodiscard]] inspect::FunctionInfo function(std::string_view name) const { + for (auto& info : app.registeredFunctions()) + if (info.name == name) + return info; + throw std::logic_error("No function named " + std::string(name)); + } + + IntroFresh fresh; // resets the shared mock socket before the application accepts its connection + IntroApp app{WebFrontConfig{.port = "0"}}; +}; + +} // namespace + +const Scenario introTypescriptTypes{"The types of the bridge are written as TypeScript declares them (ADR-027, section 7)", {"inspector"}, [] { + then("scalars and strings have their TypeScript names", [] { + requireEqual(inspect::typescriptType(), std::string{"void"}); + requireEqual(inspect::typescriptType(), std::string{"boolean"}); + requireEqual(inspect::typescriptType(), std::string{"number"}); + requireEqual(inspect::typescriptType(), std::string{"number"}); + requireEqual(inspect::typescriptType(), std::string{"number"}); + requireEqual(inspect::typescriptType(), std::string{"string"}); + requireEqual(inspect::typescriptType(), std::string{"string"}); + }); + then("numbers in a container are a typed array, and a bitset its packed bytes", [] { + requireEqual(inspect::typescriptType>(), std::string{"Uint8Array"}); + requireEqual(inspect::typescriptType>(), std::string{"Int32Array"}); + requireEqual(inspect::typescriptType>(), std::string{"Float32Array"}); + requireEqual(inspect::typescriptType>(), std::string{"Float64Array"}); + requireEqual(inspect::typescriptType>(), std::string{"BigUint64Array"}); + requireEqual(inspect::typescriptType>(), std::string{"Uint8Array"}); + }); + then("tuples, pairs and lists are written from their elements", [] { + requireEqual(inspect::typescriptType>(), std::string{"[number, string]"}); + requireEqual(inspect::typescriptType>(), std::string{"[boolean, number]"}); + requireEqual(inspect::typescriptType>(), std::string{"string[]"}); + requireEqual(inspect::typescriptType>>(), + std::string{"[number, string][]"}); + requireEqual(inspect::typescriptType, double>>(), + std::string{"[string[], number]"}); + }); + then("a type the bridge does not carry is unknown", [] { + struct Opaque { }; + requireEqual(inspect::typescriptType(), std::string{"unknown"}); + }); + then("a signature names its parameters and always returns a Promise", [] { + requireEqual(inspect::typescriptSignature({}, "void"), std::string{"() => Promise"}); + requireEqual(inspect::typescriptSignature({"number", "string"}, "boolean"), + std::string{"(a: number, b: string) => Promise"}); + const auto many = inspect::typescriptSignature(std::vector(27, "number"), "void"); + require(many.contains("z: number, a1: number")); + const auto bounded = inspect::typescriptSignature(std::vector(200, "Float64Array"), "void"); + require(bounded.size() <= inspect::maxSignatureBytes); + require(bounded.ends_with("\xE2\x80\xA6")); + }); + }}; + +const Scenario introMetadata{"Each registered function keeps its name, its TypeScript signature and where it was registered (ADR-027, section 7)", + {"inspector"}, + [] { + IntroBrowser browser; + auto& app = browser.app; + + given("a lambda", [&] { + const auto line = std::source_location::current().line() + 1; + app.cppFunction("add", [](int a, double b) { + return a + b; + }); + const auto info = browser.function("add"); + then("its signature is deduced", [&] { + requireEqual(info.signature, std::string{"(a: number, b: number) => Promise"}); + require(!info.takesCaller && !info.deferred); + }); + then("the file and the line of the registration are kept", [&] { + require(info.location.ends_with("IntrospectionTests.cpp:" + std::to_string(line))); + }); + }); + given("a function pointer", [&] { + app.cppFunction("twice", &introTwice); + requireEqual(browser.function("twice").signature, std::string{"(a: number) => Promise"}); + }); + given("a std::function", [&] { + app.cppFunction("greet", std::function{[](const std::string& name, bool) { + return name; + }}); + requireEqual(browser.function("greet").signature, std::string{"(a: string, b: boolean) => Promise"}); + }); + given("a function without result", [&] { + app.cppFunction("notify", [](const std::vector&, std::tuple) { }); + requireEqual(browser.function("notify").signature, std::string{"(a: string[], b: [number, string]) => Promise"}); + }); + given("a function that takes the calling UI", [&] { + app.cppFunction("whoami", [](IntroApp::UI ui, std::string) { + return static_cast(ui.id()); + }); + const auto info = browser.function("whoami"); + then("the caller is told, and is not a parameter of JavaScript", [&] { + require(info.takesCaller); + requireEqual(info.signature, std::string{"(a: string) => Promise"}); + }); + }); + given("a function that answers later", [&] { + app.cppFunction("later", &introLater); + const auto info = browser.function("later"); + then("its result is that of its task", [&] { + require(info.deferred && !info.takesCaller); + requireEqual(info.signature, std::string{"(a: string) => Promise"}); + }); + }); + given("the explicit form, for a generic lambda", [&] { + const auto line = std::source_location::current().line() + 1; + app.cppFunction>("hex", [](const auto&) { + return std::string{}; + }); + const auto info = browser.function("hex"); + then("the signature is the one given, and the location that of the call", [&] { + requireEqual(info.signature, std::string{"(a: Uint8Array) => Promise"}); + require(info.location.ends_with("IntrospectionTests.cpp:" + std::to_string(line))); + }); + }); + given("a name that is taken", [&] { + app.cppFunction("once", [] { + return 1; + }); + require(!app.cppFunction("once", [](std::string) { })); + then("the function that stays registered is the one listed, once", [&] { + const auto functions = app.registeredFunctions(); + requireEqual(std::ranges::count_if(functions, + [](const auto& info) { + return info.name == "once"; + }), + std::ptrdiff_t{1}); + requireEqual(browser.function("once").signature, std::string{"() => Promise"}); + }); + }); + }}; + +const Scenario introCounters{"The calls of a function are counted, with its failures and its last error (ADR-027, section 7)", {"inspector"}, [] { + IntroBrowser browser; + auto& app = browser.app; + app.cppFunction("twice", &introTwice); + app.cppFunction("fails", [](const std::string& reason) -> int { + throw std::runtime_error(reason); + }); + app.cppFunction("failsAtLength", []() -> int { + throw std::runtime_error(std::string{"a\nb"} + std::string(1000, 'x')); + }); + app.cppFunction("later", &introLater); + app.cppFunction("tooLong", &introTooLong); + browser.connect(); + + when("a call succeeds", [&] { + browser.call("twice", 3, 21); + browser.call("twice", 4, 4); + const auto info = browser.function("twice"); + then("it is counted, without failure", [&] { + requireEqual(info.calls, std::uint64_t{2}); + requireEqual(info.failures, std::uint64_t{0}); + require(info.lastError.empty()); + }); + then("no duration was measured: no inspector is reading", [&] { + requireEqual(info.timedCalls, std::uint64_t{0}); + }); + }); + when("the callback throws", [&] { + browser.call("fails", 5, std::string{"the disk is full"}); + const auto info = browser.function("fails"); + then("the failure and its message are kept", [&] { + requireEqual(info.calls, std::uint64_t{1}); + requireEqual(info.failures, std::uint64_t{1}); + requireEqual(info.lastError, std::string{"the disk is full"}); + }); + }); + when("the message of the failure is long and holds control characters", [&] { + browser.call("failsAtLength", 5); + const auto info = browser.function("failsAtLength"); + then("it is made visible and bounded", [&] { + require(info.lastError.size() <= inspect::maxTextBytes); + require(info.lastError.starts_with("a\xE2\x90\x8A" + "b")); + require(info.lastError.ends_with("\xE2\x80\xA6")); + }); + }); + when("the arguments cannot be decoded as the function declares them", [&] { + browser.call("twice", 6, std::string{"not a number"}); + then("the call fails before the callback", [&] { + const auto info = browser.function("twice"); + requireEqual(info.calls, std::uint64_t{1}); + requireEqual(info.failures, std::uint64_t{1}); + require(!info.lastError.empty()); + }); + }); + when("a function that answers later completes", [&] { + browser.call("later", 7, std::string{"x"}); + then("the call is counted when it starts", [&] { + requireEqual(browser.function("later").calls, std::uint64_t{1}); + requireEqual(browser.function("later").failures, std::uint64_t{0}); + }); + introGates.at(0).complete({}, 0); + then("its answer is not a failure", [&] { + require(IntroSocket::wrote("later:x")); + requireEqual(browser.function("later").failures, std::uint64_t{0}); + }); + }); + when("a function that answers later gives a value that cannot be encoded", [&] { + browser.call("tooLong", 9); + introGates.at(0).complete({}, 0); + const auto info = browser.function("tooLong"); + then("the call is rejected and counted as a failure, as for a function that answers at once", [&] { + requireEqual(info.calls, std::uint64_t{1}); + requireEqual(info.failures, std::uint64_t{1}); + require(!info.lastError.empty()); + }); + }); + when("the browser disconnects before a function answers", [&] { + browser.call("later", 8, std::string{"x"}); + IntroSocket::fail(std::make_error_code(std::errc::connection_reset)); + const auto info = browser.function("later"); + then("the call that gave no result is a failure, and its error says it was cancelled", [&] { + requireEqual(info.calls, std::uint64_t{1}); + requireEqual(info.failures, std::uint64_t{1}); + require(info.lastError.contains("cancelled")); + }); + }); + }}; + +const Scenario introTiming{"The duration of a call is measured only while an inspector reads the functions (ADR-027, section 7)", {"inspector"}, [] { + IntroBrowser browser; + auto& app = browser.app; + app.cppFunction("twice", &introTwice); + browser.connect(); + + given("the gate that opens the measure", [&] { + inspect::TimingGate gate; + then("it is closed until an inspector reads, and a call then reads no clock", [&] { + require(!gate.isOpen()); + require(!gate.begin()); + }); + then("a read opens it for a while, and the first call after that while closes it", [&] { + gate.observe(); + require(gate.begin().has_value()); + gate.observe(std::chrono::seconds{-1}); + require(gate.isOpen()); + require(!gate.begin()); + require(!gate.isOpen()); + }); + }); + when("no inspector has read the functions", [&] { + browser.call("twice", 3, 1); + then("the call is counted and not timed", [&] { + requireEqual(browser.function("twice").calls, std::uint64_t{1}); + requireEqual(browser.function("twice").timedCalls, std::uint64_t{0}); + }); + }); + when("an inspector reads the functions, then a call is made", [&] { + inspect::FunctionRegistry registry; + const auto record = registry.add("timed", "() => Promise", false, false, std::source_location::current()); + static_cast(registry.page(0, 200, inspect::minPageBytes)); + require(registry.timing()); + { const inspect::CallMeasure measure{record}; } + { const inspect::CallMeasure measure{record}; } + const auto info = registry.find("timed"); + then("each call is timed, and the mean and the longest duration are given in milliseconds", [&] { + require(info.has_value()); + requireEqual(info->timedCalls, std::uint64_t{2}); + require(info->maxDuration <= info->totalDuration); + const auto row = inspect::FunctionRegistry::row(*info); + require((static_cast(std::get<5>(row)) & inspect::function_flag::timed) != 0); + require(std::get<9>(row) >= 0 && std::get<9>(row) <= std::get<10>(row)); + }); + andWhen("the inspector stops reading for longer than the window", [&] { + registry.observe(std::chrono::seconds{-1}); + { const inspect::CallMeasure measure{record}; } + then("the next call is counted, not timed, and closes the measure", [&] { + requireEqual(registry.find("timed")->calls, std::uint64_t{3}); + requireEqual(registry.find("timed")->timedCalls, std::uint64_t{2}); + require(!registry.timing()); + }); + }); + }); + when("a call answered later is timed", [&] { + inspect::FunctionRegistry registry; + const auto record = registry.add("later", "() => Promise", false, true, std::source_location::current()); + registry.observe(); + inspect::CallMeasure started{record}; + inspect::CallMeasure carried{std::move(started)}; + then("the measure goes with the call, and ends once", [&] { + requireEqual(registry.find("later")->timedCalls, std::uint64_t{0}); + carried = {}; + requireEqual(registry.find("later")->timedCalls, std::uint64_t{1}); + requireEqual(registry.find("later")->calls, std::uint64_t{1}); + }); + }); + }}; + +const Scenario introFunctionPages{ + "The functions are read page after page, each within the budget of an answer (ADR-027, sections 3 and 7)", + {"inspector"}, + [] { + inspect::FunctionRegistry registry; + std::vector> owned; + const std::string longName(1000, 'n'); + for (int i = 0; i < 5; ++i) + owned.push_back(registry.add(longName + std::to_string(i), + inspect::typescriptSignature(std::vector(200, "Float64Array"), "void"), + i % 2 == 0, + i == 1, + std::source_location::current())); + for (const auto& record : owned) + record->fail(std::string(1000, 'e')); + + then("a page of one row always fits the smallest budget", [&] { + const auto [rows, next] = registry.page(0, 200, inspect::minPageBytes); + require(!rows.empty()); + requireEqual(std::get<1>(rows.front()).size(), inspect::maxTextBytes); + require(next != 0); + }); + then("the pages follow each other by the last identifier served, without loss or repetition", [&] { + std::vector ids; + double after = 0; + int pages = 0; + do { + const auto [rows, next] = registry.page(after, 2, inspect::responseBudget); + require(rows.size() <= 2); + for (const auto& row : rows) + ids.push_back(std::get<0>(row)); + after = next; + ++pages; + } while (after != 0 && pages < 10); + requireEqual(ids, (std::vector{1, 2, 3, 4, 5})); + requireEqual(pages, 3); + }); + then("the flags tell the caller and the deferred answer", [&] { + const auto [rows, next] = registry.page(0, 200, inspect::responseBudget); + static_cast(next); + requireEqual(static_cast(std::get<5>(rows.at(0))), inspect::function_flag::takesCaller); + requireEqual(static_cast(std::get<5>(rows.at(1))), inspect::function_flag::deferred); + requireEqual(std::get<7>(rows.at(0)), 1.0); + }); + then("a function released by its owner is listed no more, and the others keep their identifiers", [&] { + owned.erase(owned.begin() + 1); + const auto [rows, next] = registry.page(0, 200, inspect::responseBudget); + static_cast(next); + requireEqual(rows.size(), std::size_t{4}); + requireEqual(std::get<0>(rows.at(1)), 3.0); + }); + then("released functions leave the table at once, without any read: it does not grow with what comes and goes", [&] { + requireEqual(registry.size(), std::size_t{5}); + for (int i = 0; i < 1000; ++i) + static_cast(registry.add("transient", "() => Promise", false, false, std::source_location::current())); + requireEqual(registry.size(), std::size_t{5}); + owned.clear(); + requireEqual(registry.size(), std::size_t{0}); + }); + then("a record that outlives its registry is released without it", [&] { + std::shared_ptr kept; + { + inspect::FunctionRegistry shortLived; + kept = shortLived.add("kept", "() => Promise", false, false, std::source_location::current()); + } + requireEqual(kept->name, std::string{"kept"}); + kept.reset(); + }); + then("the application reads the names exactly as it registered them; only a page bounds them", [&] { + const auto functions = registry.list(); + requireEqual(functions.size(), std::size_t{5}); + requireEqual(functions.at(0).name, longName + "0"); + requireEqual(functions.at(4).name, longName + "4"); + require(functions.at(0).name != functions.at(4).name); + requireEqual(functions.at(0).label.size(), inspect::maxTextBytes); + require(registry.find(longName + "3").has_value()); + const auto control = registry.add("a\nb", "() => Promise", false, false, std::source_location::current()); + requireEqual(registry.find("a\nb")->name, std::string{"a\nb"}); + requireEqual(registry.find("a\nb")->label, + std::string{"a\xE2\x90\x8A" + "b"}); + }); + then("a record is listed only once its registration is accepted", [&] { + const auto prepared = registry.prepare("pending", "() => Promise", false, false, std::source_location::current()); + require(!registry.find("pending").has_value()); + requireEqual(registry.size(), std::size_t{5}); + registry.publish(prepared); + require(registry.find("pending").has_value()); + requireEqual(registry.find("pending")->id, std::uint64_t{6}); + }); + then("a function released while one of its calls is still answered is listed no more, and the call ends its measure", [&] { + registry.observe(); + auto registration = registry.add("leaving", "() => Promise", false, true, std::source_location::current()); + inspect::CallMeasure inFlight{registration->keep()}; + const auto record = registration->keep(); + registration.reset(); + require(!registry.find("leaving").has_value()); + inFlight.failed("stopped"); + inFlight = {}; + requireEqual(record->calls.load(), std::uint64_t{1}); + requireEqual(record->failures.load(), std::uint64_t{1}); + requireEqual(record->durations().count, std::uint64_t{1}); + }); + then("the number, the sum and the longest of the durations are read as one state", [&] { + const auto record = registry.add("steady", "() => Promise", false, false, std::source_location::current()); + record->timed(std::chrono::milliseconds{10}); + record->timed(std::chrono::milliseconds{30}); + const auto durations = record->durations(); + requireEqual(durations.count, std::uint64_t{2}); + requireEqual(durations.totalNanoseconds, std::uint64_t{40'000'000}); + requireEqual(durations.maxNanoseconds, std::uint64_t{30'000'000}); + const auto row = inspect::FunctionRegistry::row(*registry.find("steady")); + requireEqual(std::get<9>(row), 20.0); + requireEqual(std::get<10>(row), 30.0); + }); + then("a page counts a space's path as it is sent, control characters made visible", [&] { + inspect::FunctionRegistry scoped; + const std::string path(80, '\n'); // 80 bytes registered, 240 once visible + std::vector> kept; + for (int i = 0; i < 40; ++i) + kept.push_back(scoped.add("f" + std::to_string(i), "() => Promise", false, false, std::source_location::current(), path)); + requireEqual(scoped.find("f0", path)->scope, path); + const auto [rows, next] = scoped.page(0, 200, inspect::minPageBytes); + static_cast(next); + std::size_t sent = 0; + for (const auto& shown : rows) { + requireEqual(std::get<4>(shown).size(), std::size_t{240}); + sent += 2 + 6 * 9 + 5 * 3 + std::get<1>(shown).size() + std::get<2>(shown).size() + std::get<3>(shown).size() + 240 + std::get<8>(shown).size(); + } + require(!rows.empty() && rows.size() < kept.size()); + require(sent + inspect::responseHeaderBytes <= inspect::minPageBytes); + }); + then("a cursor or a count that is not a whole number is refused", [&] { + checkThrows([&] { + static_cast(registry.page(-1, 200, inspect::minPageBytes)); + }); + checkThrows([&] { + static_cast(registry.page(0, 1.5, inspect::minPageBytes)); + }); + }); + }}; + +const Scenario introSpaces{"The functions of a space are listed with its path, until the space releases them (ADR-027, section 7)", {"inspector"}, [] { + IntroBrowser browser; + auto& app = browser.app; + app.spaces("/s/", [](std::string_view) -> std::optional { + return std::nullopt; + }); + app.cppFunction("shared", [] { }); + { + IntroApp::Space space{app, "/s/", "alice"}; + space.cppFunction("own", [](int) { + return std::string{}; + }); + const auto functions = app.registeredFunctions(); + const auto own = std::ranges::find(functions, "own", &inspect::FunctionInfo::name); + then("the space's function names its space, the application's none", [&] { + require(own != functions.end()); + requireEqual(own->scope, std::string{"/s/alice/"}); + requireEqual(own->signature, std::string{"(a: number) => Promise"}); + require(own->location.contains("IntrospectionTests.cpp:")); + require(browser.function("shared").scope.empty()); + }); + } + then("once the space is destroyed, its function is listed no more", [&] { + const auto functions = app.registeredFunctions(); + require(std::ranges::find(functions, "own", &inspect::FunctionInfo::name) == functions.end()); + require(std::ranges::find(functions, "shared", &inspect::FunctionInfo::name) != functions.end()); + }); + }}; + +const Scenario introJsCalls{"The JavaScript functions that C++ calls are counted by name, with the failures of the typed calls (ADR-027, section 7)", + {"inspector"}, + [] { + given("the registry of the calls", [&] { + inspect::JsCallRegistry registry; + registry.counter("draw")->called(); + registry.counter("draw")->called(); + registry.counter("ask")->called(); + registry.counter("ask")->failed(); + then("each name has one counter, listed in the order of its first call", [&] { + const auto [rows, next] = registry.page(0, 200, inspect::minPageBytes); + requireEqual(next, 0.0); + requireEqual(rows.size(), std::size_t{2}); + requireEqual(rows.at(0), (inspect::JsFunctionRow{1.0, "draw", 2.0, 0.0})); + requireEqual(rows.at(1), (inspect::JsFunctionRow{2.0, "ask", 1.0, 1.0})); + }); + then("the pages follow each other by identifier", [&] { + const auto [first, next] = registry.page(0, 1, inspect::minPageBytes); + requireEqual(first.size(), std::size_t{1}); + requireEqual(next, 1.0); + const auto [second, end] = registry.page(next, 1, inspect::minPageBytes); + requireEqual(std::get<1>(second.at(0)), std::string{"ask"}); + requireEqual(end, 0.0); + }); + then("past the limit of names, the calls of the others are counted together", [&] { + for (std::size_t i = 0; registry.size() < inspect::maxJsFunctionNames; ++i) + registry.counter("generated-" + std::to_string(i))->called(); + registry.counter("one-more")->called(); + registry.counter("and-another")->called(); + requireEqual(registry.size(), inspect::maxJsFunctionNames + 1); + requireEqual(registry.counter("yet-another")->calls.load(), std::uint64_t{2}); + requireEqual(registry.counter("draw")->calls.load(), std::uint64_t{2}); + }); + }); + given("the source that call objects keep", [&] { + inspect::JsCallSource source; + then("it counts nothing until the inspectors are enabled, then gives the counters of one registry", [&] { + require(source.counter("draw") == nullptr); + require(source.registry() == nullptr); + const auto registry = source.enable(); + require(source.enable() == registry); + source.counter("draw")->called(); + requireEqual(registry->counter("draw")->calls.load(), std::uint64_t{1}); + }); + }); + given("an application outside the developer environment", [&] { + IntroBrowser browser; + browser.connect(); + then("no call to JavaScript is counted: nothing could read the count", [&] { + require(browser.app.jsCallCounter("draw") == nullptr); + }); + }); + }}; + +const Scenario introBrowsers{"The connected browsers are read page after page, with their pending calls (ADR-027, section 7)", {"inspector"}, [] { + std::vector browsers(3); + browsers[0].id = 0; + browsers[0].embeddedView = true; + browsers[0].localClient = true; + browsers[0].started = true; + browsers[0].caller = true; + browsers[0].path = "/"; + browsers[0].pendingWrites = 2; + browsers[0].pendingResults = 3; + browsers[0].pendingCalls = 4; + browsers[1].id = 1; + browsers[1].path = std::string(1000, 'p'); + browsers[1].space = "/s/alice/"; + browsers[2].id = 7; + browsers[2].closed = true; + + then("a row tells what the browser is and what it waits for", [&] { + const auto [rows, next, tasks] = inspect::browserPage(browsers, 0, 200, 5, inspect::minPageBytes); + requireEqual(rows.size(), std::size_t{3}); + requireEqual(next, 0.0); + requireEqual(tasks, 5.0); + using namespace inspect::browser_flag; + requireEqual(rows.at(0), + (inspect::BrowserRow{0.0, double{embeddedView | localClient | started | caller}, "/", "", 2.0, 3.0, 4.0})); + requireEqual(std::get<2>(rows.at(1)).size(), inspect::maxTextBytes); + requireEqual(std::get<3>(rows.at(1)), std::string{"/s/alice/"}); + requireEqual(static_cast(std::get<1>(rows.at(2))), closed); + }); + then("the cursor is the first identifier of the next page: a connection may have the identifier 0", [&] { + const auto [rows, next, tasks] = inspect::browserPage(browsers, 0, 2, 0, inspect::minPageBytes); + static_cast(tasks); + requireEqual(rows.size(), std::size_t{2}); + requireEqual(next, 7.0); + const auto [rest, end, ignored] = inspect::browserPage(browsers, next, 2, 0, inspect::minPageBytes); + static_cast(ignored); + requireEqual(rest.size(), std::size_t{1}); + requireEqual(std::get<0>(rest.at(0)), 7.0); + requireEqual(end, 0.0); + }); + }}; diff --git a/test/unit/ViewAssociationTests.cpp b/test/unit/ViewAssociationTests.cpp index 00b305dd..1cba5a81 100644 --- a/test/unit/ViewAssociationTests.cpp +++ b/test/unit/ViewAssociationTests.cpp @@ -21,8 +21,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -487,7 +489,12 @@ const Scenario developerWriteAccess{ freshNetwork(); AdmittedBrowser browser{false, false}; Commands commands{browser.app}; - const auto denied = [&](auto name, auto... arguments) { + bool ran = false; + commands.add("deploy", "writes the project", [&ran](Commands::Context) -> Task { + ran = true; + co_return; + }); + const auto denied = [&](auto name, auto... arguments) { const auto offset = ViewSocket::writtenText().size(); callWith(name, 7, arguments...); require(ViewSocket::writtenText().find(inspect::code::denied, offset) != std::string::npos); @@ -501,18 +508,36 @@ const Scenario developerWriteAccess{ denied("webfront.commands.start", std::uint32_t{1}, path, std::string{"[]"}); denied("webfront.commands.cancel", std::uint32_t{1}); denied("webfront.inspector.savePreferences", path, bytes); + // A command that exists is refused like one that does not: it is neither started nor left running. + denied("webfront.commands.start", std::uint32_t{2}, std::string{"deploy"}, std::string{"[]"}); + require(!ran); + requireEqual(commands.running(), std::size_t{0}); const auto offset = ViewSocket::writtenText().size(); callWith("webfront.developer.state", 7, path); const auto response = ViewSocket::writtenText().substr(offset); require(!response.empty() && !response.contains(inspect::code::denied)); require(!std::filesystem::exists(browser.project.path() / ".webfront/developer/staging")); + // The names and the helps of the commands stay readable: they change nothing (ADR-027, section 2). + const auto listed = ViewSocket::writtenText().size(); + callWithoutArgument("webfront.commands.list", 8); + const auto list = ViewSocket::writtenText().substr(listed); + require(list.contains("deploy") && !list.contains(inspect::code::denied)); }); given("a proven client", [&] { freshNetwork(); AdmittedBrowser browser{false, true}; + Commands commands{browser.app}; + bool ran = false; + commands.add("deploy", "writes the project", [&ran](Commands::Context) -> Task { + ran = true; + co_return; + }); callWith("webfront.developer.begin", 7, path, false); require(!ViewSocket::wrote(inspect::code::denied)); require(std::filesystem::is_directory(browser.project.path() / ".webfront/developer/staging")); + callWith("webfront.commands.start", 8, std::uint32_t{1}, std::string{"deploy"}, std::string{"[]"}); + require(ran); + require(!ViewSocket::wrote(inspect::code::denied)); }); given("a system browser with the default trust policy", [&] { freshNetwork(); @@ -659,3 +684,204 @@ const Scenario inspectorWatchesAccess{ }); } }; + +namespace { +/// A value as the bridge encodes it in an answer: what a page of the inspectors holds for it. +template +std::string encodedValue(const Value& value) { + msg::FunctionReturn<> message; + websocket::Frame frame{std::span(reinterpret_cast(message.header().data()), message.header().size())}; + message.encodeParameter(value, frame); + frame.freeze(); + const auto bytes = testing::messagePayload(frame); + std::string text(reinterpret_cast(bytes.data()), bytes.size()); + return text.substr(message.header().size()); +} + +/// A receiver that drops what a typed call completes with: the test reads the inspectors' counters instead. +struct IgnoringReceiver { + using receiver_concept = networking::ex::receiver_tag; + void set_value(int) noexcept { } + void set_error(std::exception_ptr) noexcept { } + void set_stopped() noexcept { } +}; + +/// What the socket wrote in answer to `ask`. +template +std::string answerOf(Ask ask) { + const auto offset = ViewSocket::writtenText().size(); + ask(); + return ViewSocket::writtenText().substr(offset); +} +} // namespace + +const Scenario inspectorRegistryAccess{ + "The functions, the JavaScript calls and the browsers are told to an admitted page only (ADR-027, sections 2 and 7)", + {"view-association", "inspector"}, + [] { + given("the proven view of an application that registered a function", [&] { + freshNetwork(); + AdmittedBrowser browser{false, true}; + browser.app.cppFunction("ping", [](int) { + return std::string{"pong"}; + }); + then("the three functions exist once the environment is bootstrapped", [&] { + for (const auto* name : {"webfront.inspector.functions", "webfront.inspector.jsFunctions", "webfront.inspector.browsers"}) + require(browser.app.hasCppFunction(name)); + }); + when("it asks for the functions", [&] { + const auto answer = answerOf([] { + callWith("webfront.inspector.functions", 11, 0.0, 200.0); + }); + then("the page names the function, its signature and where it was registered", [&] { + require(answer.contains("ping")); + require(answer.contains("(a: number) => Promise")); + require(answer.contains("ViewAssociationTests.cpp:")); + }); + then("the environment's own callbacks are listed, the inspectors' are not", [&] { + require(answer.contains("webfront.developer.begin")); + require(!answer.contains("webfront.inspector.")); + }); + }); + when("a call is made before any inspector read the functions, then one after", [&] { + const auto ping = [&] { + for (const auto& info : browser.app.registeredFunctions()) + if (info.name == "ping") + return info; + throw std::logic_error("ping is not registered"); + }; + callWith("ping", 3, 1); + then("the first is counted, not timed", [&] { + requireEqual(ping().calls, std::uint64_t{1}); + requireEqual(ping().timedCalls, std::uint64_t{0}); + }); + callWith("webfront.inspector.functions", 11, 0.0, 200.0); + callWith("ping", 4, 1); + then("the second is timed: an inspector is reading", [&] { + requireEqual(ping().calls, std::uint64_t{2}); + requireEqual(ping().timedCalls, std::uint64_t{1}); + }); + }); + when("it asks for the JavaScript functions that C++ called", [&] { + browser.app.forEachUI([](InspectorApp::UI ui) { + ui.jsFunction("draw")(1); + ui.jsFunction("draw")(2); + static_cast(ui.template jsFunction("measure")()); + }); + const auto answer = answerOf([] { + callWith("webfront.inspector.jsFunctions", 12, 0.0, 200.0); + }); + then("each is listed with the number of its calls", [&] { + require(answer.contains(encodedValue(std::tuple{std::string{"draw"}, 2.0, 0.0}).substr(2))); + require(answer.contains(encodedValue(std::tuple{std::string{"measure"}, 1.0, 0.0}).substr(2))); + }); + }); + when("it asks for the browsers", [&] { + const auto answer = answerOf([] { + callWith("webfront.inspector.browsers", 13, 0.0, 200.0); + }); + then("it finds itself: an embedded view, local, started, at the root", [&] { + using namespace inspect::browser_flag; + const auto row = encodedValue(std::tuple{0.0, double{embeddedView | localClient | started | caller}, std::string{"/"}}); + require(answer.contains(row.substr(2))); + require(!answer.contains(inspect::code::denied)); + }); + }); + }); + given("the typed call of a browser that fails", [&] { + freshNetwork(); + AdmittedBrowser browser{false, true}; + std::future result; + browser.app.forEachUI([&](InspectorApp::UI ui) { + result = ui.template jsFunction("measure")(); + }); + ViewSocket::fail(std::make_error_code(std::errc::connection_reset)); + then("its future fails, and the failure is counted for that function", [&] { + checkThrows([&] { + static_cast(result.get()); + }); + const auto counter = browser.app.jsCallCounter("measure"); + require(counter != nullptr); + requireEqual(counter->calls.load(), std::uint64_t{1}); + requireEqual(counter->failures.load(), std::uint64_t{1}); + }); + }); + given("a sender built before the developer environment is mounted, and started after", [&] { + freshNetwork(); + webfront::test::TemporaryDirectory project; + InspectorApp app(project.path(), inspectorConfig(false)); + connect(app, testing::LaunchSecret::of(app), inspectorUpgradeRequest); + std::optional().jsFunctionSender(""))> early; + app.forEachUI([&](InspectorApp::UI ui) { + early.emplace(ui.template jsFunctionSender("measureLater")); + }); + require(early.has_value()); + require(app.jsCallCounter("measureLater") == nullptr); + app.bootstrap("developer", {.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}); + auto operation = networking::ex::connect((*early)(), IgnoringReceiver{}); + networking::ex::start(operation); + then("the call it starts is counted: the counter is looked for when the call starts", [&] { + const auto counter = app.jsCallCounter("measureLater"); + require(counter != nullptr); + requireEqual(counter->calls.load(), std::uint64_t{1}); + requireEqual(counter->failures.load(), std::uint64_t{0}); + }); + andWhen("the browser disconnects before it answers", [&] { + ViewSocket::fail(std::make_error_code(std::errc::connection_reset)); + then("the failure of the call is counted too", [&] { + requireEqual(app.jsCallCounter("measureLater")->failures.load(), std::uint64_t{1}); + }); + }); + }); + given("a page that is not admitted, such as an external browser's", [&] { + freshNetwork(); + AdmittedBrowser browser{false, false}; + browser.app.cppFunction("ping", [](int) { + return std::string{"pong"}; + }); + for (const auto* name : {"webfront.inspector.functions", "webfront.inspector.jsFunctions", "webfront.inspector.browsers"}) { + const auto answer = answerOf([name] { + callWith(name, 11, 0.0, 200.0); + }); + then(std::string(name) + " is refused as denied, before any read", [&] { + require(answer.contains(inspect::code::denied)); + require(!answer.contains("ping")); + }); + } + then("no duration is measured for a page that was refused", [&] { + callWith("ping", 3, 1); + for (const auto& info : browser.app.registeredFunctions()) + requireEqual(info.timedCalls, std::uint64_t{0}); + }); + }); + given("a loopback page that is not proven, with trustLoopbackClients", [&] { + freshNetwork(); + ViewSocket::peerIsLoopback = true; + AdmittedBrowser browser{true, false}; + browser.app.cppFunction("ping", [](int) { + return std::string{"pong"}; + }); + const auto answer = answerOf([] { + callWith("webfront.inspector.functions", 11, 0.0, 200.0); + }); + then("it is admitted, and is told that it is a local client that is not an embedded view", [&] { + require(answer.contains("ping")); + const auto browsers = answerOf([] { + callWith("webfront.inspector.browsers", 13, 0.0, 200.0); + }); + using namespace inspect::browser_flag; + require(browsers.contains(encodedValue(std::tuple{0.0, double{localClient | started | caller}, std::string{"/"}}).substr(2))); + }); + }); + given("a developer application that is not bootstrapped", [&] { + freshNetwork(); + webfront::test::TemporaryDirectory project; + InspectorApp app(project.path(), WebFrontConfig{.port = "0"}); + then("it has none of these functions, and counts no call to JavaScript", [&] { + for (const auto* name : {"webfront.inspector.functions", "webfront.inspector.jsFunctions", "webfront.inspector.browsers"}) + require(!app.hasCppFunction(name)); + require(app.jsCallCounter("draw") == nullptr); + }); + }); + } +}; diff --git a/test/web/WKWebViewLifecycle.cpp b/test/web/WKWebViewLifecycle.cpp index ced45bc7..8f1f0b61 100644 --- a/test/web/WKWebViewLifecycle.cpp +++ b/test/web/WKWebViewLifecycle.cpp @@ -295,6 +295,31 @@ void hiddenSecondary() { require(!send(found->second->window, "isVisible"), "Opening the same page again showed a hidden window"); } +// A secondary window of a visible application is never suspended while inactive: closing it hides it before its view is +// released, and an occluded window is inactive all along. Suspended, its page would not end when the view is released and +// its connection would outlive the window (the closed inspector window of the developer journey stayed connected, #681). +void secondaryScheduling() { + Object pool(send(type("NSAutoreleasePool"), "new")); + Object configuration(send(type("WKWebViewConfiguration"), "new")); + if (!send(send(configuration.get(), "preferences"), "respondsToSelector:", sel_registerName("setInactiveSchedulingPolicy:"))) + return; // macOS 13 has no policy but the default one + Session primary("http://127.0.0.1:0/", {.visible = webfront::testdriver::visibleWindows}); + primary.create(); + auto& windows = Windows::instance(); + windows.primary = &primary; + struct Clear { + Windows& windows; + ~Clear() { + windows.clear(); + } + } clear{windows}; + openSecondary("127.0.0.1", "0", "inspector.html", {}); + const auto found = windows.secondary.find("inspector.html"); + require(found != windows.secondary.end(), "The secondary window was not opened"); + require(send(send(send(found->second->view, "configuration"), "preferences"), "inactiveSchedulingPolicy") == 2L, + "An inactive secondary window would suspend, and its closed page keep its connection"); +} + void missingResponse() { Object pool(send(type("NSAutoreleasePool"), "new")); Session session("http://127.0.0.1:0/", {.visible = webfront::testdriver::visibleWindows}); @@ -711,6 +736,7 @@ int main(int argc, char** argv) { { "settings", settings}, { "hidden-scheduling", hiddenScheduling}, { "hidden-secondary", hiddenSecondary}, + { "secondary-scheduling", secondaryScheduling}, { "translucent-background", translucentBackground}, { "navigation-diagnostic", navigationDiagnostic}, { "missing-response", missingResponse}, diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index 311bed2f..9fa613ad 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -982,7 +982,10 @@ try { assert(await webFront.cppFunction('webfront.inspector.closeWindow')('cpp.watches', window.webfrontInspectorHost.id) === false, 'The closed inspector window must be gone'); // A closed view's connection ends when its engine releases the page: WKWebView may take seconds. - await eventually(async () => await webFront.cppFunction('test.views')() === views, 'The closed inspector window must disconnect', + // On failure, the connections as the registry tells them (#681): identifier, flags, path, space, pending counts. + await eventually(async () => await webFront.cppFunction('test.views')() === views, + async () => `The closed inspector window must disconnect: ${JSON.stringify( + await webFront.cppFunction('webfront.inspector.browsers')(0, 200).catch(error => String(error)))}`, {attempts: 1200}); window.webfrontInspectorHost.attach('cpp.watches'); await window.webfrontInspectorHost.saved(); @@ -996,6 +999,32 @@ try { assert(opened.length === 0, 'An embedded view must never open a tab of the inspectors'); floating().querySelector('.webfront-inspector-close').click(); assert(floating().hidden, 'The inspector window must close'); + + // The Functions entry shows what the application registered (#681, ADR-027 section 7), read through the + // bridge of this page: its functions, their calls as they happen, and the rows that a search keeps. + await window.webfrontInspectorHost.open('cpp.functions'); + await until(() => floating() && !floating().hidden, 'The Functions entry must open the inspector in the floating window'); + const panel = () => floating().querySelector('iframe')?.contentDocument; + const functionRows = () => [...(panel()?.querySelector('table.registry')?.querySelectorAll('tbody tr') ?? [])]; + const names = () => functionRows().map(row => row.children[0].textContent); + await until(() => names().includes('test.watch'), () => `The Functions panel must list the application's functions: ${names()}`); + assert(!names().some(name => name.startsWith('webfront.')), `WebFront's own functions must be hidden until asked for: ${names()}`); + const watchRow = functionRows().find(row => row.children[0].textContent === 'test.watch'); + assert(watchRow.children[1].textContent === '(a: string) => Promise', + `A function must show its TypeScript signature: ${watchRow.children[1].textContent}`); + assert(/DeveloperTest\.cpp:\d+$/.test(watchRow.children[8].textContent), + `A function must show where it was registered: ${watchRow.children[8].textContent}`); + const callsOf = name => Number(functionRows().find(row => row.children[0].textContent === name)?.children[2].textContent); + const viewCalls = callsOf('test.views'); + await webFront.cppFunction('test.views')(); + await until(() => callsOf('test.views') > viewCalls, 'The Functions panel must follow the calls at its period'); + const search = panel().querySelector('input[type=search]'); + search.value = 'test.views'; + search.dispatchEvent(new Event('input')); + assert(names().length === 1 && names()[0] === 'test.views', `The search must keep the functions it finds: ${names()}`); + assert(opened.length === 0, 'An embedded view must never open a tab of the inspectors'); + floating().querySelector('.webfront-inspector-close').click(); + assert(floating().hidden, 'The inspector window must close'); } finally { window.open = open; } } assert(here.menus().length === 0, 'The menu must be closed'); diff --git a/test/web/suite/specs/inspector-specs.mjs b/test/web/suite/specs/inspector-specs.mjs new file mode 100644 index 00000000..2e607f79 --- /dev/null +++ b/test/web/suite/specs/inspector-specs.mjs @@ -0,0 +1,114 @@ +// The registry of the inspectors in a real browser (#681, ADR-027 section 7): the functions that this suite's application +// registered are listed with their TypeScript signature, where they were registered and their counters, through the pages +// of webfront.inspector.functions, with the bridge's existing types (the exception of ADR-003: no new wire type). +// +// These specs run in the frame of wf test. Its connection is not the application's view: the inspectors refuse it, and +// the list is read as the inspector's own frame reads it, through the bridge of the page that holds the frame. + +/** The bridge of the page that holds this frame: the environment's page, which is the proven view of the test driver. */ +const hostBridge = () => window.parent.webfrontInspectorHost?.bridge ?? window.parent.webFront; + +/** Every row of a paged inspector function, with what its first page gave beside the rows. */ +async function allRows(bridge, name) { + const rows = []; + let cursor = 0, rest = []; + for (let page = 0; page < 1000; ++page) { + const [list, next, ...more] = await bridge.cppFunction(name)(cursor, 200); + rows.push(...list); + if (page === 0) rest = more; + if (!next) return {rows, rest}; + expect(next).toBeGreaterThan(cursor); + cursor = next; + } + throw new Error(`${name} never ended`); +} + +const functionNamed = (rows, name) => rows.find(row => row[1] === name); + +describe('The inspectors\' registry', () => { + it('is refused to this frame, which is not a view of the application', async () => { + for (const name of ['webfront.inspector.functions', 'webfront.inspector.jsFunctions', 'webfront.inspector.browsers']) { + const error = await webFront.cppFunction(name)(0, 200).then(() => null, failure => failure); + expect(error?.code).withContext(name).toBe('webfront.inspector.denied'); + } + }); + + it('describes the functions of this suite to the page that holds the frame', async () => { + const host = hostBridge(); + await host.ready; + const [, admitted] = await host.cppFunction('webfront.inspector.containers')(); + expect(admitted).withContext('the page of the test driver is a proven view').toBeTrue(); + + const {rows} = await allRows(host, 'webfront.inspector.functions'); + // (identifier, name, signature, file:line, space, flags, calls, failures, last error, mean ms, longest ms) + expect(rows.every(row => Array.isArray(row) && row.length === 11)).toBeTrue(); + expect(new Set(rows.map(row => row[0])).size).toBe(rows.length); + expect(rows.some(row => row[1].startsWith('webfront.inspector.'))).withContext('the inspectors do not list themselves').toBeFalse(); + + const echo = functionNamed(rows, 'echoString'); + expect(echo[2]).toBe('(a: string) => Promise'); + expect(echo[3]).toMatch(/JasmineTest\.cpp:\d+$/); + expect(echo[4]).toBe(''); + expect(functionNamed(rows, 'recordTupleFromJs')[2]).toBe('(a: [number, string]) => Promise'); + expect(functionNamed(rows, 'listEcho')[2]).toBe('(a: string[]) => Promise'); + expect(functionNamed(rows, 'bitsetEcho')[2]).toBe('(a: Uint8Array) => Promise'); + expect(functionNamed(rows, 'throwFromCpp')[2]).toBe('() => Promise'); + + // A function that receives the calling UI says so, and the UI is not one of its JavaScript parameters. + const caller = functionNamed(rows, 'callBackCaller'); + expect(caller[5] & 1).toBe(1); + expect(caller[2]).toBe('(a: string) => Promise'); + expect(echo[5] & 1).toBe(0); + // A function that answers later says so, and its result is that of its task. + const deferred = functionNamed(rows, 'deferredEcho'); + expect(deferred[5] & 2).toBe(2); + expect(deferred[2]).toBe('(a: string, b: number) => Promise'); + + // The environment's own callbacks are listed with the application's. + expect(functionNamed(rows, 'webfront.developer.read')).toBeDefined(); + }); + + it('counts the calls and the failures, and times the calls while it is read', async () => { + const host = hostBridge(); + const read = async name => functionNamed((await allRows(host, 'webfront.inspector.functions')).rows, name); + const before = await read('echoString'); + const failuresBefore = (await read('throwFromCpp'))[7]; + + expect(await webFront.cppFunction('echoString')('inspected')).toBe('inspected'); + await expectAsync(webFront.cppFunction('throwFromCpp')()).toBeRejected(); + + const after = await read('echoString'); + expect(after[6]).toBe(before[6] + 1); + expect(after[7]).toBe(before[7]); + // The read above opened the measure: this call was timed, and its durations are plausible. + expect(after[5] & 4).toBe(4); + expect(after[9]).toBeGreaterThanOrEqual(0); + expect(after[10]).toBeGreaterThanOrEqual(after[9]); + expect(after[10]).toBeLessThan(60000); + const failed = await read('throwFromCpp'); + expect(failed[7]).toBe(failuresBefore + 1); + expect(failed[8]).not.toBe(''); + }); + + it('counts the JavaScript functions that C++ calls, and tells the connected browsers', async () => { + const host = hostBridge(); + // (identifier, name, calls, failures of the typed calls). C++ offers its read binding to every page that connects: + // that call was made at least for the page that holds this frame and for this frame. + const called = (await allRows(host, 'webfront.inspector.jsFunctions')).rows; + expect(called.every(row => Array.isArray(row) && row.length === 4)).toBeTrue(); + const binding = called.find(row => row[1] === 'wfBind.exchange'); + expect(binding?.[2]).toBeGreaterThanOrEqual(2); + expect(binding?.[3]).toBe(0); + + const {rows, rest: [tasks]} = await allRows(host, 'webfront.inspector.browsers'); + // (identifier, flags, path, space, pending writes, awaited results, unanswered calls); the flags tell an embedded view + // (1), a local client (2), a started browser (4), a closed one (8) and the page that asks (16). + expect(rows.every(row => Array.isArray(row) && row.length === 7)).toBeTrue(); + const asking = rows.filter(row => row[1] & 16); + expect(asking.length).toBe(1); + expect(asking[0][1] & 7).withContext('the page that asks is a started, local, embedded view').toBe(7); + // This frame has its own connection, which is neither the view nor a local client. + expect(rows.some(row => (row[1] & 19) === 0 && (row[1] & 4) === 4)).toBeTrue(); + expect(Number.isSafeInteger(tasks) && tasks >= rows.length).withContext(`tasks: ${tasks}`).toBeTrue(); + }); +}); diff --git a/test/web/suite/specs/webfront-specs.mjs b/test/web/suite/specs/webfront-specs.mjs index e9361311..ad0f42dc 100644 --- a/test/web/suite/specs/webfront-specs.mjs +++ b/test/web/suite/specs/webfront-specs.mjs @@ -8,6 +8,7 @@ import './forms-specs.mjs'; import './content-policy-specs.mjs'; import './dom-specs.mjs'; import './spaces-specs.mjs'; +import './inspector-specs.mjs'; import { importedValue } from './module-fixture.mjs'; import './async-diagnostics.js';