From 512d42fbd7140f8fdd7c721d3fb3d2a749943b7a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:07:05 +0100 Subject: [PATCH 01/14] Watches: read an object as a tree of nodes, by pages and passes, and write it (#682) A watch now reaches its object through its source, and the inspectors read it (ADR-027, sections 3 to 6): - WatchValues.hpp: the bounds, the paths (ASCII, reversible, percent-encoded keys), the kinds of section 4 and how each type is rendered into a bounded receiver; PagedSource and its optional keys; Described for the types that have a forms::Description. - WatchMemory.hpp: what a connection knows of a watch, under a revision. Pages of children whose first node is the parent, passes of differences read in a set kept by the pass, interruption that gives back what was not served, resynchronization, writes under the precondition of what was displayed. - Watches.hpp: the sources (visitor, reference, copy, owning source), the executor, the mutator, the registry's operations, the full value by fragments of an identified snapshot, and the two contracts of destruction. - webfront.inspector.children, changes, value, fold, reset, limits and write, answered to an admitted page only, each operation whole on the watch's executor or on the server thread. A buffers policy too small for a page of one node or a write of 1 KiB does not compile with the developer environment (WatchPolicyRejects). Destroying the handle of a watch whose source refers to the application's objects from its own operation writes a diagnostic and terminates (WatchDestroyedFromItsVisitor). --- include/webfront/DeveloperApp.hpp | 60 +- include/webfront/WatchMemory.hpp | 830 ++++++++++++++++++++++ include/webfront/WatchValues.hpp | 1002 +++++++++++++++++++++++++++ include/webfront/Watches.hpp | 883 ++++++++++++++++------- include/webfront/WebFront.hpp | 195 +++++- test/unit/CMakeLists.txt | 30 +- test/unit/InspectorDistribution.cpp | 9 +- test/unit/ViewAssociationTests.cpp | 76 ++ test/unit/WatchHarness.hpp | 221 ++++++ test/unit/WatchPassTests.cpp | 476 +++++++++++++ test/unit/WatchPolicyRejects.cpp | 32 + test/unit/WatchTerminates.cpp | 46 ++ test/unit/WatchTests.cpp | 40 ++ test/unit/WatchTreeTests.cpp | 967 ++++++++++++++++++++++++++ test/unit/WatchWriteTests.cpp | 659 ++++++++++++++++++ 15 files changed, 5236 insertions(+), 290 deletions(-) create mode 100644 include/webfront/WatchMemory.hpp create mode 100644 include/webfront/WatchValues.hpp create mode 100644 test/unit/WatchHarness.hpp create mode 100644 test/unit/WatchPassTests.cpp create mode 100644 test/unit/WatchPolicyRejects.cpp create mode 100644 test/unit/WatchTerminates.cpp create mode 100644 test/unit/WatchTreeTests.cpp create mode 100644 test/unit/WatchWriteTests.cpp diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 23c21eac..ba0b7bf5 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -185,10 +185,10 @@ class DeveloperAppWithNetwork : public BasicWF >= inspect::minPageBytes, - "The buffers policy is too small for the inspectors: an answer must hold a page of one node (ADR-027)"); - using Caller = typename Base::UI; - const auto registry = this->enableInspectors(); + // A policy too small for a page of one node, or for a write of 1 KiB, does not compile (ADR-027, section 3). + static constexpr inspect::Limits limits = inspect::limitsOf(); + using Caller = typename Base::UI; + const auto registry = this->enableInspectors(); // The menu of the environment's tab asks it first: an environment that does not find it says the library is too old. this->template reservedCppFunction, Caller>( "webfront.inspector.containers", @@ -224,6 +224,58 @@ class DeveloperAppWithNetwork : public BasicWFpage(revision, after, count, inspect::responseBudget); }); + // The watches' trees (sections 3, 5 and 6). Each operation runs whole where the watch's object lives: on its executor + // when it has one, else here, on the server thread. The session is taken while the caller is known to be connected. + this->template reservedCppFunction("webfront.inspector.limits", [](Caller ui) { + admit(ui); + return inspect::WatchRegistry::limits(limits); + }); + this->template reservedCppFunction, Caller, double, std::string, double, double, double>( + "webfront.inspector.children", + [this, registry](Caller ui, double watch, std::string path, double revision, double start, double count) { + admit(ui); + return inspect::onWatch(registry, watch, [=, session = this->inspectorSession(ui)] { + return registry->children(session, watch, path, revision, start, count, limits); + }); + }); + this->template reservedCppFunction, Caller, double, double, double, double>( + "webfront.inspector.changes", + [this, registry](Caller ui, double watch, double revision, double cursor, double count) { + admit(ui); + return inspect::onWatch(registry, watch, [=, session = this->inspectorSession(ui)] { + return registry->changes(session, watch, revision, cursor, count, limits); + }); + }); + this->template reservedCppFunction, Caller, double, std::string, double, double>( + "webfront.inspector.value", + [this, registry](Caller ui, double watch, std::string path, double snapshot, double offset) { + admit(ui); + return inspect::onWatch(registry, watch, [=, session = this->inspectorSession(ui)] { + return registry->value(session, watch, path, snapshot, offset, limits); + }); + }); + this->template reservedCppFunction, Caller, double, std::string, double>( + "webfront.inspector.fold", + [this, registry](Caller ui, double watch, std::string path, double revision) { + admit(ui); + return inspect::onWatch(registry, watch, [=, session = this->inspectorSession(ui)] { + return registry->fold(session, watch, path, revision); + }); + }); + this->template reservedCppFunction, Caller, double>("webfront.inspector.reset", [this, registry](Caller ui, double watch) { + admit(ui); + return inspect::onWatch(registry, watch, [=, session = this->inspectorSession(ui)] { + return registry->reset(session, watch); + }); + }); + this->template reservedCppFunction, Caller, double, double, std::string, std::string, std::string>( + "webfront.inspector.write", + [this, registry](Caller ui, double watch, double revision, std::string path, std::string expected, std::string text) { + admit(ui); + return inspect::onWatch(registry, watch, [=, session = this->inspectorSession(ui)] { + return registry->write(session, watch, revision, path, expected, text, limits); + }); + }); // What the application registered and runs (section 7): pages of rows, each within the answer's budget. this->template reservedCppFunction( "webfront.inspector.functions", diff --git a/include/webfront/WatchMemory.hpp b/include/webfront/WatchMemory.hpp new file mode 100644 index 00000000..ba07aeb9 --- /dev/null +++ b/include/webfront/WatchMemory.hpp @@ -0,0 +1,830 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-27 +// +// WebFront — core +// Role: What one connection knows of one watch (ADR-027, section 3): the nodes sent, their pages, the passes of differences and the writes. +// Thread: thread-safe | Alloc: unrestricted +// LLM: internal; one Memory per connection and watch, each operation whole inside the access window the application defines + +#pragma once + +#include "WatchValues.hpp" + +#include +#include +#include +#include +#include + +namespace webfront::inspect::detail { + +// --- Encoded sizes (weblink/Messages.hpp) ---------------------------------------------------------------------- + +/// The bytes a string takes on the wire: its code, its length on 1, 2 or 4 bytes, and its bytes. +[[nodiscard]] constexpr std::size_t stringBytes(std::size_t size) noexcept { + return (size < 256 ? 2u : size <= 65535 ? 3u : 5u) + size; +} +/// The bytes of a node: a tuple header, four strings and two numbers. +[[nodiscard]] inline std::size_t nodeBytes(const Node& node) noexcept { + return 2 + stringBytes(std::get<0>(node).size()) + stringBytes(std::get<1>(node).size()) + stringBytes(std::get<2>(node).size()) + + stringBytes(std::get<3>(node).size()) + 9 + 9; +} +/// The bytes of a page besides its nodes: the message header, the tuple and list headers, two numbers and a boolean. +inline constexpr std::size_t pageOverheadBytes = 8 + 2 + 5 + 9 + 9 + 1; +static_assert(pageOverheadBytes <= responseHeaderBytes); +/// The bytes of a node whose every field is at its bound. +inline constexpr std::size_t largestNodeBytes = 2 + (3 + maxPathBytes) + (2 + maxKindBytes) + 2 * (3 + maxTextBytes) + 9 + 9; +static_assert(largestNodeBytes <= maxNodeBytes); +static_assert(pageOverheadBytes + 2 * largestNodeBytes <= minPageBytes, "The smallest page holds a parent and one child"); +/// The answer of a write, at its largest: the header, a tuple, a number, the longest code and a message of 256 bytes. +static_assert(8 + 2 + 9 + (2 + 64) + (3 + maxTextBytes) <= minPageBytes); + +[[nodiscard]] inline BridgeError refusal(std::string_view code, std::string_view message) { + return webfront::detail::makeBridgeError(code, std::string(message)); +} + +/// A number of the protocol: a whole number from 0 to 2^53. +[[nodiscard]] inline std::uint64_t wholeNumber(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); +} + +[[nodiscard]] inline unsigned flagsOf(const Node& node) noexcept { + return static_cast(std::get<5>(node)); +} +[[nodiscard]] inline std::size_t childrenOf(const Node& node) noexcept { + return static_cast(std::get<4>(node)); +} + +/// The text of an exception of the application's code, as the value of a node. +[[nodiscard]] inline std::string exceptionValue(std::string_view what) { + static constexpr std::string_view open = "\xE2\x80\xB9" + "exception : ", + close = "\xE2\x80\xBA"; + return std::string(open) + boundedText(what, maxTextBytes - open.size() - close.size()) + std::string(close); +} + +/// A parent whose children could not all have a path within the bounds is not unfolded (ADR-027, section 3). +[[nodiscard]] inline bool depthReached(std::string_view path, const NodeOps& ops) noexcept { + const auto level = static_cast(std::ranges::count(path, '/')); + return ops.container && (level >= maxPathSegments || path.size() + 1 + (ops.keyed ? maxKeySegment : maxIndexSegment) > maxPathBytes); +} + +/// A node read in the object, with what the memory keeps to write it later. +struct Rendered { + Node node; + const NodeOps* ops = nullptr; + const void* aux = nullptr; + Editor editor; +}; + +/** + * Reads a node. Nothing here fails: an exception of a formatter or of a paged source becomes the node's value, with the + * kind `opaque`. A node is writable when the watch is, its type has an editor, and what is shown of it is whole and + * tells it exactly: neither its label nor its value cut, and not a keyed element told by its position. + */ +[[nodiscard]] inline Rendered render(const ChildView& view, std::string path, bool positional, bool writable) { + const auto& ops = *view.node.ops; + std::string kind, value; + std::size_t count = 0; + bool cut = false; + bool failed = false; + try { + kind = ops.kind(view.node); + TextSink sink{maxTextBytes + 1}; // one byte more than what is shown tells that it is cut + ops.value(view.node, sink); + std::tie(value, cut) = visibleText(sink.text(), maxTextBytes, true); + count = ops.container ? ops.size(view.node) : 0; + } catch (const std::exception& error) { + failed = true; + value = exceptionValue(error.what()); + } catch (...) { + failed = true; + value = exceptionValue("unknown"); + } + if (failed) { + kind = "opaque"; + count = 0; + cut = false; + } + unsigned flags = cut ? flag::truncated : 0u; + Editor editor; + if (writable && !failed && !cut && !view.labelCut && !positional && ops.editor != nullptr) { + try { + editor = ops.editor(view.node); + } catch (...) { + editor = nullptr; + } + if (editor) + flags |= flag::writable; + } + if (!failed && depthReached(path, ops)) + flags |= flag::depthReached; + return { + .node = Node{std::move(path), std::move(kind), view.label, std::move(value), static_cast(count), static_cast(flags)}, + .ops = &ops, + .aux = view.node.aux, + .editor = std::move(editor) + }; +} + +/// The key of the child at `position` when it can name it in a path: none for a source without keys, when key() throws, +/// or when its encoding is longer than 128 bytes (a cut key would be ambiguous). +[[nodiscard]] inline std::optional usableKey(const NodeRef& parent, std::size_t position) noexcept { + if (!parent.ops->keyed) + return std::nullopt; + try { + auto key = parent.ops->key(parent, position); + if (key && encodeKey(*key).size() <= maxKeyBytes) + return key; + } catch (...) { // NOLINT(bugprone-empty-catch): an element whose key fails is an element without a key + } + return std::nullopt; +} + +/// What visits each node of a path: (level, node, told by its position under a keyed parent). False stops. +using PathHook = FunctionRef; + +/** + * Follows `segments` from `here`, calling `at` for each node from `here` down, while they resolve. A keyed segment is + * resolved by find(), then checked: the key at the position found must be the same, else the node is gone. Returns + * whether the walk went as far as `at` let it (false: a segment no longer resolves). `at` must not throw. + */ +inline bool descend(const ChildView& here, std::span segments, std::size_t level, bool positional, PathHook at) { + if (!at(level, here, positional) || segments.empty()) + return true; + const auto& segment = segments.front(); + const auto& ops = *here.node.ops; + bool found = false; + try { + if (!ops.container) + return false; + if (segment.letter == 'k') { + if (!ops.keyed) + return false; + const auto position = ops.find(here.node, segment.key); + if (!position) + return false; + const auto key = ops.key(here.node, *position); + if (!key || *key != segment.key) + return false; + ops.visit(here.node, *position, 1, [&](const ChildView& child) { + ChildView named = child; + std::tie(named.label, named.labelCut) = visibleText(segment.key, maxTextBytes, true); + found = descend(named, segments.subspan(1), level + 1, false, at); + return false; + }); + } else { + if (segment.letter != ops.letter || segment.number > std::numeric_limits::max()) + return false; + const auto position = ops.alternative ? std::size_t{0} : static_cast(segment.number); + if (position >= ops.size(here.node)) + return false; + ops.visit(here.node, position, 1, [&](const ChildView& child) { + if (child.rank == segment.number) + found = descend(child, segments.subspan(1), level + 1, ops.keyed, at); + return false; + }); + } + } catch (...) { + return false; // a source that fails while it is walked no longer shows the node + } + return found; +} + +/// How an operation reaches the object of its watch, for the time of one call. +struct Access { + /// Calls its argument once with the root, inside the window the application defines (its lock, its executor); false + /// when the source did not give its object. + std::function)> open; + std::string label; // of the root: the watch's name, visible and bounded + bool writable = false; + /// The application's own way to write a value, or nothing: (root object, path, text). Throws to refuse. + std::function mutate; + std::function diagnose; // ADR-011: what the application should know + std::atomic duplicateKeysReported{false}; +}; + +/** + * Runs `use` with the root inside the access window. A source that fails before giving its object rejects the call, with + * nothing changed; one that fails after it is only reported, since the operation is done (ADR-027, "Atomicité des refus"). + * `use` must not throw. + */ +template +void enter(Access& access, Use&& use) { + bool entered = false; + const auto failure = [&](std::string_view what) { + if (!entered) + throw std::runtime_error("The watch's source failed: " + boundedText(what, maxTextBytes - 32)); + if (access.diagnose) + access.diagnose("The source of the watch '" + access.label + "' threw after its visit: " + boundedText(what)); + }; + try { + if (!access.open) + throw refusal(code::unavailable, "The watch has no source"); + static_cast(access.open([&](const NodeRef& root) { + if (entered) + return; // a source calls its visit once: a second call reads nothing + entered = true; + use(root); + })); + } catch (const BridgeError&) { + if (!entered) + throw; + } catch (const std::exception& error) { + failure(error.what()); + } catch (...) { + failure("unknown exception"); + } + if (!entered) + throw refusal(code::unavailable, "The watch's source did not give its object"); +} + +/** + * @brief The memory of one connection for one watch: the nodes it was sent, under a revision, and the pass of differences + * in progress. Every call that changes it validates first, without effect, then acts inside the access window and always + * answers with the resulting revision (ADR-027, section 3). + */ +class Memory { +public: + struct Entry { + Node node; // as it was last sent, without the flags that tell an event + const NodeOps* ops = nullptr; + const void* aux = nullptr; + Editor editor; + std::map positions; // the children loaded: position, path + std::optional lastKey; // of the last child served, for a keyed parent + std::size_t lastPosition = 0; + }; + + [[nodiscard]] std::uint64_t revision() const { + std::scoped_lock lock{mutex}; + return current; + } + [[nodiscard]] std::size_t size() const { + std::scoped_lock lock{mutex}; + return nodes.size(); + } + [[nodiscard]] bool contains(std::string_view path) const { + std::scoped_lock lock{mutex}; + return nodes.contains(path); + } + /// Whether a pass of differences has pages left to serve. + [[nodiscard]] bool passing() const { + std::scoped_lock lock{mutex}; + return pass.has_value(); + } + + /// webfront.inspector.children: a page of the children of `path`, its first node being the parent itself. + Page children(Access& access, std::string_view path, double revisionAsked, double startAsked, double countAsked, const Limits& limits) { + const auto segments = segmentsOf(path); + const auto revision = wholeNumber(revisionAsked, "revision"); + const auto start = wholeNumber(startAsked, "position"); + const auto count = (std::min)(wholeNumber(countAsked, "count"), maxPageCount); + std::scoped_lock lock{mutex}; + if (revision != current) + return resynchronize(); + const Entry* known = restored(path); + if (known == nullptr && !path.empty()) + throw refusal(code::unknown, "The node is not in the inspector's memory: unfold its parent first"); + if (known != nullptr && (flagsOf(known->node) & flag::depthReached) != 0) + throw refusal(code::limit, "The node is too deep to be unfolded"); + if (sizeRestored() >= limits.maxNodes) + throw refusal(code::limit, "The inspector's memory is full: fold some nodes"); + Page page; + enter(access, [&](const NodeRef& root) { + interrupt(); + page = list(access, root, std::string(path), segments, static_cast(start), static_cast(count), limits); + }); + return page; + } + + /// webfront.inspector.changes: a page of a pass of differences; the cursor 0 starts a pass on the object as it is. + Page changes(Access& access, double revisionAsked, double cursorAsked, double countAsked, const Limits& limits) { + const auto revision = wholeNumber(revisionAsked, "revision"); + const auto cursor = wholeNumber(cursorAsked, "cursor"); + const auto count = std::clamp(wholeNumber(countAsked, "count"), 1, maxPageCount); + std::scoped_lock lock{mutex}; + if (cursor != 0) { + // A later page is read in the set kept by the pass: a revision or a cursor that is not the pass's is a page lost. + if (!pass || revision != current || cursor != pass->served) + return resynchronize(); + return serve(static_cast(count), limits); + } + if (revision != current) + return resynchronize(); + enter(access, [&](const NodeRef& root) { + interrupt(); + compare(access, root); + }); + return serve(static_cast(count), limits); + } + + /// webfront.inspector.fold: forgets the descendants of `path`. The root stays. + Page fold(std::string_view path, double revisionAsked) { + static_cast(segmentsOf(path)); + const auto revision = wholeNumber(revisionAsked, "revision"); + std::scoped_lock lock{mutex}; + if (revision != current) + return resynchronize(); + if (restored(path) == nullptr) + throw refusal(code::unknown, "The node is not in the inspector's memory"); + interrupt(); + auto& entry = nodes.find(path)->second; + dropDescendants(path, nullptr); + entry.positions.clear(); + entry.lastKey.reset(); + return {std::vector{}, 0.0, static_cast(++current), false}; + } + + /// webfront.inspector.reset: empties the memory and gives the revision of the empty one. + double reset() { + std::scoped_lock lock{mutex}; + nodes.clear(); + pass.reset(); + return static_cast(++current); + } + + /** + * webfront.inspector.write. What can be refused without reading the object rejects (exceptions, nothing changed); then, + * inside the access window, a pass in progress is interrupted and the target and its ancestors must still show what + * the memory holds, the target showing `expected`. The answer then always carries the resulting revision, with the + * code `stale` or `refused` when the value was not written. `applied` tells that the object was changed. + */ + WriteAnswer + write(Access& access, double revisionAsked, std::string_view path, std::string_view expected, std::string_view text, const Limits& limits, bool& applied) { + if (text.size() > limits.maxWriteTextBytes) + throw refusal(code::tooLarge, "The text is longer than " + std::to_string(limits.maxWriteTextBytes) + " bytes"); + const auto segments = segmentsOf(path); + const auto revision = wholeNumber(revisionAsked, "revision"); + std::scoped_lock lock{mutex}; + if (revision != current) + throw refusal(code::stale, "The inspector's revision is no longer the memory's"); + const Entry* known = restored(path); + if (known == nullptr) + throw refusal(code::unknown, "The node is not in the inspector's memory"); + if (!access.writable || (flagsOf(known->node) & flag::writable) == 0 || !known->editor) + throw refusal(code::readOnly, "The node is not writable"); + Applier apply; + try { + apply = known->editor(text); + } catch (const std::exception& error) { + throw refusal(code::parse, boundedText(error.what())); + } + WriteAnswer answer; + enter(access, [&](const NodeRef& root) { + interrupt(); + std::string code, message; + bool reached = false; + const auto whole = descend(rootView(access, root), segments, 0, false, [&](std::size_t level, const ChildView& view, bool positional) { + const auto at = prefix(path, level); + const auto found = nodes.find(at); + if (found == nodes.end()) + return false; + auto& entry = found->second; + const auto now = render(view, std::string(at), positional, access.writable); + // What the user saw of the node must still be true: its kind, its label, its value, its number of children. + if (std::get<1>(now.node) != std::get<1>(entry.node) || std::get<2>(now.node) != std::get<2>(entry.node) + || std::get<3>(now.node) != std::get<3>(entry.node) || std::get<4>(now.node) != std::get<4>(entry.node)) + return false; + if (level != segments.size()) + return true; + if (std::get<3>(now.node) != expected || now.ops != entry.ops || now.aux != entry.aux || (flagsOf(now.node) & flag::writable) == 0) + return false; + reached = true; + try { + if (access.mutate) + access.mutate(root.object, path, text); + else + apply(view.node); + applied = true; + } catch (const std::exception& error) { + code = inspect::code::refused; + message = boundedText(error.what()); + } catch (...) { + code = inspect::code::refused; + message = "The application refused the value"; + } + if (applied) + store(entry, render(view, std::string(at), positional, access.writable)); + return true; + }); + if (!whole || !reached) + code = inspect::code::stale; + answer = {static_cast(++current), std::move(code), std::move(message)}; + }); + return answer; + } + + /// The whole value of a node of the memory, formatted inside the access window up to `limit` bytes, and whether it was + /// cut there. The memory is not changed. + std::pair value(Access& access, std::string_view path, std::size_t limit) { + const auto segments = segmentsOf(path); + std::scoped_lock lock{mutex}; + if (restored(path) == nullptr) + throw refusal(code::unknown, "The node is not in the inspector's memory"); + std::pair text; + std::string failure; + bool reached = false; + enter(access, [&](const NodeRef& root) { + static_cast(descend(rootView(access, root), segments, 0, false, [&](std::size_t level, const ChildView& view, bool) { + if (level != segments.size()) + return true; + reached = true; + try { + TextSink sink{limit == std::numeric_limits::max() ? limit : limit + 1}; + view.node.ops->value(view.node, sink); + text = visibleText(sink.text(), limit, false); + } catch (const std::exception& error) { + failure = "The value could not be formatted: " + boundedText(error.what(), maxTextBytes - 40); + } catch (...) { + failure = "The value could not be formatted"; + } + return true; + })); + }); + if (!reached) + throw refusal(code::stale, "The node is no longer in the object"); + if (!failure.empty()) + throw std::runtime_error(failure); + return text; + } + +private: + /// A change of a pass: what the node shows now, and what the memory held, to give it back if the page is never served. + struct Change { + std::string path; + Rendered now; + bool dropChildren = false; + Entry before; + std::vector> dropped; + }; + struct Pass { + std::vector changes; + std::size_t served = 0; + }; + + [[nodiscard]] static std::vector segmentsOf(std::string_view path) { + auto segments = parsePath(path); + if (!segments) + throw refusal(code::unknown, "Ill-formed path"); + return std::move(*segments); + } + + [[nodiscard]] static ChildView rootView(const Access& access, const NodeRef& root) { + return {.position = 0, .rank = 0, .node = root, .label = access.label, .labelCut = false}; + } + + /// The path of the ancestor of `path` at `level` (0 is the root). + [[nodiscard]] static std::string_view prefix(std::string_view path, std::size_t level) noexcept { + std::size_t end = 0; + for (std::size_t seen = 0; seen < level; ++seen) { + const auto next = path.find('/', end + 1); + if (next == std::string_view::npos) + return path; + end = next; + } + return path.substr(0, end); + } + + /// The memory emptied under a new revision, which the answer carries: the inspector reads again from the root. + Page resynchronize() { + nodes.clear(); + pass.reset(); + return {std::vector{}, 0.0, static_cast(++current), true}; + } + + /// What the memory would hold for `path` once a pass in progress is interrupted: exactly what the inspector received. + [[nodiscard]] const Entry* restored(std::string_view path) const { + if (pass) + for (std::size_t index = pass->served; index < pass->changes.size(); ++index) { + const auto& change = pass->changes[index]; + if (change.path == path) + return &change.before; + for (const auto& [dropped, entry] : change.dropped) + if (dropped == path) + return &entry; + } + const auto found = nodes.find(path); + return found == nodes.end() ? nullptr : &found->second; + } + + [[nodiscard]] std::size_t sizeRestored() const { + auto size = nodes.size(); + if (pass) + for (std::size_t index = pass->served; index < pass->changes.size(); ++index) + size += pass->changes[index].dropped.size(); + return size; + } + + /// Ends a pass in progress: the entries of the pages not served get back what they held before the pass, so that the + /// memory tells exactly what the inspector received. The next pass finds those differences again. + void interrupt() { + if (!pass) + return; + for (std::size_t index = pass->changes.size(); index > pass->served; --index) { + auto& change = pass->changes[index - 1]; + nodes[change.path] = std::move(change.before); + for (auto& [path, entry] : change.dropped) + nodes[path] = std::move(entry); + } + pass.reset(); + } + + /// Removes the descendants of `path`, keeping them in `kept` when given. + void dropDescendants(std::string_view path, std::vector>* kept) { + // Every descendant's path starts with the parent's and a '/': they follow it in the order of the paths. + std::string from{path}; + from += '/'; + auto it = nodes.lower_bound(from); + while (it != nodes.end() && std::string_view{it->first}.starts_with(from)) { + if (kept != nullptr) + kept->emplace_back(it->first, std::move(it->second)); + it = nodes.erase(it); + } + } + + static void store(Entry& entry, Rendered now) { + if (entry.ops != now.ops || entry.aux != now.aux) { + entry.positions.clear(); + entry.lastKey.reset(); + } + entry.node = std::move(now.node); + entry.ops = now.ops; + entry.aux = now.aux; + entry.editor = std::move(now.editor); + } + + /// The page of `children`, inside the access window. + Page list(Access& access, + const NodeRef& root, + const std::string& path, + const std::vector& segments, + std::size_t start, + std::size_t count, + const Limits& limits) { + std::vector served; + std::size_t next = 0; + bool reached = false; + static_cast(descend(rootView(access, root), segments, 0, false, [&](std::size_t level, const ChildView& view, bool positional) { + if (level != segments.size()) + return true; + reached = true; + next = listChildren(access, view, path, positional, start, count, limits, served); + return true; + })); + if (!reached) { + // The node is gone from the object: it leaves the memory with its descendants, and the inspector is told. + Node gone{path, "opaque", "", "", 0.0, static_cast(flag::removed)}; + if (const auto found = nodes.find(path); found != nodes.end()) { + gone = found->second.node; + std::get<4>(gone) = 0.0; + std::get<5>(gone) = static_cast(flag::removed); + dropDescendants(path, nullptr); + nodes.erase(found); + } + served.push_back(std::move(gone)); + } + return {std::move(served), static_cast(next), static_cast(++current), false}; + } + + /// Serves the parent then its children from `start`; returns the next position, 0 at the end. + std::size_t listChildren(Access& access, + const ChildView& view, + const std::string& path, + bool positional, + std::size_t start, + std::size_t count, + const Limits& limits, + std::vector& served) { + auto parent = render(view, path, positional, access.writable); + const auto& ops = *view.node.ops; + const auto total = childrenOf(parent.node); + auto& entry = nodes[path]; + if (start > 0) { + // A later page of a list is read on the state of the previous ones, or the list starts again (rule 2). + bool consistent = entry.ops == parent.ops && total == childrenOf(entry.node); + if (consistent && entry.lastKey) { + try { + const auto position = ops.find(view.node, *entry.lastKey); + consistent = position && *position == entry.lastPosition; + } catch (...) { + consistent = false; + } + } + if (!consistent) { + dropDescendants(path, nullptr); + entry.positions.clear(); + entry.lastKey.reset(); + store(entry, parent); + std::get<5>(parent.node) = static_cast(flagsOf(parent.node) | flag::childrenChanged); + served.push_back(std::move(parent.node)); + return 0; + } + } + store(entry, parent); + // The positions that no longer exist leave the memory with what was under them. + for (auto it = entry.positions.lower_bound(total); it != entry.positions.end(); it = entry.positions.erase(it)) + forget(it->second); + const auto budget = limits.responseBudget; + auto used = pageOverheadBytes + nodeBytes(parent.node); + served.push_back(parent.node); + if (!ops.container || (flagsOf(parent.node) & flag::depthReached) != 0 || start >= total || count == 0) + return 0; + + struct Pending { + std::size_t position; + Rendered node; + std::optional key; + }; + std::vector pending; + std::size_t fresh = 0; // the entries the page adds to the memory + ops.visit(view.node, start, count, [&](const ChildView& child) { + ChildView shown = child; + const auto key = usableKey(view.node, child.position); + if (key) + std::tie(shown.label, shown.labelCut) = visibleText(*key, maxTextBytes, true); + const auto told = numberSegment(ops.letter, child.rank); + const auto childAt = childPath(path, key ? 'k' + encodeKey(*key) : told); + auto rendered = render(shown, childAt, ops.keyed && !key, access.writable); + // A keyed child may yet be told by its position (a key that another child of the page has too): the page keeps + // room for the longer of its two paths. + const auto longer = (std::max)(childAt.size(), path.size() + 1 + told.size()); + const auto bytes = nodeBytes(rendered.node) + stringBytes(longer) - stringBytes(childAt.size()); + const bool added = !nodes.contains(childAt); + if (used + bytes > budget || (added && nodes.size() + fresh >= limits.maxNodes)) + return false; + used += bytes; + fresh += added ? 1 : 0; + pending.push_back({.position = child.position, .node = std::move(rendered), .key = key}); + return pending.size() < count; + }); + + // Two elements of a page with the same key break the key's contract: both are told by their position, and neither + // is writable (ADR-027, section 5). + std::map> seen; + for (const auto& child : pending) + if (child.key) + ++seen[*child.key]; + for (auto& child : pending) { + if (!child.key || seen.find(*child.key)->second < 2) + continue; + auto& node = child.node.node; + std::get<0>(node) = childPath(path, numberSegment(ops.letter, child.position)); + auto flags = flagsOf(node) & ~(flag::writable | flag::depthReached); + if (std::get<1>(node) != "opaque" && depthReached(std::get<0>(node), *child.node.ops)) + flags |= flag::depthReached; + std::get<5>(node) = static_cast(flags); + child.node.editor = nullptr; + child.key.reset(); + if (!access.duplicateKeysReported.exchange(true) && access.diagnose) + access.diagnose("The watch '" + access.label + "' has elements with the same key in one page: they are shown by their position"); + } + + std::vector replaced; + for (auto& child : pending) { + const std::string childAt = std::get<0>(child.node.node); // a copy: the node is moved into the memory below + if (const auto loaded = entry.positions.find(child.position); loaded != entry.positions.end() && loaded->second != childAt) + replaced.push_back(loaded->second); + entry.positions[child.position] = childAt; + served.push_back(child.node.node); + store(nodes[childAt], std::move(child.node)); + } + if (!replaced.empty()) { + std::set loaded; + for (const auto& [position, childAt] : entry.positions) + loaded.insert(childAt); + for (const auto& old : replaced) + if (!loaded.contains(old)) + forget(old); + } + if (!pending.empty()) { + entry.lastKey = pending.back().key; + entry.lastPosition = pending.back().position; + } + const auto after = start + pending.size(); + return after < total ? after : 0; + } + + /// Removes a node and its descendants. + void forget(const std::string& path) { + dropDescendants(path, nullptr); + nodes.erase(path); + } + + /// Starts a pass: compares the memory with the object in one read, keeps the differences with what the memory held, + /// and gives the memory the new values. + void compare(Access& access, const NodeRef& root) { + Pass started; + if (const auto found = nodes.find(std::string_view{}); found != nodes.end()) + walk(access, rootView(access, root), std::string{}, false, found->second, started.changes); + for (auto& change : started.changes) { + auto& entry = nodes.find(change.path)->second; + change.before = entry; + if (change.dropChildren) { + dropDescendants(change.path, &change.dropped); + entry.positions.clear(); + entry.lastKey.reset(); + } + Rendered kept = change.now; + std::get<5>(kept.node) = static_cast(flagsOf(kept.node) & ~flag::childrenChanged); + store(entry, std::move(kept)); + } + ++current; + if (!started.changes.empty()) + pass = std::move(started); + } + + /// Compares a node of the memory and, when it is unfolded, the structure of its children then each child loaded. + void walk(Access& access, const ChildView& view, const std::string& path, bool positional, const Entry& entry, std::vector& out) { + auto now = render(view, path, positional, access.writable); + const auto mark = out.size(); + if (now.node != entry.node || now.ops != entry.ops || now.aux != entry.aux) + out.push_back({.path = path, .now = now, .dropChildren = false, .before = {}, .dropped = {}}); + if (entry.positions.empty()) + return; + const auto& ops = *view.node.ops; + bool structure = now.ops != entry.ops || childrenOf(now.node) != childrenOf(entry.node); + // Each run of loaded positions is walked once (rule 3): a container without random access is not walked per child. + for (auto run = entry.positions.begin(); run != entry.positions.end() && !structure;) { + auto last = run; + std::size_t length = 1; + for (auto following = std::next(run); following != entry.positions.end() && following->first == last->first + 1; ++following) { + last = following; + ++length; + } + std::size_t visited = 0; + try { + ops.visit(view.node, run->first, length, [&](const ChildView& child) { + const auto loaded = entry.positions.find(child.position); + if (loaded == entry.positions.end()) + return true; + ++visited; + const std::string_view recorded = std::string_view{loaded->second}.substr(path.size() + 1); + ChildView shown = child; + bool byPlace = false; + // A keyed child is labelled by its key, also when it is told by its position (a key that repeats). + const auto key = usableKey(view.node, child.position); + if (key) + std::tie(shown.label, shown.labelCut) = visibleText(*key, maxTextBytes, true); + if (ops.keyed && recorded.starts_with('k')) { + if (!key || 'k' + encodeKey(*key) != recorded) { + structure = true; + return false; + } + } else { + byPlace = ops.keyed; + if (numberSegment(ops.letter, ops.keyed ? child.position : child.rank) != recorded) { + structure = true; + return false; + } + } + if (const auto found = nodes.find(loaded->second); found != nodes.end()) + walk(access, shown, loaded->second, byPlace, found->second, out); + return true; + }); + } catch (...) { + structure = true; + } + if (visited != length) + structure = true; + run = std::next(last); + } + if (structure) { + // The children are no longer those the memory holds: they leave it, and the inspector reads the list again. + out.resize(mark); + std::get<5>(now.node) = static_cast(flagsOf(now.node) | flag::childrenChanged); + out.push_back({.path = path, .now = std::move(now), .dropChildren = true, .before = {}, .dropped = {}}); + } + } + + /// The next page of the pass, read in the set it keeps. + Page serve(std::size_t count, const Limits& limits) { + std::vector served; + if (!pass) + return {std::move(served), 0.0, static_cast(current), false}; + auto used = pageOverheadBytes; + while (pass->served < pass->changes.size() && served.size() < count) { + const auto& node = pass->changes[pass->served].now.node; + const auto bytes = nodeBytes(node); + if (used + bytes > limits.responseBudget && !served.empty()) + break; + used += bytes; + served.push_back(node); + ++pass->served; + } + const auto next = pass->served < pass->changes.size() ? pass->served : 0; + if (next == 0) + pass.reset(); + return {std::move(served), static_cast(next), static_cast(current), false}; + } + + mutable std::mutex mutex; + std::uint64_t current = 1; + std::map> nodes; + std::optional pass; +}; + +} // namespace webfront::inspect::detail diff --git a/include/webfront/WatchValues.hpp b/include/webfront/WatchValues.hpp new file mode 100644 index 00000000..6b975ea0 --- /dev/null +++ b/include/webfront/WatchValues.hpp @@ -0,0 +1,1002 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-27 +// +// WebFront — core +// Role: How the inspectors read a C++ object as a tree of nodes (ADR-027, sections 3, 4 and 6): bounds, texts, paths, kinds, rendering. +// Thread: worker-safe | Alloc: unrestricted +// LLM: public API (Visit, PagedSource, Described, the bounds); the per-type tables are internal, read by WatchMemory.hpp + +#pragma once + +#include "BridgeError.hpp" +#include "components/forms/Description.hpp" +#include "http/BuffersPolicy.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() + #include + + #include +#endif + +namespace webfront::inspect { + +// --- Bounds (ADR-027, section 3) ------------------------------------------------------------------------------- + +/// A watch's name, the label and the value of a node, and the texts of a descriptor are at most this many UTF-8 bytes. +inline constexpr std::size_t maxTextBytes = 256; +/// The kind of a node is a word of the closed vocabulary below, at most this many bytes. +inline constexpr std::size_t maxKindBytes = 16; +/// A page holds 200 entries unless the inspector asks for another count, and never more than 1 000. +inline constexpr std::size_t defaultPageCount = 200; +inline constexpr std::size_t maxPageCount = 1000; +/// The bytes of an answer that are not its entries: the message header, the call identifier and the page's own fields. +inline constexpr std::size_t responseHeaderBytes = 64; +/// The smallest answer the inspectors must be able to send: a page of one node, with its header. +inline constexpr std::size_t minPageBytes = 4096; +/// A path is at most this many bytes and segments; an encoded key at most maxKeyBytes, else its element is told by its position. +inline constexpr std::size_t maxPathBytes = 1024; +inline constexpr std::size_t maxPathSegments = 64; +inline constexpr std::size_t maxKeyBytes = 128; +inline constexpr std::size_t maxIndexSegment = 21; // a letter and the 20 digits of 2^64 - 1 +inline constexpr std::size_t maxKeySegment = 1 + maxKeyBytes; // `k` and the encoded key +inline constexpr std::size_t maxNodeBytes = 2048; +/// The nodes a connection keeps of one watch, and the bytes of the snapshot of a full value. +inline constexpr std::size_t maxMemoryNodes = 10'000; +inline constexpr std::size_t maxSnapshotBytes = 16 * 1024 * 1024; +/// The smallest text an inspector must be able to write, whatever the policy. +inline constexpr std::size_t minWriteTextBytes = 1024; +/// What a write request takes besides its text, all its other arguments at their largest: the message header, the name +/// `webfront.inspector.write`, two numbers, the path and the expected value. +inline constexpr std::size_t writeRequestFixedBytes = 8 + (2 + 24) + 9 + 9 + (3 + maxPathBytes) + (3 + maxTextBytes); + +namespace detail { +/// The longest string that, with its header of 2, 3 or 5 bytes, takes at most `room` bytes on the wire. +[[nodiscard]] constexpr std::size_t longestStringIn(std::size_t room) noexcept { + if (room > 5 + 65535) + return room - 5; + if (room > 3 + 255) + return (std::min)(room - 3, 65535); + return room > 2 ? (std::min)(room - 2, 255) : 0; +} +} // namespace detail + +/// What an answer may take with the policy: it must fit both the encoding buffer and the message size. +template +inline constexpr std::size_t responseBudget = std::min(Policy::functionCallBufferSize, http::maxMessageSize()); +/// What a request may take: C++ closes a connection that announces a larger message (ADR-003). +template +inline constexpr std::size_t requestBudget = http::maxMessageSize(); +/// The longest text webfront.inspector.write accepts with the policy: what the request budget leaves once every other +/// argument is at its largest. +template +inline constexpr std::size_t maxWriteTextBytes = detail::longestStringIn( + requestBudget > writeRequestFixedBytes ? requestBudget - writeRequestFixedBytes : 0); + +/// The bounds an operation of the inspectors runs with; limitsOf() gives those of a buffers policy. +struct Limits { + std::size_t responseBudget; + std::size_t maxWriteTextBytes; + std::size_t maxNodes = maxMemoryNodes; + std::size_t maxSnapshotBytes = inspect::maxSnapshotBytes; +}; + +/** + * The bounds of a buffers policy. A policy too small for the inspectors does not compile with the developer environment, + * rather than failing while inspecting: an answer must hold a page of one node, and a write a text of 1 KiB. + */ +template +[[nodiscard]] constexpr Limits limitsOf() noexcept { + static_assert(responseBudget >= minPageBytes, + "The buffers policy is too small for the inspectors: an answer must hold a page of one node (ADR-027)"); + static_assert(maxWriteTextBytes >= minWriteTextBytes, + "The buffers policy is too small for the inspectors: a write must carry a text of 1 KiB (ADR-027)"); + return {.responseBudget = responseBudget, .maxWriteTextBytes = maxWriteTextBytes}; +} + +/// The error codes of the inspectors (typed codes of ADR-003). +namespace code { +inline constexpr std::string_view denied = "webfront.inspector.denied"; // the caller is not admitted +inline constexpr std::string_view unknown = "webfront.inspector.unknown"; // no such watch, path or node +inline constexpr std::string_view unavailable = "webfront.inspector.unavailable"; // the source did not give its object +inline constexpr std::string_view limit = "webfront.inspector.limit"; // depth reached, or the memory is full +inline constexpr std::string_view stale = "webfront.inspector.stale"; // what the inspector shows is no longer true +inline constexpr std::string_view parse = "webfront.inspector.parse"; // the text is not a value of the node +inline constexpr std::string_view readOnly = "webfront.inspector.readOnly"; // the node is not writable +inline constexpr std::string_view tooLarge = "webfront.inspector.tooLarge"; // the text is longer than maxWriteTextBytes +inline constexpr std::string_view refused = "webfront.inspector.refused"; // the application refused the value +} // namespace code + +/// The bits of a node's flags. +namespace flag { +inline constexpr unsigned writable = 1; +inline constexpr unsigned truncated = 2; +inline constexpr unsigned removed = 4; +inline constexpr unsigned depthReached = 8; +inline constexpr unsigned childrenChanged = 16; +} // namespace flag + +/// The prefix of the names reserved to the inspectors: cppFunction refuses them to the application (ADR-027, section 1). +inline constexpr std::string_view reservedPrefix = "webfront.inspector."; + +[[nodiscard]] inline bool isReservedName(std::string_view name) noexcept { + return name.starts_with(reservedPrefix); +} + +/// A node as the bridge carries it: (path, kind, label, value, children, flags). +using Node = std::tuple; +/// A page of nodes: (nodes, next, revision, resynchronize). `next` is 0 at the end. +using Page = std::tuple, double, double, bool>; +/// What webfront.inspector.write answers: (revision, code, message); the code is empty when the value was written. +using WriteAnswer = std::tuple; +/// What webfront.inspector.value answers: (fragment, total size, next offset, capped, snapshot). +using ValueAnswer = std::tuple; +/// What webfront.inspector.limits answers: (maxWriteTextBytes, responseBudget, nodes of the memory, bytes of a snapshot, +/// largest page count, default page count). +using LimitsAnswer = std::tuple; + +/// The largest number a page exchanges exactly with JavaScript (2^53). +inline constexpr double maxExactNumber = 9007199254740992.0; + +// --- Texts ----------------------------------------------------------------------------------------------------- + +/// The longest prefix of `text` of at most `limit` bytes that does not cut a UTF-8 character. +[[nodiscard]] inline std::string_view utf8Prefix(std::string_view text, std::size_t limit) noexcept { + if (text.size() <= limit) + return text; + std::size_t end = limit; + // Back to the first byte of the character that the limit cuts: continuation bytes are 10xxxxxx. + while (end > 0 && (static_cast(text[end]) & 0xC0u) == 0x80u) + --end; + return text.substr(0, end); +} + +namespace detail { +/// Appends `c` to `visible`, a control character as its visible picture (U+2400 to U+241F, U+2421 for DEL). +inline void appendVisible(std::string& visible, char c) { + const auto byte = static_cast(c); + if (byte < 0x20u || byte == 0x7Fu) { + const unsigned picture = byte == 0x7Fu ? 0x2421u : 0x2400u + byte; // three UTF-8 bytes: E2 90 xx + visible += static_cast(0xE2); + visible += static_cast(0x80u | ((picture >> 6) & 0x3Fu)); + visible += static_cast(0x80u | (picture & 0x3Fu)); + } else + visible += c; +} +inline constexpr std::string_view ellipsis = "\xE2\x80\xA6"; + +/// `text` with its control characters visible, cut to `limit` bytes on a character boundary (ending with "…" when +/// `mark`), and whether it was cut. Only the bytes needed to know it are read. +[[nodiscard]] inline std::pair visibleText(std::string_view text, std::size_t limit, bool mark) { + std::string visible; + visible.reserve((std::min)(text.size(), limit)); // parenthesized: Windows headers may define min + for (const char c : text) { + appendVisible(visible, c); + if (visible.size() > limit) + break; // the first byte past the limit is enough to know that it is cut, whatever the limit (npos included) + } + if (visible.size() <= limit) + return {std::move(visible), false}; + if (!mark || limit < ellipsis.size()) + return {std::string{utf8Prefix(visible, limit)}, true}; + std::string cut{utf8Prefix(visible, limit - ellipsis.size())}; + cut += ellipsis; + return {std::move(cut), true}; +} +} // namespace detail + +/// A text of the application made safe to show and bounded: control characters become their visible pictures (U+2400 +/// to U+241F, U+2421 for DEL), then the text is cut to `limit` bytes on a character boundary, ending with "…" when cut. +/// A limit too small for the ellipsis gives the longest prefix that fits, without it. +[[nodiscard]] inline std::string boundedText(std::string_view text, std::size_t limit = maxTextBytes) { + return detail::visibleText(text, limit, true).first; +} + +/// Where a watch was declared, "file:line", made visible as boundedText() does, then cut from its start when it is too long: +/// the end of the path, the file's name and the line, are what identify it. +[[nodiscard]] inline std::string locationText(std::string_view file, std::uint_least32_t line) { + std::string visible; + for (const char c : std::string(file) + ':' + std::to_string(line)) + detail::appendVisible(visible, c); + if (visible.size() <= maxTextBytes) + return visible; + std::size_t start = visible.size() - (maxTextBytes - detail::ellipsis.size()); + while (start < visible.size() && (static_cast(visible[start]) & 0xC0u) == 0x80u) + ++start; // a character is never cut: its first byte is not a continuation byte + return std::string(detail::ellipsis) + visible.substr(start); +} +[[nodiscard]] inline std::string locationText(const std::source_location& location) { + return locationText(location.file_name(), location.line()); +} + +/** + * @brief A bounded receiver (ADR-027, "Formatage borné"): what is written to it is stored up to its limit only, and it + * knows whether more was written. A string is copied up to the limit; a formattable value goes through + * std::format_to_n, which counts the size the whole output would have without storing it. + */ +class TextSink { +public: + explicit TextSink(std::size_t bound) : limit(bound) { } + + void append(std::string_view part) { + const auto room = limit - stored.size(); + if (part.size() > room) { + stored.append(part.substr(0, room)); + cut = true; + } else + stored.append(part); + } + void append(char c) { + if (stored.size() < limit) + stored += c; + else + cut = true; + } + template + void format(const T& value) { + const auto room = limit - stored.size(); + const auto result = std::format_to_n(std::back_inserter(stored), static_cast(room), "{}", value); + if (static_cast(result.size) > room) + cut = true; + } + [[nodiscard]] bool full() const noexcept { + return stored.size() >= limit; + } + [[nodiscard]] bool truncated() const noexcept { + return cut; + } + [[nodiscard]] const std::string& text() const noexcept { + return stored; + } + +private: + std::string stored; + std::size_t limit; + bool cut = false; +}; + +// --- Paths (ADR-027, section 3, "Encodage des chemins") -------------------------------------------------------- + +/// One segment of a path: `#` and an index or a rank, `.` and the rank of a described field, or `k` and a key. +struct Segment { + char letter = '#'; + std::uint64_t number = 0; + std::string key; + + friend bool operator==(const Segment&, const Segment&) = default; +}; + +namespace detail { +[[nodiscard]] constexpr bool unreservedByte(char c) noexcept { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' || c == '~'; +} +[[nodiscard]] constexpr int hexDigit(char c) noexcept { + return c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; +} +} // namespace detail + +/// A key in percent encoding: every byte outside `A-Z a-z 0-9 - . _ ~` becomes `%HH`. Reversible, and never holds a `/`. +[[nodiscard]] inline std::string encodeKey(std::string_view key) { + static constexpr std::string_view digits = "0123456789ABCDEF"; + std::string encoded; + encoded.reserve(key.size()); + for (const char c : key) { + if (detail::unreservedByte(c)) + encoded += c; + else { + const auto byte = static_cast(c); + encoded += '%'; + encoded += digits[byte >> 4]; + encoded += digits[byte & 0x0Fu]; + } + } + return encoded; +} + +/// The segment of an index, a rank or a field: its letter and the decimal number. +[[nodiscard]] inline std::string numberSegment(char letter, std::uint64_t number) { + return letter + std::to_string(number); +} + +/// The path of a child: its parent's path, `/`, and the segment. +[[nodiscard]] inline std::string childPath(std::string_view parent, std::string_view segment) { + std::string path; + path.reserve(parent.size() + 1 + segment.size()); + path += parent; + path += '/'; + path += segment; + return path; +} + +/// The path of the parent of a node that is not the root. +[[nodiscard]] inline std::string_view parentPath(std::string_view path) noexcept { + const auto cut = path.rfind('/'); + return cut == std::string_view::npos ? std::string_view{} : path.substr(0, cut); +} + +/** + * The segments of a path, or nothing for a path that is not one this C++ builds: more than 1 024 bytes or 64 segments, a + * segment without its letter, a number that is not the decimal text of a 64-bit number, a key longer than 128 bytes or + * that is not exactly what encodeKey() writes. The root is the empty path. + */ +[[nodiscard]] inline std::optional> parsePath(std::string_view path) { + std::vector segments; + if (path.empty()) + return segments; + if (path.size() > maxPathBytes || path.front() != '/') + return std::nullopt; + std::size_t start = 1; + while (true) { + const auto end = (std::min)(path.find('/', start), path.size()); + const auto text = path.substr(start, end - start); + if (text.empty() || segments.size() == maxPathSegments) + return std::nullopt; + Segment segment{.letter = text.front(), .number = 0, .key = {}}; + const auto rest = text.substr(1); + if (segment.letter == '#' || segment.letter == '.') { + const auto [parsed, error] = std::from_chars(rest.data(), rest.data() + rest.size(), segment.number); + // The one text of the number: no sign, no leading zero, nothing after the digits. + if (error != std::errc{} || parsed != rest.data() + rest.size() || std::to_string(segment.number) != rest) + return std::nullopt; + } else if (segment.letter == 'k') { + if (rest.size() > maxKeyBytes) + return std::nullopt; + for (std::size_t i = 0; i < rest.size(); ++i) { + if (detail::unreservedByte(rest[i])) + segment.key += rest[i]; + else if (rest[i] == '%' && i + 2 < rest.size() && detail::hexDigit(rest[i + 1]) >= 0 && detail::hexDigit(rest[i + 2]) >= 0) { + const char byte = static_cast(detail::hexDigit(rest[i + 1]) * 16 + detail::hexDigit(rest[i + 2])); + if (detail::unreservedByte(byte)) + return std::nullopt; // encodeKey() never encodes it: two texts would name one key + segment.key += byte; + i += 2; + } else + return std::nullopt; + } + } else + return std::nullopt; + segments.push_back(std::move(segment)); + if (end == path.size()) + return segments; + start = end + 1; + } +} + +// --- Sources and descriptions ---------------------------------------------------------------------------------- + +/** + * @brief Gives the inspectors the description of T (docs/FORMS.md): specialize it with a static `description()` that + * returns a `forms::Description`, and a T is shown as its fields (kind `described`), each writable within its bounds. + * + * template <> struct webfront::inspect::Described { + * static webfront::forms::Description description() { return {.name = "Settings", .fields = {...}}; } + * }; + * + * With C++26 reflection (components/forms/Reflection.hpp), `description()` returns `forms::describe()`. + */ +template +struct Described; + +template +concept HasDescription = requires { + { Described>::description() } -> std::same_as>>; +}; + +namespace detail { +/// What a PagedSource's visit() is checked with: it must accept any element. +struct AnyElement { + template + void operator()(Element&&) const noexcept { } +}; +} // namespace detail + +/** + * @brief A container that pages itself (ADR-027, section 5): `size()` and `visit(first, count, function)`, which calls + * `function(element)` for the elements at `first` to `first + count - 1`, in order. A page then costs what the application + * decides: it is the way of a very large container without random access, or of a content computed on demand. + */ +template +concept PagedSource = !std::ranges::range && requires(T& source, std::size_t position) { + { source.size() } -> std::convertible_to; + source.visit(position, position, detail::AnyElement{}); +}; + +/** + * @brief A PagedSource whose elements have keys: `key(position)` gives the key of an element and `find(key)` its position + * now, or nothing. The contract is a primary key's: a key names at most one element, and an element keeps its key while + * it exists. The path of an element then carries its key, so that an inspector follows it when the container changes. + */ +template +concept KeyedPagedSource = PagedSource && requires(T& source, std::size_t position, std::string_view key) { + { source.key(position) } -> std::convertible_to; + { source.find(key) } -> std::convertible_to>; +}; + +// --- Kinds (ADR-027, section 4) -------------------------------------------------------------------------------- + +namespace detail { +template +struct is_bitset : std::false_type { }; +template +struct is_bitset> : std::true_type { }; +template +struct is_optional : std::false_type { }; +template +struct is_optional> : std::true_type { }; +template +struct is_variant : std::false_type { }; +template +struct is_variant> : std::true_type { }; +template +struct is_tuple : std::false_type { }; +template +struct is_tuple> : std::true_type { }; +template +struct is_tuple> : std::true_type { }; +template +concept associative = std::ranges::sized_range && requires { + typename T::key_type; + typename T::mapped_type; +}; +template +concept text = std::is_same_v || std::is_same_v; +/// A type std::format can write. std::formattable alone misses the formatters written for std::format_context only, which +/// std::format accepts: the context it checks with is the library's own choice. +template +concept formattable = std::formattable + || (std::default_initializable> + && requires(const std::formatter& formatter, const T& value, std::format_context& context) { + { formatter.format(value, context) } -> std::same_as; + }); +} // namespace detail + +namespace detail { +/// What a type is for the inspectors, in the order of ADR-027 section 4. T keeps its constness: a container that only a +/// non-constant object can walk is not one when it is constant. +enum class Shape : std::uint8_t { boolean, integer, real, string, bitset, optional, variant, tuple, map, sequence, paged, described, formatted, opaque }; + +template +[[nodiscard]] constexpr Shape shapeOf() noexcept { + using U = std::remove_cv_t; + if constexpr (std::is_same_v) + return Shape::boolean; + else if constexpr (std::is_integral_v) + return Shape::integer; + else if constexpr (std::is_floating_point_v) + return Shape::real; + else if constexpr (text) + return Shape::string; + else if constexpr (is_bitset::value) + return Shape::bitset; + else if constexpr (is_optional::value) + return Shape::optional; + else if constexpr (is_variant::value) + return Shape::variant; + else if constexpr (is_tuple::value) + return Shape::tuple; + else if constexpr (associative && std::ranges::sized_range) + return Shape::map; + else if constexpr (std::ranges::sized_range) + return Shape::sequence; + else if constexpr (PagedSource) + return Shape::paged; + else if constexpr (HasDescription) + return Shape::described; + else if constexpr (formattable) + return Shape::formatted; + else + return Shape::opaque; +} + +[[nodiscard]] constexpr std::string_view kindName(Shape shape) noexcept { + constexpr std::array + names{"bool", "integer", "real", "string", "bitset", "optional", "variant", "tuple", "map", "sequence", "sequence", "described", "formatted", "opaque"}; + return names[static_cast(shape)]; +} +} // namespace detail + +/** + * The kind of a node of type T, in the order of ADR-027 section 4: scalars, strings and bitsets, then optional, variant and + * tuples, then sized ranges, associative containers and paged sources, then a described type, then a type std::format can + * write, else `opaque`. The fields of a described type have the kinds of their members, `enum` for a choice. + */ +template +[[nodiscard]] constexpr std::string_view kindOf() noexcept { + return detail::kindName(detail::shapeOf>()); +} + +// --- Rendering ------------------------------------------------------------------------------------------------- + +namespace detail { + +/// A reference to a callable that outlives the call it is passed to: what an enumeration of children calls for each. +template +class FunctionRef; +template +class FunctionRef { +public: + template + requires(!std::same_as, FunctionRef>) && std::is_invocable_r_v + FunctionRef(F&& function) noexcept // NOLINT(google-explicit-constructor): a callable is passed where one is expected + : object(const_cast(static_cast(std::addressof(function)))), call([](void* target, Args... args) -> R { + return (*static_cast*>(target))(std::forward(args)...); + }) { } + R operator()(Args... args) const { + return call(object, std::forward(args)...); + } + +private: + void* object; + R (*call)(void*, Args...); +}; + +struct NodeOps; + +/// A node of the object being read: valid only during the call that gives it. `aux` is the field of a described member. +struct NodeRef { + void* object = nullptr; + const NodeOps* ops = nullptr; + const void* aux = nullptr; +}; + +/// A child as its parent enumerates it. `rank` is the number of its segment: its position, or the index of the +/// alternative a variant holds. +struct ChildView { + std::size_t position = 0; + std::size_t rank = 0; + NodeRef node; + std::string label; // visible and bounded + bool labelCut = false; // the label is not the whole one: the node is not writable +}; + +using ChildFn = FunctionRef; // false stops the enumeration + +/// Thrown by an editor for a text that is not a value of the node, and by an applier that the object refuses. +struct ParseError : std::runtime_error { + using std::runtime_error::runtime_error; +}; +struct RefusedError : std::runtime_error { + using std::runtime_error::runtime_error; +}; + +/// Writes a value already parsed into the node; the node is the one the editor came from (same type, same field). +using Applier = std::function; +/// Parses a text for a node, without the object: throws ParseError, else gives what writes the value. +using Editor = std::function; + +/// How a type is read: one table per type, shared by every node of that type. +struct NodeOps { + std::string_view (*kind)(const NodeRef&); + void (*value)(const NodeRef&, TextSink&); // may throw what a std::formatter throws + std::size_t (*size)(const NodeRef&); // the number of children; may throw what a PagedSource throws + void (*visit)(const NodeRef&, std::size_t first, std::size_t count, ChildFn each); + std::optional (*key)(const NodeRef&, std::size_t position); // of a keyed source + std::optional (*find)(const NodeRef&, std::string_view key); + Editor (*editor)(const NodeRef&); // null when values of the type cannot be written + bool container = false; // may have children + bool keyed = false; // its children have keys + bool alternative = false; // its one child is told by the rank of an alternative, not by its position + char letter = '#'; // of its children's segments +}; + +template +const NodeOps& opsOf() noexcept; + +[[nodiscard]] inline std::string typeName(const std::type_info& type) { +#if __has_include() + int status = 0; + char* demangled = abi::__cxa_demangle(type.name(), nullptr, nullptr, &status); + std::string name{status == 0 && demangled != nullptr ? demangled : type.name()}; + std::free(demangled); // NOLINT(cppcoreguidelines-no-malloc): the ABI allocates it with malloc + return name; +#else + return type.name(); +#endif +} + +template +void appendNumber(TextSink& sink, F value) { + std::array digits{}; + const auto end = std::to_chars(digits.data(), digits.data() + digits.size(), value).ptr; + sink.append(std::string_view{digits.data(), static_cast(end - digits.data())}); +} +template +void appendNumber(TextSink& sink, I value) { + std::array digits{}; + // A character type is shown as its number: to_chars has no overload for some of them. + const auto end = std::is_signed_v ? std::to_chars(digits.data(), digits.data() + digits.size(), static_cast(value)).ptr + : std::to_chars(digits.data(), digits.data() + digits.size(), static_cast(value)).ptr; + sink.append(std::string_view{digits.data(), static_cast(end - digits.data())}); +} + +template +[[nodiscard]] T& objectOf(const NodeRef& node) noexcept { + return *static_cast(node.object); +} + +/// A child of type E at `address`; a constant element gives a constant node, which no editor writes. +template +[[nodiscard]] NodeRef refOf(E& element) noexcept { + return {.object = const_cast(static_cast(std::addressof(element))), .ops = &opsOf(), .aux = nullptr}; +} + +[[nodiscard]] inline ChildView indexedChild(std::size_t position, NodeRef node) { + return {.position = position, .rank = position, .node = node, .label = '[' + std::to_string(position) + ']', .labelCut = false}; +} + +/// The description of T, built once. +template +[[nodiscard]] const forms::Description& descriptionOf() { + static const forms::Description description = [] { + auto built = Described::description(); + forms::validate(built); + return built; + }(); + return description; +} + +/// The field of a described type T: `aux` is its forms::Field, `object` the T. +template +struct FieldRender { + using Plain = std::remove_const_t; + static const forms::Field& field(const NodeRef& node) noexcept { + return *static_cast*>(node.aux); + } + static std::string_view kind(const NodeRef& node) { + switch (field(node).kind) { + case forms::Kind::boolean: + return "bool"; + case forms::Kind::integer: + return "integer"; + case forms::Kind::number: + return "real"; + case forms::Kind::text: + return "string"; + case forms::Kind::choice: + return "enum"; + } + return "opaque"; + } + static void value(const NodeRef& node, TextSink& sink) { + sink.append(field(node).read(objectOf(node))); + } + static std::size_t size(const NodeRef&) { + return 0; + } + static void visit(const NodeRef&, std::size_t, std::size_t, ChildFn) { } + /// The text is checked without the object as far as the description tells (kind, bounds, choices); the member's own + /// type, which only its accessor knows, is checked when the value is written. + static Editor editor(const NodeRef& node) { + const auto* described = &field(node); + return [described](std::string_view text) -> Applier { + switch (described->kind) { + case forms::Kind::boolean: + if (text != "true" && text != "false") + throw ParseError("A boolean is true or false"); + break; + case forms::Kind::integer: + case forms::Kind::number: { + const auto number = forms::detail::parseFloating(text); + // "0" underflows nothing; a text the double parser refuses may still be a whole number beyond 2^53. + long long whole = 0; + unsigned long long big = 0; + const bool exact = std::from_chars(text.data(), text.data() + text.size(), whole).ptr == text.data() + text.size() + || std::from_chars(text.data(), text.data() + text.size(), big).ptr == text.data() + text.size(); + if (!number && !exact) + throw ParseError("Not a number"); + if (described->kind == forms::Kind::integer && !exact && std::trunc(*number) != *number) + throw ParseError("Not a whole number"); + if (number && described->range && (*number < described->range->min || *number > described->range->max)) + throw ParseError("Out of the bounds " + forms::detail::formatNumber(described->range->min) + " to " + + forms::detail::formatNumber(described->range->max)); + break; + } + case forms::Kind::text: + break; + case forms::Kind::choice: + if (std::ranges::find(described->choices, text) == described->choices.end()) + throw ParseError("Not one of the choices"); + break; + } + return [described, value = std::string(text)](const NodeRef& target) { + if (!described->write(objectOf(target), value)) + throw RefusedError("The member does not take this value"); + }; + }; + } + static constexpr NodeOps ops{.kind = &kind, + .value = &value, + .size = &size, + .visit = &visit, + .key = nullptr, + .find = nullptr, + .editor = std::is_const_v ? nullptr : &editor, + .container = false, + .keyed = false, + .alternative = false, + .letter = '#'}; +}; + +/// How a T is read. T keeps its constness: a constant object has no editor, and its children are constant. +template +struct Render { + using U = std::remove_cv_t; + static constexpr Shape shape = shapeOf(); + + static std::string_view kind(const NodeRef&) { + return kindName(shape); + } + + static void value(const NodeRef& node, TextSink& sink) { + [[maybe_unused]] const auto& object = objectOf(node); + if constexpr (shape == Shape::boolean) + sink.append(object ? std::string_view{"true"} : std::string_view{"false"}); + else if constexpr (shape == Shape::integer || shape == Shape::real) + appendNumber(sink, object); + else if constexpr (shape == Shape::string) + sink.append(std::string_view{object}); + else if constexpr (shape == Shape::bitset) { + for (std::size_t bit = object.size(); bit > 0 && !sink.truncated(); --bit) + sink.append(object[bit - 1] ? '1' : '0'); + } else if constexpr (shape == Shape::optional) + sink.append(object ? std::string_view{"engaged"} : std::string_view{"nullopt"}); + else if constexpr (shape == Shape::variant) { + if (object.valueless_by_exception()) + sink.append(std::string_view{"valueless"}); + else { + sink.append(std::string_view{"alternative "}); + appendNumber(sink, object.index()); + } + } else if constexpr (shape == Shape::described) + sink.append(descriptionOf().name); + else if constexpr (shape == Shape::formatted) + sink.format(object); + else if constexpr (shape == Shape::opaque) { + sink.append(typeName(typeid(U))); + sink.append(std::string_view{" (not displayable)"}); + } + // A tuple or a container shows nothing beside the number of its children, which are its content. + } + + static std::size_t size(const NodeRef& node) { + [[maybe_unused]] auto& object = objectOf(node); + if constexpr (shape == Shape::optional) + return object ? 1 : 0; + else if constexpr (shape == Shape::variant) + return object.valueless_by_exception() ? 0 : 1; + else if constexpr (shape == Shape::tuple) + return std::tuple_size_v; + else if constexpr (shape == Shape::map || shape == Shape::sequence) + return static_cast(std::ranges::size(object)); + else if constexpr (shape == Shape::paged) + return static_cast(object.size()); + else if constexpr (shape == Shape::described) + return descriptionOf().fields.size(); + else + return 0; + } + + template + static void visitTuple(T& object, std::size_t first, std::size_t count, ChildFn each, std::index_sequence) { + [[maybe_unused]] const auto one = [&](std::size_t index, auto& member) { + if (index < first || index - first >= count) + return true; + ChildView child = indexedChild(index, refOf(member)); + child.label = std::to_string(index); + return each(child); + }; + static_cast((one(I, std::get(object)) && ...)); + } + + template + static void visitAlternative(T& object, ChildFn each, std::index_sequence) { + const auto one = [&](std::size_t index, auto* alternative) { + if (alternative == nullptr) + return false; + ChildView child = indexedChild(0, refOf(*alternative)); + child.rank = index; + child.label = std::to_string(index); + static_cast(each(child)); + return true; + }; + static_cast((one(I, std::get_if(&object)) || ...)); + } + + /// One element of a range or of a paged source: an lvalue is read where it is, anything else through a constant copy. + template + static bool element(std::size_t position, Element&& item, ChildFn each) { + if constexpr (std::is_lvalue_reference_v) + return elementAt(position, item, each); + else { + const std::remove_cvref_t copy{std::forward(item)}; + return elementAt(position, copy, each); + } + } + template + static bool elementAt(std::size_t position, Item& item, ChildFn each) { + if constexpr (shape == Shape::map) { + // The node is the mapped value; its label is the key, formatted as a value is. + TextSink sink{maxTextBytes + 1}; + try { + opsOf().value(refOf(item.first), sink); + } catch (const std::exception& error) { + sink.append(std::string_view{error.what()}); + } + auto [label, cut] = visibleText(sink.text(), maxTextBytes, true); + return each(ChildView{.position = position, .rank = position, .node = refOf(item.second), .label = std::move(label), .labelCut = cut}); + } else + return each(indexedChild(position, refOf(item))); + } + + static void visit(const NodeRef& node, std::size_t first, std::size_t count, ChildFn each) { + [[maybe_unused]] auto& object = objectOf(node); + if (count == 0) + return; + if constexpr (shape == Shape::optional) { + if (first == 0 && object) { + ChildView child = indexedChild(0, refOf(*object)); + child.label = "value"; + static_cast(each(child)); + } + } else if constexpr (shape == Shape::variant) { + if (first == 0) + visitAlternative(object, each, std::make_index_sequence>{}); + } else if constexpr (shape == Shape::tuple) + visitTuple(object, first, count, each, std::make_index_sequence>{}); + else if constexpr (shape == Shape::map || shape == Shape::sequence) { + const auto total = static_cast(std::ranges::size(object)); + if (first >= total) + return; + const auto last = count > total - first ? total : first + count; + auto it = std::ranges::begin(object); + // A random-access range reaches the position at once; any other is walked from its start. + std::ranges::advance(it, static_cast>(first), std::ranges::end(object)); + for (std::size_t position = first; position < last && it != std::ranges::end(object); ++position, ++it) + if (!element(position, *it, each)) + return; + } else if constexpr (shape == Shape::paged) { + std::size_t position = first; + bool more = true; + object.visit(first, count, [&](auto&& item) { + // A source cannot be stopped: what it gives after the page is full, or beyond what was asked, is ignored. + if (more && position - first < count) + more = element(position, std::forward(item), each); + ++position; + }); + } else if constexpr (shape == Shape::described) { + const auto& fields = descriptionOf().fields; + for (std::size_t rank = first; rank < fields.size() && rank - first < count; ++rank) { + auto [label, cut] = visibleText(fields[rank].label, maxTextBytes, true); + if (!each(ChildView{ + .position = rank, + .rank = rank, + .node = NodeRef{.object = node.object, .ops = &FieldRender::ops, .aux = &fields[rank]}, + .label = std::move(label), + .labelCut = cut + })) + return; + } + } else + static_cast(first), static_cast(each); + } + + static std::optional key(const NodeRef& node, std::size_t position) { + if constexpr (KeyedPagedSource) + return std::string(objectOf(node).key(position)); + else + return static_cast(node), static_cast(position), std::nullopt; + } + static std::optional find(const NodeRef& node, std::string_view wanted) { + if constexpr (KeyedPagedSource) + return objectOf(node).find(wanted); + else + return static_cast(node), static_cast(wanted), std::nullopt; + } + + static Editor editor(const NodeRef&) { + return [](std::string_view input) -> Applier { + if constexpr (shape == Shape::boolean) { + if (input != "true" && input != "false") + throw ParseError("A boolean is true or false"); + return [value = input == "true"](const NodeRef& target) { + objectOf(target) = value; + }; + } else if constexpr (shape == Shape::integer || shape == Shape::real) { + const auto parsed = forms::detail::parseNumber(input); + if (!parsed) + throw ParseError(std::is_floating_point_v ? "Not a finite number" : "Not a whole number of the value's type"); + return [value = *parsed](const NodeRef& target) { + objectOf(target) = value; + }; + } else if constexpr (std::is_same_v) { + return [value = std::string(input)](const NodeRef& target) { + objectOf(target) = value; + }; + } else if constexpr (shape == Shape::bitset) { + if (input.size() != U{}.size() || input.find_first_not_of("01") != std::string_view::npos) + throw ParseError("A bitset is written as " + std::to_string(U{}.size()) + " binary digits"); + U value; + for (std::size_t bit = 0; bit < input.size(); ++bit) + value[input.size() - 1 - bit] = input[bit] == '1'; + return [value](const NodeRef& target) { + objectOf(target) = value; + }; + } else + return static_cast(input), Applier{}; + }; + } + + static constexpr bool editable = !std::is_const_v + && (shape == Shape::boolean || shape == Shape::integer || shape == Shape::real || shape == Shape::bitset + || std::is_same_v); + static constexpr bool hasChildren = shape == Shape::optional || shape == Shape::variant || shape == Shape::tuple || shape == Shape::map + || shape == Shape::sequence || shape == Shape::paged || shape == Shape::described; + + static constexpr NodeOps ops{.kind = &kind, + .value = &value, + .size = &size, + .visit = &visit, + .key = &key, + .find = &find, + .editor = editable ? &editor : nullptr, + .container = hasChildren, + .keyed = KeyedPagedSource, + .alternative = shape == Shape::variant, + .letter = shape == Shape::described ? '.' : '#'}; +}; + +template +const NodeOps& opsOf() noexcept { + return Render>::ops; +} + +} // namespace detail + +/** + * @brief What a watch's visitor source receives: WebFront calls the source with a Visit, and the source calls it once with + * the object, under its own lock, so that the whole operation runs while the object is safe to read. `Visit` + * only reads; `Visit` makes the watch writable. + */ +template +class Visit { +public: + using Object = T; + + explicit Visit(std::function visitor) : run(std::move(visitor)) { } + + void operator()(T& object) const { + run(object); + } + +private: + std::function run; +}; + +} // namespace webfront::inspect diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index 624d171a..a2fec538 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -3,220 +3,30 @@ // Created: 2026-11-25 // // WebFront — core -// Role: The registry of the watches an application declares for the inspectors (ADR-027), and its discovery page. +// Role: The watches an application declares for the inspectors (ADR-027): their sources, their registry, their handle and their operations. // Thread: thread-safe | Alloc: unrestricted -// LLM: public API (Watch, Visit) and the bounds of ADR-027 section 3; the registry is read by webfront.inspector.watches +// LLM: public API (Watch, Visit, PagedSource in WatchValues.hpp); the registry answers webfront.inspector.watches, children, changes, value, fold, reset and +// write #pragma once -#include "http/BuffersPolicy.hpp" +#include "Task.hpp" +#include "WatchMemory.hpp" #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include namespace webfront::inspect { -// --- Bounds (ADR-027, section 3) ------------------------------------------------------------------------------- - -/// A watch's name, and the texts of a descriptor (name, location), are at most this many UTF-8 bytes. -inline constexpr std::size_t maxTextBytes = 256; -/// The kind of a node is a word of the closed vocabulary below, at most this many bytes. -inline constexpr std::size_t maxKindBytes = 16; -/// A page holds 200 entries unless the inspector asks for another count, and never more than 1 000. -inline constexpr std::size_t defaultPageCount = 200; -inline constexpr std::size_t maxPageCount = 1000; -/// The bytes of an answer that are not its entries: the message header, the call identifier and the page's own fields. -inline constexpr std::size_t responseHeaderBytes = 64; -/// The smallest answer the inspectors must be able to send: a page of one node, with its header. -inline constexpr std::size_t minPageBytes = 4096; - -/// What an answer may take with the policy: it must fit both the encoding buffer and the message size. -template -inline constexpr std::size_t responseBudget = std::min(Policy::functionCallBufferSize, http::maxMessageSize()); - -/// The error codes of the inspectors (typed codes of ADR-003): the caller is not admitted, or names a watch that is gone. -namespace code { -inline constexpr std::string_view denied = "webfront.inspector.denied"; -inline constexpr std::string_view unknown = "webfront.inspector.unknown"; -inline constexpr std::string_view unavailable = "webfront.inspector.unavailable"; -} // namespace code - -/// The prefix of the names reserved to the inspectors: cppFunction refuses them to the application (ADR-027, section 1). -inline constexpr std::string_view reservedPrefix = "webfront.inspector."; - -[[nodiscard]] inline bool isReservedName(std::string_view name) noexcept { - return name.starts_with(reservedPrefix); -} - -// --- Texts ----------------------------------------------------------------------------------------------------- - -/// The longest prefix of `text` of at most `limit` bytes that does not cut a UTF-8 character. -[[nodiscard]] inline std::string_view utf8Prefix(std::string_view text, std::size_t limit) noexcept { - if (text.size() <= limit) - return text; - std::size_t end = limit; - // Back to the first byte of the character that the limit cuts: continuation bytes are 10xxxxxx. - while (end > 0 && (static_cast(text[end]) & 0xC0u) == 0x80u) - --end; - return text.substr(0, end); -} - -namespace detail { -/// Appends `c` to `visible`, a control character as its visible picture (U+2400 to U+241F, U+2421 for DEL). -inline void appendVisible(std::string& visible, char c) { - const auto byte = static_cast(c); - if (byte < 0x20u || byte == 0x7Fu) { - const unsigned picture = byte == 0x7Fu ? 0x2421u : 0x2400u + byte; // three UTF-8 bytes: E2 90 xx - visible += static_cast(0xE2); - visible += static_cast(0x80u | ((picture >> 6) & 0x3Fu)); - visible += static_cast(0x80u | (picture & 0x3Fu)); - } else - visible += c; -} -inline constexpr std::string_view ellipsis = "\xE2\x80\xA6"; -} // namespace detail - -/// A text of the application made safe to show and bounded: control characters become their visible pictures (U+2400 -/// to U+241F, U+2421 for DEL), then the text is cut to `limit` bytes on a character boundary, ending with "…" when cut. -/// A limit too small for the ellipsis gives the longest prefix that fits, without it. -[[nodiscard]] inline std::string boundedText(std::string_view text, std::size_t limit = maxTextBytes) { - std::string visible; - visible.reserve((std::min)(text.size(), limit)); // parenthesized: Windows headers may define min - for (const char c : text) { - detail::appendVisible(visible, c); - if (visible.size() > limit) - break; // the first byte past the limit is enough to know that it is cut, whatever the limit (npos included) - } - if (visible.size() <= limit) - return visible; - if (limit < detail::ellipsis.size()) - return std::string{utf8Prefix(visible, limit)}; - std::string cut{utf8Prefix(visible, limit - detail::ellipsis.size())}; - cut += detail::ellipsis; - return cut; -} - -/// Where a watch was declared, "file:line", made visible as boundedText() does, then cut from its start when it is too long: -/// the end of the path, the file's name and the line, are what identify it. -[[nodiscard]] inline std::string locationText(std::string_view file, std::uint_least32_t line) { - std::string visible; - for (const char c : std::string(file) + ':' + std::to_string(line)) - detail::appendVisible(visible, c); - if (visible.size() <= maxTextBytes) - return visible; - std::size_t start = visible.size() - (maxTextBytes - detail::ellipsis.size()); - while (start < visible.size() && (static_cast(visible[start]) & 0xC0u) == 0x80u) - ++start; // a character is never cut: its first byte is not a continuation byte - return std::string(detail::ellipsis) + visible.substr(start); -} -[[nodiscard]] inline std::string locationText(const std::source_location& location) { - return locationText(location.file_name(), location.line()); -} - -// --- Kinds (ADR-027, section 4) -------------------------------------------------------------------------------- - -namespace detail { -template -struct is_bitset : std::false_type { }; -template -struct is_bitset> : std::true_type { }; -template -struct is_optional : std::false_type { }; -template -struct is_optional> : std::true_type { }; -template -struct is_variant : std::false_type { }; -template -struct is_variant> : std::true_type { }; -template -struct is_tuple : std::false_type { }; -template -struct is_tuple> : std::true_type { }; -template -struct is_tuple> : std::true_type { }; -template -concept associative = std::ranges::sized_range && requires { - typename T::key_type; - typename T::mapped_type; -}; -} // namespace detail - -/** - * The kind of a node of type T, in the order of ADR-027 section 4: scalars, strings and bitsets, then optional, variant and - * tuples, then sized ranges and associative containers, then a type std::format can write, else `opaque`. Enumerations and - * described types (`enum`, `described`) are recognized once a description is given to the watch. - */ -template -[[nodiscard]] constexpr std::string_view kindOf() noexcept { - using U = std::remove_cvref_t; - if constexpr (std::is_same_v) - return "bool"; - else if constexpr (std::is_integral_v) - return "integer"; - else if constexpr (std::is_floating_point_v) - return "real"; - else if constexpr (std::is_same_v || std::is_same_v) - return "string"; - else if constexpr (detail::is_bitset::value) - return "bitset"; - else if constexpr (detail::is_optional::value) - return "optional"; - else if constexpr (detail::is_variant::value) - return "variant"; - else if constexpr (detail::is_tuple::value) - return "tuple"; - else if constexpr (detail::associative) - return "map"; - else if constexpr (std::ranges::sized_range) - return "sequence"; - else if constexpr (std::formattable) - return "formatted"; - else - return "opaque"; -} - // --- Sources (ADR-027, section 5) ------------------------------------------------------------------------------ -/** - * @brief What a watch's visitor source receives: WebFront calls the source with a Visit, and the source calls it once with - * the object, under its own lock, so that the whole operation runs while the object is safe to read. `Visit` - * only reads; `Visit` makes the watch writable. - */ -template -class Visit { -public: - using Object = T; - - explicit Visit(std::function visitor) : run(std::move(visitor)) { } - - void operator()(T& object) const { - run(object); - } - -private: - std::function run; -}; - namespace detail { template struct visit_object { }; @@ -225,31 +35,32 @@ struct visit_object> { using type = T; }; +/// The parameters of a call signature, as a tuple. template -struct single_parameter { }; -template -struct single_parameter { - using type = A; +struct parameter_list { }; +template +struct parameter_list { + using type = std::tuple; }; -template -struct single_parameter : single_parameter { }; -template -struct single_parameter : single_parameter { }; -template -struct single_parameter : single_parameter { }; -template -struct single_parameter : single_parameter { }; -template -struct single_parameter : single_parameter { }; +template +struct parameter_list : parameter_list { }; +template +struct parameter_list : parameter_list { }; +template +struct parameter_list : parameter_list { }; +template +struct parameter_list : parameter_list { }; +template +struct parameter_list : parameter_list { }; // Callable on an lvalue only, as the stored source is invoked. -template -struct single_parameter : single_parameter { }; -template -struct single_parameter : single_parameter { }; -template -struct single_parameter : single_parameter { }; -template -struct single_parameter : single_parameter { }; +template +struct parameter_list : parameter_list { }; +template +struct parameter_list : parameter_list { }; +template +struct parameter_list : parameter_list { }; +template +struct parameter_list : parameter_list { }; template struct call_signature { @@ -261,15 +72,36 @@ struct call_signature { using type = decltype(&Source::operator()); }; -/// The object a visitor source visits, when Source is one: a callable whose one parameter is a Visit. +/// The object a visitor visits, from the parameters of its source: (Visit), or (State&, Visit) for an owning source. +template +struct visited { }; +template + requires requires { typename visit_object>::type; } +struct visited> { + using type = typename visit_object>::type; + static constexpr bool stateful = false; +}; +template + requires requires { typename visit_object>::type; } +struct visited> { + using type = typename visit_object>::type; + static constexpr bool stateful = true; +}; + +template +concept visitor_source = requires { typename visited::type>::type>::type; } + && !visited::type>::type>::stateful; + template -concept visitor_source = requires { typename visit_object::type>::type>>::type; }; +concept stateful_visitor_source = requires { typename visited::type>::type>::type; } + && visited::type>::type>::stateful; } // namespace detail /** * @brief How a watch reaches its object, deduced from its source: a visitor (`[&](Visit visit) { ... visit(object); }`), - * or an accessor that returns a reference or a copy (`[&] -> const T& { return object; }`). Only a visitor of a non-constant - * object is writable: a reference read on the server thread is not, and a copy is not the object (ADR-027, section 6). + * or an accessor that returns a reference or a copy (`[&] -> const T& { return object; }`). A visitor of a non-constant + * object is writable; an accessor is writable only when it returns a non-constant reference and the watch has an executor, + * and a copy never is: it is not the object (ADR-027, section 6). */ template struct SourceShape; @@ -277,8 +109,7 @@ struct SourceShape; template requires detail::visitor_source struct SourceShape { - using Object = - typename detail::visit_object::type>::type>>::type; + using Object = typename detail::visited::type>::type>::type; static constexpr bool visitor = true; static constexpr bool writable = !std::is_const_v; }; @@ -295,6 +126,55 @@ struct SourceShape { template concept WatchSource = requires { typename SourceShape>::Object; }; +/** + * @brief The shape of an owning source (ADR-027, section 5): the watch keeps a `std::shared_ptr` alive during each + * operation and the source receives the state, `[](State& state, Visit visit) { std::scoped_lock lock{state.mutex}; + * visit(state.value); }` or `[](State& state) -> T& { return state.value; }`. A source of the ordinary shapes is accepted + * too, when it captures nothing that the state does not keep alive. + */ +template +struct OwnedSourceShape; + +template + requires detail::stateful_visitor_source + && std::invocable::type>::type>::type>> +struct OwnedSourceShape { + using Object = typename detail::visited::type>::type>::type; + static constexpr bool visitor = true; + static constexpr bool stateful = true; + static constexpr bool writable = !std::is_const_v; +}; + +template + requires(!detail::stateful_visitor_source && !detail::visitor_source && std::invocable + && !std::is_void_v>) +struct OwnedSourceShape { + using Object = std::remove_reference_t>; + static constexpr bool visitor = false; + static constexpr bool stateful = true; + static constexpr bool writable = false; +}; + +template + requires(!detail::stateful_visitor_source && !std::invocable && WatchSource) +struct OwnedSourceShape : SourceShape { + static constexpr bool stateful = false; +}; + +template +concept OwnedWatchSource = requires { typename OwnedSourceShape, State>::Object; }; + +/// The executor of a watch: what owns the object's thread (`app.uiExecutor()`, a host's loop). `schedule()` gives a sender +/// that completes there; the operations of a watch are run in the order they are scheduled. +template +concept WatchExecutor = std::copy_constructible && requires(const Executor& executor) { executor.schedule(); }; + +/// The application's own way to write a value of a watch of T: `mutate(object, path, text)`, which throws to refuse it. +template +concept WatchMutator = !std::is_const_v && std::invocable; + // --- Registry -------------------------------------------------------------------------------------------------- /// A watch as webfront.inspector.watches describes it: (identifier, name, kind of the root, "file:line", writable). @@ -302,57 +182,165 @@ using Descriptor = std::tuple, double, double, bool>; -/// The largest number a page exchanges exactly with JavaScript (2^53). -inline constexpr double maxExactNumber = 9007199254740992.0; +namespace detail { + +/// Runs `work` on the executor's thread; the task itself resumes where it was awaited. +template +ResultTask hopOn(Executor executor, std::function work) { + co_await networking::ex::then(executor.schedule(), std::move(work)); +} + +/// A registered watch. Its operations hold it, so that a source that owns its state outlives a handle destroyed meanwhile. +struct WatchCore { + std::uint64_t id = 0; + std::string name; // as the application gave it: what makes a watch unique + std::string kind; + std::string location; // "file:line", visible and bounded + bool owned = false; // the source keeps its state alive: destroying the handle never waits + Access access; + /// Runs an operation on the watch's executor; empty when the operations run on the thread that asks. + std::function(std::function)> hop; + std::shared_ptr keep; // what a source registered without access captures + + std::mutex lifecycle; + std::condition_variable idle; + std::vector running; // the threads inside an operation + bool removed = false; +}; + +/// What a connection reads of a full value: one at a time, told by an identifier never reused while the connection lives. +struct Snapshot { + std::uint64_t id = 0; + std::uint64_t watch = 0; + std::string path; + std::string text; + std::size_t next = 0; + bool capped = false; +}; + +} // namespace detail /** - * @brief The watches of an application (ADR-027, section 3, "Découverte"). Each registration gets an identifier that is - * never reused while the registry lives, and the registry's revision changes at each registration and each removal. - * Reading it calls no source: it is a read of the table. Thread-safe. + * @brief What the inspectors keep for one connection: its memory of each watch and its snapshot of a full value. Freed + * when the connection closes (WatchRegistry::forget). + */ +class WatchSession { +public: + /// The memory of a watch for this connection, created empty at its first call. + [[nodiscard]] std::shared_ptr memory(std::uint64_t watch) { + std::scoped_lock lock{mutex}; + if (closed) + throw webfront::detail::makeBridgeError(bridge_code::disconnected, "The connection is closed"); + auto& kept = memories[watch]; + if (!kept) + kept = std::make_shared(); + return kept; + } + /// The memory of a watch if this connection has one: for tests and diagnostics. + [[nodiscard]] std::shared_ptr find(std::uint64_t watch) const { + std::scoped_lock lock{mutex}; + const auto found = memories.find(watch); + return found == memories.end() ? nullptr : found->second; + } + [[nodiscard]] bool hasSnapshot() const { + std::scoped_lock lock{mutex}; + return snapshot.has_value(); + } + +private: + friend class WatchRegistry; + mutable std::mutex mutex; + bool closed = false; + std::map> memories; + std::uint64_t snapshots = 0; + std::optional snapshot; +}; + +/** + * @brief The watches of an application (ADR-027). Each registration gets an identifier that is never reused while the + * registry lives, and the registry's revision changes at each registration and each removal. Discovering the watches + * (page) calls no source; the other operations read or write the watched object, each whole inside the access window of + * its source. Thread-safe. */ class WatchRegistry { public: - struct Entry { - std::string name; // as the application gave it: what makes a watch unique - std::string label; // the name as the inspectors show it: control characters visible, bounded (boundedText) - std::string kind; - std::string location; - bool writable = false; - std::shared_ptr source; // what the source captures lives as long as its registration - }; + using Core = detail::WatchCore; + + /// Where the registry tells the application what it should know (ADR-011): standard error while it is empty. Set it + /// before the watches are registered. + std::function diagnostic; + /// How long the destruction of a handle waits for an operation before it says so (and goes on waiting). + std::chrono::milliseconds destructionWarning{5000}; /// Registers a watch; throws std::invalid_argument for an empty name, a name longer than maxTextBytes, a kind longer /// than maxKindBytes, or the name of a watch that is still registered. The location is made visible and bounded as a /// text of the application is, so that every descriptor fits a page of the smallest budget. - std::uint64_t add(std::string name, std::string_view kind, std::string location, bool writable, std::shared_ptr source) { - checkName(name); - if (kind.empty() || kind.size() > maxKindBytes) + std::uint64_t add(std::shared_ptr core) { + checkName(core->name); + if (core->kind.empty() || core->kind.size() > maxKindBytes) throw std::invalid_argument("A watch's kind is 1 to 16 bytes"); - auto label = boundedText(name); - auto shown = boundedText(location); - auto keeping = source; // declared before the lock: a source released by a failed insertion is destroyed after it + core->access.label = boundedText(core->name); + core->location = boundedText(core->location); + core->access.diagnose = diagnostic ? diagnostic : std::function{&toStandardError}; + auto keeping = core; // declared before the lock: a source released by a failed insertion is destroyed after it std::scoped_lock lock{mutex}; for (const auto& [id, entry] : entries) - if (entry.name == name) - throw std::invalid_argument("A watch named '" + name + "' is already registered"); + if (entry->name == core->name) + throw std::invalid_argument("A watch named '" + core->name + "' is already registered"); const auto id = nextId++; - entries.emplace(id, Entry{std::move(name), std::move(label), std::string(kind), std::move(shown), writable, std::move(source)}); + core->id = id; + entries.emplace(id, std::move(core)); ++currentRevision; return id; } - /// Removes a watch; a removed or unknown identifier is ignored. The source is released outside the registry's lock. + /// Registers a watch that has no access to its object: it is listed, and its operations answer `unavailable`. + std::uint64_t add(std::string name, std::string_view kind, std::string location, bool writable, std::shared_ptr source) { + auto core = std::make_shared(); + core->name = std::move(name); + core->kind = std::string(kind); + core->location = std::move(location); + core->access.writable = writable; + core->owned = true; + core->keep = std::move(source); + return add(std::move(core)); + } + + /** + * Removes a watch; a removed or unknown identifier is ignored. From then on no operation starts, and the calls that + * name it are refused (`webfront.inspector.unknown`). A watch whose source refers to objects of the application waits + * for an operation that another thread started: call it outside every lock the source takes. Removing such a watch + * from its own operation cannot be made safe: it is reported, then the process is terminated (ADR-027, section 5). + */ void remove(std::uint64_t id) noexcept { - std::shared_ptr released; + std::shared_ptr core; { std::scoped_lock lock{mutex}; const auto found = entries.find(id); if (found == entries.end()) return; - released = std::move(found->second.source); + core = std::move(found->second); entries.erase(found); ++currentRevision; } + retire(*core); + std::vector> open; + { + std::scoped_lock lock{sessionsMutex}; + for (const auto& [connection, session] : sessions) + open.push_back(session); + } + std::vector> released; // freed outside the sessions' locks + for (const auto& session : open) { + std::scoped_lock lock{session->mutex}; + if (const auto found = session->memories.find(id); found != session->memories.end()) { + released.push_back(std::move(found->second)); + session->memories.erase(found); + } + if (session->snapshot && session->snapshot->watch == id) + session->snapshot.reset(); + } + // The source is released here, outside the registry's lock, unless an operation still holds it. } [[nodiscard]] std::uint64_t revision() const { @@ -388,7 +376,8 @@ class WatchRegistry { std::uint64_t last = 0; bool more = false; for (auto entry = entries.upper_bound(from); entry != entries.end(); ++entry) { - const auto bytes = encodedSize(entry->second); + const auto& core = *entry->second; + const auto bytes = encodedSize(core); if (served.size() == wanted || used + bytes > room) { if (served.empty() && wanted != 0) throw std::length_error("The inspector's page budget cannot hold one watch descriptor"); @@ -397,7 +386,7 @@ class WatchRegistry { } used += bytes; last = entry->first; - served.emplace_back(static_cast(entry->first), entry->second.label, entry->second.kind, entry->second.location, entry->second.writable); + served.emplace_back(static_cast(entry->first), core.access.label, core.kind, core.location, core.access.writable); } const bool changed = known != currentRevision; return {std::move(served), more && wanted != 0 ? static_cast(last) : 0.0, static_cast(currentRevision), changed}; @@ -413,28 +402,392 @@ class WatchRegistry { } private: + [[nodiscard]] std::shared_ptr find(double watch) const { + const auto id = wholeNumber(watch, "watch"); + std::scoped_lock lock{mutex}; + const auto found = entries.find(id); + if (found == entries.end()) + throw gone(false); + return found->second; + } + + /// The terminal answer of a watch that is gone (ADR-027, "Réponse terminale"). + [[nodiscard]] static BridgeError gone(bool written) { + return detail::refusal(code::unknown, written ? "The watch was removed after the write" : "No such watch: it was removed, or never existed"); + } + + /** + * Runs an operation of a watch. None starts once the watch is removed, and the answer of one that was running when + * it was removed is replaced by the terminal refusal: its revision would be that of a memory that no longer exists. + */ + template + static auto perform(Core& core, Operation&& operation, const bool* written = nullptr) { + { + std::scoped_lock lock{core.lifecycle}; + if (core.removed) + throw gone(false); + core.running.push_back(std::this_thread::get_id()); + } + struct Done { + Core& core; + ~Done() { + std::scoped_lock lock{core.lifecycle}; + core.running.erase(std::ranges::find(core.running, std::this_thread::get_id())); + core.idle.notify_all(); + } + }; + const auto removed = [&] { + std::scoped_lock lock{core.lifecycle}; + return core.removed; + }; + Done done{core}; + try { + auto result = operation(); + if (removed()) + throw gone(written != nullptr && *written); + return result; + } catch (...) { + if (removed()) + throw gone(written != nullptr && *written); + throw; + } + } + +public: + // --- Operations (ADR-027, sections 3 and 6) ---------------------------------------------------------------- + + /// What the inspectors keep for a connection, created at its first call. `connection` is never reused while the + /// registry lives. + [[nodiscard]] std::shared_ptr session(std::uint64_t connection) { + std::scoped_lock lock{sessionsMutex}; + auto& kept = sessions[connection]; + if (!kept) + kept = std::make_shared(); + return kept; + } + + /// Frees what the inspectors keep for a closed connection: its memories, its passes and its snapshot. + void forget(std::uint64_t connection) noexcept { + std::shared_ptr closed; + { + std::scoped_lock lock{sessionsMutex}; + const auto found = sessions.find(connection); + if (found == sessions.end()) + return; + closed = std::move(found->second); + sessions.erase(found); + } + std::map> released; + std::optional snapshot; + std::scoped_lock lock{closed->mutex}; + closed->closed = true; + released.swap(closed->memories); + snapshot.swap(closed->snapshot); + } + + [[nodiscard]] std::size_t sessionCount() const { + std::scoped_lock lock{sessionsMutex}; + return sessions.size(); + } + + /// How the operations of a watch reach its executor; empty when they run on the thread that asks. Throws `unknown`. + [[nodiscard]] std::function(std::function)> hopOf(double watch) const { + return find(watch)->hop; + } + + Page children(const std::shared_ptr& from, + double watch, + std::string_view path, + double revision, + double start, + double count, + const Limits& limits) { + const auto core = find(watch); + return perform(*core, [&] { + return from->memory(core->id)->children(core->access, path, revision, start, count, limits); + }); + } + + Page changes(const std::shared_ptr& from, double watch, double revision, double cursor, double count, const Limits& limits) { + const auto core = find(watch); + return perform(*core, [&] { + return from->memory(core->id)->changes(core->access, revision, cursor, count, limits); + }); + } + + Page fold(const std::shared_ptr& from, double watch, std::string_view path, double revision) { + const auto core = find(watch); + return perform(*core, [&] { + return from->memory(core->id)->fold(path, revision); + }); + } + + double reset(const std::shared_ptr& from, double watch) { + const auto core = find(watch); + return perform(*core, [&] { + return from->memory(core->id)->reset(); + }); + } + + WriteAnswer write(const std::shared_ptr& from, + double watch, + double revision, + std::string_view path, + std::string_view expected, + std::string_view text, + const Limits& limits) { + const auto core = find(watch); + bool applied = false; + return perform( + *core, + [&] { + return from->memory(core->id)->write(core->access, revision, path, expected, text, limits, applied); + }, + &applied); + } + + /** + * webfront.inspector.value: a fragment of the whole value of a node. The snapshot 0 formats the value, inside the + * access window, and keeps it as the connection's snapshot under a new identifier; the following calls give that + * identifier and the offset they received. Anything else is refused (`stale`): a second reading that replaced the + * snapshot makes the rest of the first one fail, and never serves it a fragment of another value. + */ + ValueAnswer + value(const std::shared_ptr& from, double watch, std::string_view path, double snapshotAsked, double offsetAsked, const Limits& limits) { + const auto core = find(watch); + return perform(*core, [&]() -> ValueAnswer { + const auto snapshot = wholeNumber(snapshotAsked, "snapshot"), offset = wholeNumber(offsetAsked, "offset"); + const auto room = limits.responseBudget - responseHeaderBytes; + if (snapshot == 0) { + if (offset != 0) + throw detail::refusal(code::stale, "A new reading starts at the offset 0"); + auto [text, capped] = from->memory(core->id)->value(core->access, path, limits.maxSnapshotBytes); + std::scoped_lock lock{from->mutex}; + if (from->closed) + throw webfront::detail::makeBridgeError(bridge_code::disconnected, "The connection is closed"); + from->snapshot = detail::Snapshot{.id = ++from->snapshots, + .watch = core->id, + .path = std::string(path), + .text = std::move(text), + .next = 0, + .capped = capped}; + return fragment(*from, room); + } + std::scoped_lock lock{from->mutex}; + const auto& kept = from->snapshot; + if (!kept || kept->id != snapshot || kept->watch != core->id || kept->path != path || kept->next != offset || offset == 0) + throw detail::refusal(code::stale, "The snapshot is no longer the connection's: read the value again"); + return fragment(*from, room); + }); + } + + /// The bounds of the operations, as webfront.inspector.limits answers them. + [[nodiscard]] static LimitsAnswer limits(const Limits& limits) noexcept { + return {static_cast((std::min)(limits.maxWriteTextBytes, static_cast(maxExactNumber))), + static_cast(limits.responseBudget), + static_cast(limits.maxNodes), + static_cast(limits.maxSnapshotBytes), + static_cast(maxPageCount), + static_cast(defaultPageCount)}; + } + +private: + static std::uint64_t wholeNumber(double value, std::string_view what) { + return detail::wholeNumber(value, what); + } + /// An upper bound of the encoded size of a descriptor: a tuple header, a number, three strings with the longest string /// header and a boolean. - static std::size_t encodedSize(const Entry& entry) noexcept { - return 2 + 9 + (3 + entry.label.size()) + (3 + entry.kind.size()) + (3 + entry.location.size()) + 1; + static std::size_t encodedSize(const Core& core) noexcept { + return 2 + 9 + (3 + core.access.label.size()) + (3 + core.kind.size()) + (3 + core.location.size()) + 1; } - static std::uint64_t wholeNumber(double value, std::string_view what) { - if (!std::isfinite(value) || value < 0 || value > maxExactNumber || std::trunc(value) != value) - throw std::invalid_argument("The watches' " + std::string(what) + " must be a whole number from 0 to 2^53"); - return static_cast(value); + /// Marks the watch removed and, for a source that refers to objects of the application, waits for its operations. + void retire(Core& core) noexcept { + std::unique_lock lock{core.lifecycle}; + core.removed = true; + if (core.owned) + return; + if (std::ranges::find(core.running, std::this_thread::get_id()) != core.running.end()) { + const auto message = "The watch '" + core.access.label + "' declared at " + core.location + + " was destroyed from its own operation (source, visitor or mutator): its source refers to objects that may be" + " destroyed next. Use an owning source, watch(name, std::shared_ptr, source), or destroy the handle" + " from another thread."; + report(message); + if (diagnostic) + toStandardError(message); // also where a process that ends is read, whatever the application's journal keeps + std::fflush(stderr); + std::terminate(); + } + bool warned = false; + while (!core.running.empty()) { + if (warned) + core.idle.wait(lock); + else if (core.idle.wait_for(lock, destructionWarning) == std::cv_status::timeout && !core.running.empty()) { + warned = true; + report("The destruction of the watch '" + core.access.label + "' declared at " + core.location + " has been waiting for an operation for " + + std::to_string(destructionWarning.count()) + " ms: destroy the handle outside every lock its source takes, and outside its executor"); + } + } + } + + static void toStandardError(std::string_view message) { + std::fprintf(stderr, "webfront: %.*s\n", static_cast(message.size()), message.data()); + } + + void report(std::string_view message) const noexcept { + try { + if (diagnostic) + diagnostic(message); + else + toStandardError(message); + } catch (...) { // NOLINT(bugprone-empty-catch): a diagnostic that fails is not worth an exception in a destructor + } + } + + /// The next fragment of the session's snapshot, of at most `room` bytes and never cutting a character. The session's + /// lock is held. + [[nodiscard]] static ValueAnswer fragment(WatchSession& from, std::size_t room) { + auto& kept = *from.snapshot; + const auto rest = std::string_view{kept.text}.substr(kept.next); + auto part = utf8Prefix(rest, room); + if (part.empty() && !rest.empty()) + part = rest.substr(0, (std::min)(room, rest.size())); // bytes that are no UTF-8 text are cut where the room ends + const auto end = kept.next + part.size(); + const bool last = end == kept.text.size(); + ValueAnswer answer{std::string(part), + static_cast(kept.text.size()), + last ? 0.0 : static_cast(end), + kept.capped, + static_cast(kept.id)}; + kept.next = end; + if (last) + from.snapshot.reset(); + return answer; } - mutable std::mutex mutex; - std::map entries; - std::uint64_t nextId = 1; - std::uint64_t currentRevision = 1; // never 0: an inspector that starts with 0 sees a change + mutable std::mutex mutex; + std::map> entries; + std::uint64_t nextId = 1; + std::uint64_t currentRevision = 1; // never 0: an inspector that starts with 0 sees a change + mutable std::mutex sessionsMutex; + std::map> sessions; }; +/** + * Runs an operation of a watch where its object lives: on the watch's executor when it has one, else on the calling thread. + * The operations of a watch are run in the order they are asked. A watch whose executor has no running loop answers + * `webfront.inspector.unavailable`. The operation is type-erased: the coroutine's frame then names no type of the caller. + */ +template +ResultTask onWatch(std::shared_ptr registry, double watch, std::function operation) { + const auto hop = registry->hopOf(watch); + if (!hop) + co_return operation(); + std::optional result; + std::exception_ptr failure; + std::string unavailable; + try { + co_await hop([&] { + try { + result.emplace(operation()); + } catch (...) { + failure = std::current_exception(); + } + }); + } catch (const std::exception& error) { + unavailable = error.what(); + } + if (failure) + std::rethrow_exception(failure); + if (!result) + throw detail::refusal(code::unavailable, "The watch's executor is not available: " + boundedText(unavailable, maxTextBytes - 48)); + co_return std::move(*result); +} + +/// What BasicWF::watch passes for a watch without an executor, without a mutator, or that owns no state. +struct NoExecutor { }; +struct NoMutator { }; +struct NoState { }; + +namespace detail { +/// Whether an accessor returns a reference to its object, not a copy. A visitor is not an accessor. +template +[[nodiscard]] constexpr bool returnsReference() noexcept { + if constexpr (visitor) + return false; + else if constexpr (stateful) + return std::is_lvalue_reference_v>; + else + return std::is_lvalue_reference_v>; +} +} // namespace detail + +/// Builds a watch from its source, and optionally the state it owns, its executor and its mutator (BasicWF::watch). +template +[[nodiscard]] std::shared_ptr +makeWatch(std::string name, std::string location, Source&& source, std::shared_ptr owner, Executor executor, Mutator mutator) { + using Stored = std::decay_t; // a function given by name is kept as a pointer + using Object = typename Shape::Object; + constexpr bool stateful = requires { requires Shape::stateful; }; + constexpr bool hasExecutor = !std::same_as; + // An accessor writes only through a non-constant reference, on the executor that owns the object. + constexpr bool writable = !std::is_const_v + && (Shape::visitor || (detail::returnsReference() && hasExecutor)); + using Root = std::conditional_t; + + auto core = std::make_shared(); + core->name = std::move(name); + core->kind = std::string(kindOf()); + core->location = std::move(location); + core->owned = !std::same_as; + core->access.writable = writable; + auto kept = std::make_shared(std::forward(source)); + core->access.open = [kept, owner](detail::FunctionRef use) { + if constexpr (Shape::visitor) { + bool visited = false; + Visit visit{[&](Object& object) { + visited = true; + use(detail::refOf(object)); + }}; + if constexpr (stateful) + (*kept)(*owner, std::move(visit)); + else + (*kept)(std::move(visit)); + return visited; + } else { + if constexpr (stateful) { + decltype(auto) object = (*kept)(*owner); + use(detail::refOf(object)); + } else { + decltype(auto) object = (*kept)(); + use(detail::refOf(object)); + } + return true; + } + }; + if constexpr (hasExecutor) + core->hop = [bound = std::move(executor)](std::function work) { + return detail::hopOn(bound, std::move(work)); + }; + if constexpr (!std::same_as) { + static_assert(writable, "A watch's mutator needs a source that writes: a Visit of a non-constant T, or a non-constant reference on an executor"); + auto mutate = std::make_shared(std::move(mutator)); + core->access.mutate = [mutate](void* root, std::string_view path, std::string_view text) { + (*mutate)(*static_cast(root), path, text); + }; + } + return core; +} + /** * @brief The handle of a watch, as UISubscription is the handle of a subscription: the watch exists while it lives, and * the handle stays safe after the application is destroyed. An empty handle registered nothing: outside the developer * environment, and in a distribution build, `app.watch` returns one (ADR-027, section 1). Move-only. + * + * Unlike UISubscription, destroying the handle of a watch whose source refers to objects of the application waits for an + * operation in progress on another thread: destroy it outside every lock the source takes, and outside the watch's + * executor. A watch declared with the state it owns (`watch(name, std::shared_ptr, source)`) never waits. */ class Watch { public: diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 7381974a..12419fe5 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -1309,12 +1309,27 @@ class BasicWF { /** * @brief Declares a watch: an object or a container of the application that the inspectors of the developer environment - * show (ADR-027, section 5). The watch exists while the returned handle lives. + * show as a tree and refresh (ADR-027, section 5; docs/WATCHES.md). The watch exists while the returned handle lives. * - * `source` reaches the object. A visitor, `[&](webfront::inspect::Visit visit) { std::scoped_lock lock{m}; visit(object); }`, - * is called by WebFront and calls the visit once with the object under its own lock: it is the form of an object shared - * between threads, and `Visit` makes the watch writable. An accessor, `[&] -> const T& { return object; }`, returns a - * reference, read on the server thread only (correct only for an object that thread alone touches), or a copy. + * `source` reaches the object, and every operation of the inspectors (a page, a pass of differences, a value, a write) + * runs whole inside the access it defines: + * - a visitor, `[&](webfront::inspect::Visit visit) { std::scoped_lock lock{m}; visit(object); }`, is called by + * WebFront and calls the visit once with the object under its own lock: it is the form of an object shared between + * threads, and `Visit` makes the watch writable; + * - an accessor, `[&] -> const T& { return object; }`, returns a reference, read on the thread that runs the operation + * (correct only for an object that thread alone touches), or a copy. A lock taken inside an accessor protects nothing. + * + * `executor` (`app.uiExecutor()`, a host's loop: anything whose `schedule()` gives a sender) is the thread that owns the + * object: the source and the whole operation run there, in the order the calls were received. Without one they run on + * the server thread, the one of the `cppFunction` callbacks. An accessor that returns a non-constant reference is + * writable with an executor only. + * + * `mutator`, `[](T& object, std::string_view path, std::string_view text) { ... }`, applies a write its own way and + * throws to refuse it; without one a value is assigned. Values are writable only when the source is. + * + * Destroying the handle waits for an operation that another thread started: destroy it outside every lock the source + * takes and outside the executor. Destroying it from the operation itself terminates the process, after a diagnostic. + * The overloads that take a `std::shared_ptr` never wait and allow both: see below. * * Outside the developer environment (`bootstrap("developer")`), and in a distribution build, nothing is registered and * the handle is empty: declare the watches after bootstrap(). Inside, a watch costs an entry in a table until an @@ -1324,22 +1339,141 @@ class BasicWF { */ template [[nodiscard]] inspect::Watch watch(std::string name, Source&& source, std::source_location location = std::source_location::current()) { - using Stored = std::decay_t; // a function given by name is kept as a pointer - using Shape = inspect::SourceShape; + using Shape = inspect::SourceShape>; + return declareWatch(std::move(name), + location, + std::forward(source), + std::shared_ptr{}, + inspect::NoExecutor{}, + inspect::NoMutator{}); + } + template + [[nodiscard]] inspect::Watch watch(std::string name, Source&& source, Executor executor, std::source_location location = std::source_location::current()) { + using Shape = inspect::SourceShape>; + return declareWatch(std::move(name), + location, + std::forward(source), + std::shared_ptr{}, + std::move(executor), + inspect::NoMutator{}); + } + template >::Object> Mutator> + [[nodiscard]] inspect::Watch watch(std::string name, Source&& source, Mutator mutator, std::source_location location = std::source_location::current()) { + using Shape = inspect::SourceShape>; + return declareWatch(std::move(name), + location, + std::forward(source), + std::shared_ptr{}, + inspect::NoExecutor{}, + std::move(mutator)); + } + template >::Object> Mutator> + [[nodiscard]] inspect::Watch + watch(std::string name, Source&& source, Executor executor, Mutator mutator, std::source_location location = std::source_location::current()) { + using Shape = inspect::SourceShape>; + return declareWatch(std::move(name), + location, + std::forward(source), + std::shared_ptr{}, + std::move(executor), + std::move(mutator)); + } + + /** + * @brief Declares a watch whose source owns its state: each operation keeps `owner` alive while it runs, and the source + * captures nothing else by reference. It receives the state, `[](State& state, inspect::Visit visit) { + * std::scoped_lock lock{state.mutex}; visit(state.value); }` (or `[](State& state) -> T& { ... }`). + * + * Destroying the handle then never waits: it may be destroyed under the lock the source takes, and from the operation + * itself (source, visitor or mutator). An operation in progress ends on a state that still lives, and its answer is + * replaced by the refusal `webfront.inspector.unknown`. It is the form to choose when the order of destruction cannot + * be guaranteed. The other parameters are those of the overloads above. + */ + template Source> + [[nodiscard]] inspect::Watch + watch(std::string name, std::shared_ptr owner, Source&& source, std::source_location location = std::source_location::current()) { + using Shape = inspect::OwnedSourceShape, State>; + return declareWatch(std::move(name), + location, + std::forward(source), + requireOwner(std::move(owner)), + inspect::NoExecutor{}, + inspect::NoMutator{}); + } + template Source, inspect::WatchExecutor Executor> + [[nodiscard]] inspect::Watch + watch(std::string name, std::shared_ptr owner, Source&& source, Executor executor, std::source_location location = std::source_location::current()) { + using Shape = inspect::OwnedSourceShape, State>; + return declareWatch(std::move(name), + location, + std::forward(source), + requireOwner(std::move(owner)), + std::move(executor), + inspect::NoMutator{}); + } + template Source, + inspect::WatchMutator, State>::Object> Mutator> + [[nodiscard]] inspect::Watch + watch(std::string name, std::shared_ptr owner, Source&& source, Mutator mutator, std::source_location location = std::source_location::current()) { + using Shape = inspect::OwnedSourceShape, State>; + return declareWatch(std::move(name), + location, + std::forward(source), + requireOwner(std::move(owner)), + inspect::NoExecutor{}, + std::move(mutator)); + } + template Source, + inspect::WatchExecutor Executor, + inspect::WatchMutator, State>::Object> Mutator> + [[nodiscard]] inspect::Watch watch(std::string name, + std::shared_ptr owner, + Source&& source, + Executor executor, + Mutator mutator, + std::source_location location = std::source_location::current()) { + using Shape = inspect::OwnedSourceShape, State>; + return declareWatch(std::move(name), + location, + std::forward(source), + requireOwner(std::move(owner)), + std::move(executor), + std::move(mutator)); + } + +private: + template + static std::shared_ptr requireOwner(std::shared_ptr owner) { + if (!owner) + throw std::invalid_argument("webfront::BasicWF::watch(): an owning watch needs the state it owns"); + return owner; + } + + template + [[nodiscard]] inspect::Watch + declareWatch(std::string name, const std::source_location& location, Source&& source, std::shared_ptr owner, Executor executor, Mutator mutator) { inspect::WatchRegistry::checkName(name); - const auto registry = inspectorRegistry(); - if (!registry) + if constexpr (inspect::introspection) { + const auto registry = inspectorRegistry(); + if (!registry) + return {}; + const auto id = registry->add(inspect::makeWatch(std::move(name), + inspect::locationText(location), + std::forward(source), + std::move(owner), + std::move(executor), + std::move(mutator))); + return inspect::Watch{registry, id}; + } else { + static_cast(location), static_cast(source), static_cast(owner), static_cast(executor), static_cast(mutator); return {}; - auto owned = std::make_shared(std::forward(source)); - const auto id = registry->add(std::move(name), - inspect::kindOf(), - inspect::locationText(location), - Shape::writable, - std::static_pointer_cast(std::move(owned))); - return inspect::Watch{registry, id}; + } } -private: /// The names of the inspectors belong to WebFront: an application can neither hide one nor pose as one (ADR-027, section 1). static void refuseReservedName(std::string_view functionName) { if (inspect::isReservedName(functionName)) @@ -1766,13 +1900,33 @@ class BasicWF { /// table without the bootstrap or in a distribution build, where the handle must stay empty (section 1). std::shared_ptr enableInspectors() { std::scoped_lock lock{watchRegistryMutex}; - if (!watchRegistry) - watchRegistry = std::make_shared(); + if (!watchRegistry) { + watchRegistry = std::make_shared(); + watchRegistry->diagnostic = [](std::string_view message) { + log::warn("{}", message); + }; + } if (jsCalls) jsCalls->enable(); return watchRegistry; } + /// What the inspectors keep for the connection of `caller` (its memory of each watch), freed when it closes. Throws + /// when the connection is gone. + [[nodiscard]] std::shared_ptr inspectorSession(const UI& caller) const { + const auto registry = inspectorRegistry(); + const auto generation = deferredCallsOf(caller).second; + if (!registry || generation == 0) + throw detail::makeBridgeError(bridge_code::disconnected, "The connection is closed"); + return registry->session(generation); + } + + /// Frees what the inspectors keep for a connection that closed. + void forgetInspectorSession(WebLinkGeneration generation) const noexcept { + if (const auto registry = inspectorRegistry()) + registry->forget(generation); + } + /// For the inspectors' functions (DeveloperAppWithNetwork): what cppFunction registered, and the calls made to JavaScript. [[nodiscard]] const std::shared_ptr& inspectedFunctions() const noexcept { return functionRegistry; @@ -1924,6 +2078,7 @@ class BasicWF { } stoppedCalls->close(); readBinding->close(generation); + forgetInspectorSession(generation); if (auto found = domDocuments.find(id); found != domDocuments.end()) { found->second->close(); domDocuments.erase(found); @@ -2357,6 +2512,8 @@ class BasicWF { // Outside linksMutex: dropping the grants destroys their contexts, whose destructors may use the application. if (closedGeneration) readBinding->close(*closedGeneration); // its read URLs stop working at once + if (closedGeneration) + forgetInspectorSession(*closedGeneration); if (auto found = domDocuments.find(event.webLinkId); found != domDocuments.end()) { found->second->close(); domDocuments.erase(found); diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 5cf5b6a6..634d4113 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 IntrospectionTests.cpp BroadcastTests.cpp SpaceTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) +list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp WatchTests.cpp WatchTreeTests.cpp WatchPassTests.cpp WatchWriteTests.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) @@ -525,6 +525,34 @@ target_link_libraries(inspector_distribution PRIVATE WebFront WebFront::Bdd WebF target_compile_definitions(inspector_distribution PRIVATE WEBFRONT_DISTRIBUTION=1) add_test(NAME InspectorsAbsentFromDistribution COMMAND inspector_distribution) +# Destroying the handle of a watch from its own visitor, when its source refers to the application's objects, cannot be made +# safe: the process writes a diagnostic that names the watch and where it was declared, then terminates (ADR-027, section 5). +add_executable(watch_terminates WatchTerminates.cpp) +target_link_libraries(watch_terminates PRIVATE WebFront WebFront_test_hardening WebFront_warnings WebFront_options) +add_test(NAME WatchDestroyedFromItsVisitor COMMAND watch_terminates) +set_tests_properties(WatchDestroyedFromItsVisitor PROPERTIES + PASS_REGULAR_EXPRESSION "The watch 'values' declared at app.cpp:12 was destroyed from its own operation.*terminated" + FAIL_REGULAR_EXPRESSION "the process survived" TIMEOUT 60 LABELS fast) + +# A buffers policy too small for the inspectors does not compile with what the developer environment instantiates +# (inspect::limitsOf), also when only its maxMessageSize is too small (ADR-027, section 3). +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang" AND NOT MSVC) + foreach(_case IN ITEMS "SMALL_BUFFER|an answer must hold a page of one node" "SMALL_MESSAGE|an answer must hold a page of one node" + "SMALL_WRITE|a write must carry a text of 1 KiB") + string(REPLACE "|" ";" _case "${_case}") + list(GET _case 0 _name) + list(GET _case 1 _message) + add_test(NAME WatchPolicyRejects.${_name} + COMMAND ${CMAKE_CXX_COMPILER} -std=c++23 -fsyntax-only -I${PROJECT_SOURCE_DIR}/include + -DREJECT_${_name} ${CMAKE_CURRENT_SOURCE_DIR}/WatchPolicyRejects.cpp) + set_tests_properties(WatchPolicyRejects.${_name} PROPERTIES PASS_REGULAR_EXPRESSION "${_message}" TIMEOUT 60 LABELS fast) + endforeach() + # Without a small policy the same file compiles: the cases above fail only on their assertion. + add_test(NAME WatchPolicyRejects.NONE COMMAND ${CMAKE_CXX_COMPILER} -std=c++23 -fsyntax-only -I${PROJECT_SOURCE_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/WatchPolicyRejects.cpp) + set_tests_properties(WatchPolicyRejects.NONE PROPERTIES TIMEOUT 60 LABELS fast) +endif() + # A project outside WebFront finds the installed WebFrontBdd package, writes scenarios and has CTest discover them (#647). # Only the top-level project installs the package, so only it can run this check. if(WEBFRONT_IS_TOP_LEVEL) diff --git a/test/unit/InspectorDistribution.cpp b/test/unit/InspectorDistribution.cpp index 2b7fba10..37a63638 100644 --- a/test/unit/InspectorDistribution.cpp +++ b/test/unit/InspectorDistribution.cpp @@ -42,7 +42,14 @@ const Scenario inspectorsAbsent{"A distribution build registers no inspector fun "webfront.inspector.readPreferences", "webfront.inspector.savePreferences", "webfront.inspector.openWindow", - "webfront.inspector.closeWindow"}) + "webfront.inspector.closeWindow", + "webfront.inspector.limits", + "webfront.inspector.children", + "webfront.inspector.changes", + "webfront.inspector.value", + "webfront.inspector.fold", + "webfront.inspector.reset", + "webfront.inspector.write"}) require(!app.hasCppFunction(name)); }); then("nothing is recorded of the functions or of the calls to JavaScript", [&] { diff --git a/test/unit/ViewAssociationTests.cpp b/test/unit/ViewAssociationTests.cpp index 1cba5a81..2ea9e58d 100644 --- a/test/unit/ViewAssociationTests.cpp +++ b/test/unit/ViewAssociationTests.cpp @@ -601,6 +601,82 @@ const Scenario inspectorWindowAccess{ } }; +const Scenario inspectorTreeAccess{ + "The trees of the watches are read and written through the bridge by an admitted page only (ADR-027, sections 2, 3 and 6)", + {"view-association", "inspector"}, + [] { + std::vector grid{1, 2, 3}; + const auto visitor = [&grid](inspect::Visit> visit) { + visit(grid); + }; + given("the proven view and a writable watch", [&] { + freshNetwork(); + AdmittedBrowser browser{false, true}; + auto watch = browser.app.watch("grid", visitor); + const auto id = static_cast(watch.id()); + then("the functions of the trees are registered", [&] { + for (const auto* name : {"webfront.inspector.limits", + "webfront.inspector.children", + "webfront.inspector.changes", + "webfront.inspector.value", + "webfront.inspector.fold", + "webfront.inspector.reset", + "webfront.inspector.write"}) + require(browser.app.hasCppFunction(name)); + }); + then("the root and its children are read, a value is written, and the next pass is empty", [&] { + callWith("webfront.inspector.reset", 11, id); // the memory of a first call has the revision 1: reset gives 2 + callWith("webfront.inspector.children", 12, id, std::string{}, 2.0, 0.0, 200.0); + require(ViewSocket::wrote("sequence")); + require(ViewSocket::wrote("/#2")); + require(ViewSocket::wrote("[2]")); + callWith("webfront.inspector.write", 13, id, 3.0, std::string{"/#1"}, std::string{"2"}, std::string{"20"}); + requireEqual(grid, std::vector({1, 20, 3})); + callWith("webfront.inspector.value", 14, id, std::string{"/#1"}, 0.0, 0.0); + callWith("webfront.inspector.changes", 15, id, 4.0, 0.0, 200.0); + callWith("webfront.inspector.fold", 16, id, std::string{}, 5.0); + require(!ViewSocket::wrote(std::string_view{"webfront.inspector."})); // no refusal among the answers + }); + then("a watch on an executor that has no running loop answers unavailable, and its source is not called", [&] { + bool read = false; + auto waiting = browser.app.watch( + "waiting", + [&]() -> std::vector& { + read = true; + return grid; + }, + browser.app.uiExecutor()); + callWith("webfront.inspector.reset", 11, static_cast(waiting.id())); + require(ViewSocket::wrote(inspect::code::unavailable)); + require(!read); + }); + then("a call for a watch that is gone is refused as unknown", [&] { + watch.reset(); + callWith("webfront.inspector.reset", 11, id); + require(ViewSocket::wrote(inspect::code::unknown)); + }); + }); + given("a page that is not admitted", [&] { + freshNetwork(); + AdmittedBrowser browser{false, false}; + auto watch = browser.app.watch("grid", visitor); + const auto id = static_cast(watch.id()); + then("every function of the trees is refused as denied, and nothing is read or written", [&] { + callWithoutArgument("webfront.inspector.limits", 10); + callWith("webfront.inspector.reset", 11, id); + callWith("webfront.inspector.children", 12, id, std::string{}, 2.0, 0.0, 200.0); + callWith("webfront.inspector.changes", 13, id, 2.0, 0.0, 200.0); + callWith("webfront.inspector.value", 14, id, std::string{}, 0.0, 0.0); + callWith("webfront.inspector.fold", 15, id, std::string{}, 2.0); + callWith("webfront.inspector.write", 16, id, 2.0, std::string{"/#1"}, std::string{"2"}, std::string{"20"}); + require(ViewSocket::wrote(inspect::code::denied)); + require(!ViewSocket::wrote("sequence")); + requireEqual(grid, std::vector({1, 2, 3})); + }); + }); + } +}; + const Scenario inspectorWatchesAccess{ "webfront.inspector.watches lists the application's watches to an admitted page only (ADR-027, sections 2 and 3)", {"view-association", "inspector"}, diff --git a/test/unit/WatchHarness.hpp b/test/unit/WatchHarness.hpp new file mode 100644 index 00000000..9f6a96b5 --- /dev/null +++ b/test/unit/WatchHarness.hpp @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-27 +// +// WebFront — tests/unit +// Role: A registry of watches with one connection, and readers of the pages, for the tests of the inspectors' trees (ADR-027). +// Thread: worker-safe | Alloc: unrestricted +// LLM: test helper of WatchTreeTests.cpp, WatchPassTests.cpp and WatchWriteTests.cpp; no network, the operations are called directly + +#pragma once + +#include "FormsSettings.hpp" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +/// The fixture of the forms is described for the inspectors too. +template <> +struct webfront::inspect::Described { + static webfront::forms::Description description() { + return forms_fixture::settingsDescription(); + } +}; + +namespace watch_fixture { + +using webfront::inspect::Limits; +using webfront::inspect::Node; +using webfront::inspect::Page; +using webfront::inspect::Visit; +using webfront::inspect::WatchRegistry; +namespace flag = webfront::inspect::flag; +namespace code = webfront::inspect::code; + +inline const std::string& pathOf(const Node& node) { + return std::get<0>(node); +} +inline const std::string& kindOf(const Node& node) { + return std::get<1>(node); +} +inline const std::string& labelOf(const Node& node) { + return std::get<2>(node); +} +inline const std::string& valueOf(const Node& node) { + return std::get<3>(node); +} +inline std::size_t countOf(const Node& node) { + return static_cast(std::get<4>(node)); +} +inline unsigned flagsOf(const Node& node) { + return static_cast(std::get<5>(node)); +} +inline const std::vector& nodesOf(const Page& page) { + return std::get<0>(page); +} +inline double nextOf(const Page& page) { + return std::get<1>(page); +} +inline double revisionOf(const Page& page) { + return std::get<2>(page); +} +inline bool resyncOf(const Page& page) { + return std::get<3>(page); +} +inline std::vector pathsOf(const Page& page) { + std::vector paths; + for (const auto& node : nodesOf(page)) + paths.push_back(pathOf(node)); + return paths; +} +inline std::vector valuesOf(const Page& page) { + std::vector values; + for (const auto& node : nodesOf(page)) + values.push_back(valueOf(node)); + return values; +} +/// The node of `path` in the page; fails the scenario when it is not there. +inline const Node& nodeAt(const Page& page, std::string_view path) { + for (const auto& node : nodesOf(page)) + if (pathOf(node) == path) + return node; + webfront::bdd::require(false); + return nodesOf(page).front(); +} +inline bool hasNode(const Page& page, std::string_view path) { + for (const auto& node : nodesOf(page)) + if (pathOf(node) == path) + return true; + return false; +} +/// The bytes a page takes in its message, header included. +inline std::size_t bytesOf(const Page& page) { + auto bytes = webfront::inspect::detail::pageOverheadBytes; + for (const auto& node : nodesOf(page)) + bytes += webfront::inspect::detail::nodeBytes(node); + return bytes; +} + +/// The code of the BridgeError that `call` throws, "" when it throws nothing, "exception" for another exception. +template +std::string codeOf(Call&& call) { + try { + static_cast(call()); + } catch (const webfront::BridgeError& error) { + return error.code(); + } catch (const std::exception&) { + return "exception"; + } + return {}; +} +template +std::string messageOf(Call&& call) { + try { + static_cast(call()); + } catch (const std::exception& error) { + return error.what(); + } + return {}; +} + +/// A visitor source of `object`, as an application writes one (here without a lock: one thread). +template +auto visiting(T& object) { + return [&object](Visit visit) { + visit(object); + }; +} + +/// A registry, the session of one connection, and the calls of the inspectors on it. +struct Bench { + std::shared_ptr registry = std::make_shared(); + std::shared_ptr session; + Limits limits{.responseBudget = 32768, .maxWriteTextBytes = 4096}; + std::mutex diagnosticsMutex; + std::vector diagnostics; + + Bench() { + registry->diagnostic = [this](std::string_view message) { + std::scoped_lock lock{diagnosticsMutex}; + diagnostics.emplace_back(message); + }; + session = registry->session(1); + } + + template + std::uint64_t watch(std::string name, Source&& source) { + using Shape = webfront::inspect::SourceShape>; + return registry->add(webfront::inspect::makeWatch(std::move(name), + "test.cpp:1", + std::forward(source), + std::shared_ptr{}, + webfront::inspect::NoExecutor{}, + webfront::inspect::NoMutator{})); + } + template + std::uint64_t watch(std::string name, Source&& source, Mutator mutator) { + using Shape = webfront::inspect::SourceShape>; + return registry->add(webfront::inspect::makeWatch(std::move(name), + "test.cpp:1", + std::forward(source), + std::shared_ptr{}, + webfront::inspect::NoExecutor{}, + std::move(mutator))); + } + template + std::uint64_t owning(std::string name, std::shared_ptr state, Source&& source) { + using Shape = webfront::inspect::OwnedSourceShape, State>; + return registry->add(webfront::inspect::makeWatch(std::move(name), + "test.cpp:1", + std::forward(source), + std::move(state), + webfront::inspect::NoExecutor{}, + webfront::inspect::NoMutator{})); + } + + std::size_t diagnosticCount() { + std::scoped_lock lock{diagnosticsMutex}; + return diagnostics.size(); + } + std::string lastDiagnostic() { + std::scoped_lock lock{diagnosticsMutex}; + return diagnostics.empty() ? std::string{} : diagnostics.back(); + } + + double reset(std::uint64_t watch) { + return registry->reset(session, static_cast(watch)); + } + Page children(std::uint64_t watch, std::string_view path, double revision, double start = 0, double count = 200) { + return registry->children(session, static_cast(watch), path, revision, start, count, limits); + } + Page changes(std::uint64_t watch, double revision, double cursor = 0, double count = 200) { + return registry->changes(session, static_cast(watch), revision, cursor, count, limits); + } + Page fold(std::uint64_t watch, std::string_view path, double revision) { + return registry->fold(session, static_cast(watch), path, revision); + } + webfront::inspect::WriteAnswer write(std::uint64_t watch, double revision, std::string_view path, std::string_view expected, std::string_view text) { + return registry->write(session, static_cast(watch), revision, path, expected, text, limits); + } + webfront::inspect::ValueAnswer value(std::uint64_t watch, std::string_view path, double snapshot = 0, double offset = 0) { + return registry->value(session, static_cast(watch), path, snapshot, offset, limits); + } + /// The memory of the watch for the bench's connection. + std::shared_ptr memory(std::uint64_t watch) { + return session->memory(watch); + } + /// Opens a watch as the panel does: an empty memory, then the root and its first children. Returns that page. + Page open(std::uint64_t watch, double count = 200) { + return children(watch, "", reset(watch), 0, count); + } +}; + +} // namespace watch_fixture diff --git a/test/unit/WatchPassTests.cpp b/test/unit/WatchPassTests.cpp new file mode 100644 index 00000000..5dba51a5 --- /dev/null +++ b/test/unit/WatchPassTests.cpp @@ -0,0 +1,476 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-27 +// +// WebFront — tests/unit +// Role: The passes of differences of the watches (ADR-027, section 3): pages of a coherent set, interruption, stale revisions, resynchronization. +// Thread: worker-safe | Alloc: unrestricted +// LLM: unit tests of Memory::changes and of what interrupts a pass; trees are in WatchTreeTests.cpp, writes in WatchWriteTests.cpp + +#include "WatchHarness.hpp" + +#include +#include +#include + +using namespace webfront::bdd; +using namespace webfront; + +namespace watch_pass { +using namespace watch_fixture; + +/// Its formatter throws while `failing` is set. +struct Fragile { + int value = 0; + bool failing = false; +}; + +/// A keyed paged source of numbers. +struct Rows { + std::vector> rows; + bool keyFails = false; + [[nodiscard]] std::size_t size() const { + return rows.size(); + } + void visit(std::size_t first, std::size_t count, auto&& each) { + for (std::size_t index = first; index < rows.size() && index - first < count; ++index) + each(rows[index].second); + } + [[nodiscard]] std::string key(std::size_t position) const { + if (keyFails) + throw std::runtime_error("no key"); + return rows.at(position).first; + } + [[nodiscard]] std::optional find(std::string_view wanted) const { + for (std::size_t index = 0; index < rows.size(); ++index) + if (rows[index].first == wanted) + return index; + return std::nullopt; + } +}; + +/// Reads the whole list of the root, 1 000 children a page; returns the last page. +Page loadAll(Bench& bench, std::uint64_t id) { + auto page = bench.open(id, 1000); + while (nextOf(page) != 0) + page = bench.children(id, "", revisionOf(page), nextOf(page), 1000); + return page; +} + +/// Reads a pass to its end from its first page; returns the paths of all its nodes. +std::vector finish(Bench& bench, std::uint64_t id, Page page, double count = 1000) { + auto paths = pathsOf(page); + while (nextOf(page) != 0) { + page = bench.changes(id, revisionOf(page), nextOf(page), count); + webfront::bdd::require(!resyncOf(page)); + for (const auto& path : pathsOf(page)) + paths.push_back(path); + } + return paths; +} +} // namespace watch_pass + +template <> +struct std::formatter { + constexpr auto parse(std::format_parse_context& context) { + return context.begin(); + } + auto format(const watch_pass::Fragile& fragile, std::format_context& context) const { + if (fragile.failing) + throw std::runtime_error("broken"); + return std::format_to(context.out(), "fragile {}", fragile.value); + } +}; + +namespace watch_pass { + +const Scenario watchChanges{"A pass of differences tells what changed since the memory was written (ADR-027, section 3, \"Différences paginées\")", + {"inspector"}, + [] { + Bench bench; + std::vector> grid{ + {1, 2, 3}, + {4, 5} + }; + const auto id = bench.watch("grid", visiting(grid)); + auto page = bench.open(id); + page = bench.children(id, "/#0", revisionOf(page)); + then("nothing changed: an empty page, under a new revision", [&] { + const auto pass = bench.changes(id, revisionOf(page)); + require(nodesOf(pass).empty() && !resyncOf(pass)); + requireEqual(nextOf(pass), 0.0); + require(revisionOf(pass) != revisionOf(page)); + }); + then("a value that changed is told with its new value, and only once", [&] { + grid[0][1] = 20; + const auto pass = bench.changes(id, revisionOf(page)); + requireEqual(pathsOf(pass), std::vector{"/#0/#1"}); + requireEqual(valueOf(nodesOf(pass).front()), std::string{"20"}); + require(nodesOf(bench.changes(id, revisionOf(pass))).empty()); + }); + then("what is not unfolded is not read: a change under a folded node tells nothing", [&] { + grid[1][0] = 40; + require(nodesOf(bench.changes(id, revisionOf(page))).empty()); + }); + then("a parent whose number of children changed is told \"children changed\", and its children leave the memory", [&] { + grid[0].push_back(9); + const auto pass = bench.changes(id, revisionOf(page)); + requireEqual(pathsOf(pass), std::vector{"/#0"}); + requireEqual(flagsOf(nodesOf(pass).front()), flag::childrenChanged); + requireEqual(countOf(nodesOf(pass).front()), std::size_t{4}); + require(!bench.memory(id)->contains("/#0/#0")); + // The inspector reads the list again; the next pass has nothing left to tell. + const auto again = bench.children(id, "/#0", revisionOf(pass)); + requireEqual(nodesOf(again).size(), std::size_t{5}); + require(nodesOf(bench.changes(id, revisionOf(again))).empty()); + }); + then("an optional that empties and a variant that changes alternative are told the same way", [&] { + std::tuple, std::variant> wrapped{5, 6}; + const auto other = bench.watch("wrapped", visiting(wrapped)); + auto opened = bench.open(other); + opened = bench.children(other, "/#0", revisionOf(opened)); + opened = bench.children(other, "/#1", revisionOf(opened)); + requireEqual(pathOf(nodesOf(opened).back()), std::string{"/#1/#0"}); + std::get<0>(wrapped).reset(); + std::get<1>(wrapped) = std::string{"now text"}; + const auto pass = bench.changes(other, revisionOf(opened)); + requireEqual(pathsOf(pass), std::vector{"/#0", "/#1"}); + checkEqual(flagsOf(nodesOf(pass)[0]), flag::childrenChanged); + checkEqual(valueOf(nodesOf(pass)[0]), std::string{"nullopt"}); + checkEqual(flagsOf(nodesOf(pass)[1]), flag::childrenChanged); + checkEqual(valueOf(nodesOf(pass)[1]), std::string{"alternative 1"}); + requireEqual(bench.memory(other)->size(), std::size_t{3}); + }); + then("a pass of several pages is read in the set it kept, whatever the object becomes meanwhile", [&] { + std::vector values(1000, 0); + const auto other = bench.watch("values", visiting(values)); + auto loaded = loadAll(bench, other); + for (auto& value : values) + value = 1; + auto pass = bench.changes(other, revisionOf(loaded), 0, 100); + requireEqual(nodesOf(pass).size(), std::size_t{100}); + requireEqual(nextOf(pass), 100.0); + const auto revision = revisionOf(pass); + for (auto& value : values) + value = 2; // between two pages + std::size_t told = 100; + while (nextOf(pass) != 0) { + pass = bench.changes(other, revision, nextOf(pass), 100); + require(!resyncOf(pass)); + requireEqual(revisionOf(pass), revision); + for (const auto& node : nodesOf(pass)) + requireEqual(valueOf(node), std::string{"1"}); + told += nodesOf(pass).size(); + } + requireEqual(told, std::size_t{1000}); + // The inspector holds the revision of the pass, and the next one finds what changed since. + const auto next = bench.changes(other, revision, 0, 1000); + requireEqual(valueOf(nodesOf(next).front()), std::string{"2"}); + requireEqual(finish(bench, other, next).size(), std::size_t{1000}); + }); + }}; + +const Scenario watchPassInterrupted{ + "A pass of thousands of pages is interrupted at any time, without a resynchronization (ADR-027, section 3, \"Interruption\")", + {"inspector"}, + [] { + Bench bench; + bench.limits.responseBudget = inspect::minPageBytes; + std::vector values(3000); + for (std::size_t index = 0; index < values.size(); ++index) + values[index] = static_cast(index); + const auto id = bench.watch("values", visiting(values)); + auto loaded = loadAll(bench, id); + requireEqual(bench.memory(id)->size(), std::size_t{3001}); + const auto changeUpTo = [&](std::size_t end) { + for (std::size_t index = 0; index < end; ++index) + values[index] += 10'000; + }; + // A page of one node: the pass would take 3 000 round trips. Five are made before it is interrupted. + const auto startPass = [&] { + auto pass = bench.changes(id, revisionOf(loaded), 0, 1); + requireEqual(pathsOf(pass), std::vector{"/#0"}); + for (int served = 1; served < 5; ++served) { + pass = bench.changes(id, revisionOf(pass), nextOf(pass), 1); + requireEqual(nodesOf(pass).size(), std::size_t{1}); + } + requireEqual(nextOf(pass), 5.0); + require(bench.memory(id)->passing()); + return pass; + }; + then("by a new pass: the differences not served are found again", [&] { + changeUpTo(3000); + const auto pass = startPass(); + const auto again = bench.changes(id, revisionOf(pass), 0, 1000); + const auto missing = finish(bench, id, again); + require(!resyncOf(again)); + requireEqual(missing.size(), std::size_t{2995}); + requireEqual(missing.front(), std::string{"/#5"}); + }); + then("by children: the page read is fresh, the rest is restored and found by the next pass", [&] { + changeUpTo(3000); + const auto pass = startPass(); + const auto page = bench.children(id, "", revisionOf(pass), 0, 10); + require(!resyncOf(page)); + requireEqual(valueOf(nodesOf(page)[10]), std::string{"10009"}); + require(!bench.memory(id)->passing()); + requireEqual(bench.memory(id)->size(), std::size_t{3001}); + const auto missing = finish(bench, id, bench.changes(id, revisionOf(page), 0, 1000)); + requireEqual(missing.size(), std::size_t{2990}); + requireEqual(missing.front(), std::string{"/#10"}); + }); + then("by fold: the fold is done on the restored memory", [&] { + changeUpTo(3000); + const auto pass = startPass(); + const auto folded = bench.fold(id, "/#7", revisionOf(pass)); + require(!resyncOf(folded)); + requireEqual(finish(bench, id, bench.changes(id, revisionOf(folded), 0, 1000)).size(), std::size_t{2995}); + }); + then("by a write whose target still shows what was sent: the value is written", [&] { + changeUpTo(2000); + const auto pass = startPass(); + const auto answer = bench.write(id, revisionOf(pass), "/#2999", "2999", "7"); + requireEqual(std::get<1>(answer), std::string{}); + requireEqual(values[2999], 7); + require(std::get<0>(answer) != revisionOf(pass)); + const auto missing = finish(bench, id, bench.changes(id, std::get<0>(answer), 0, 1000)); + requireEqual(missing.size(), std::size_t{1995}); // the write is in the memory: it is not a difference + }); + then("by a write whose target is in a page not served: it is compared with what the user sees, and refused as stale", [&] { + changeUpTo(3000); + const auto pass = startPass(); + const auto answer = bench.write(id, revisionOf(pass), "/#2999", "2999", "7"); + requireEqual(std::get<1>(answer), std::string{code::stale}); + requireEqual(values[2999], 12'999); + require(std::get<0>(answer) != revisionOf(pass)); + // The refusal carries the revision: the next call needs no resynchronization, and loses no difference. + const auto again = bench.changes(id, std::get<0>(answer), 0, 1000); + require(!resyncOf(again)); + requireEqual(finish(bench, id, again).size(), std::size_t{2995}); + }); + then("by a write that the mutator refuses: the answer is resolved with the code and the new revision", [&] { + std::vector guarded(100, 1); + const auto other = bench.watch("guarded", visiting(guarded), [](std::vector&, std::string_view, std::string_view) { + throw std::runtime_error("not today"); + }); + auto opened = loadAll(bench, other); + for (std::size_t index = 0; index < 50; ++index) + guarded[index] = 2; + const auto pass = bench.changes(other, revisionOf(opened), 0, 1); + const auto answer = bench.write(other, revisionOf(pass), "/#99", "1", "5"); + requireEqual(std::get<1>(answer), std::string{code::refused}); + requireEqual(std::get<2>(answer), std::string{"not today"}); + requireEqual(guarded[99], 1); + const auto again = bench.changes(other, std::get<0>(answer), 0, 1000); + require(!resyncOf(again)); + requireEqual(nodesOf(again).size(), std::size_t{49}); + }); + then("a refusal of the validation rejects without interrupting the pass", [&] { + changeUpTo(3000); + const auto pass = startPass(); + const auto memory = bench.memory(id); + checkEqual(codeOf([&] { + return bench.write(id, revisionOf(pass), "/#2999", "2999", "not a number"); + }), + std::string{code::parse}); + checkEqual(codeOf([&] { + return bench.write(id, revisionOf(pass), "", "", "1"); + }), + std::string{code::readOnly}); + checkEqual(codeOf([&] { + return bench.write(id, revisionOf(pass), "/#2999", "2999", std::string(bench.limits.maxWriteTextBytes + 1, '1')); + }), + std::string{code::tooLarge}); + checkEqual(codeOf([&] { + return bench.write(id, revisionOf(loaded), "/#2999", "2999", "1"); + }), + std::string{code::stale}); + require(memory->passing()); + requireEqual(static_cast(memory->revision()), revisionOf(pass)); + requireEqual(values[2999], 12'999); + // The pass goes on where it was. + const auto next = bench.changes(id, revisionOf(pass), nextOf(pass), 1); + require(!resyncOf(next)); + requireEqual(pathsOf(next), std::vector{"/#5"}); + }); + }}; + +const Scenario watchStaleRevisions{"A revision that is not the memory's has one contract, checked before any effect (ADR-027, section 3, \"Révision périmée\")", + {"inspector"}, + [] { + Bench bench; + std::vector values(50, 1); + const auto id = bench.watch("values", visiting(values)); + const auto opened = bench.open(id); + const auto memory = bench.memory(id); + for (auto& value : values) + value = 2; + const auto pass = bench.changes(id, revisionOf(opened), 0, 10); + require(memory->passing()); + const auto resynchronized = [&](const Page& page) { + require(resyncOf(page) && nodesOf(page).empty()); + requireEqual(nextOf(page), 0.0); + requireEqual(memory->size(), std::size_t{0}); + require(!memory->passing()); + requireEqual(revisionOf(page), static_cast(memory->revision())); + // The revision answered opens the root again. + requireEqual(nodesOf(bench.children(id, "", revisionOf(page))).size(), std::size_t{51}); + }; + then("children with an older revision during a pass: resynchronization, the pass released", [&] { + resynchronized(bench.children(id, "", revisionOf(opened))); + }); + then("changes with an older revision during a pass: the same", [&] { + resynchronized(bench.changes(id, revisionOf(opened))); + }); + then("fold with an older revision during a pass: the same, and nothing is folded", [&] { + resynchronized(bench.fold(id, "", revisionOf(opened))); + }); + then("a cursor that is not the pass's, or a page asked twice, is a page lost", [&] { + resynchronized(bench.changes(id, revisionOf(pass), 7, 10)); + }); + then("a page of a pass that is over is a page lost", [&] { + auto last = pass; + while (nextOf(last) != 0) + last = bench.changes(id, revisionOf(last), nextOf(last), 10); + require(!memory->passing()); + resynchronized(bench.changes(id, revisionOf(last), 40, 10)); + }); + then("write with an older revision during a pass is refused with no effect, then the next call resynchronizes", [&] { + const auto size = memory->size(); + requireEqual(codeOf([&] { + return bench.write(id, revisionOf(opened), "/#0", "1", "9"); + }), + std::string{code::stale}); + require(memory->passing()); + requireEqual(memory->size(), size); + requireEqual(static_cast(memory->revision()), revisionOf(pass)); + requireEqual(values[0], 2); + resynchronized(bench.children(id, "", revisionOf(opened))); + }); + then("two calls that change the memory sent without waiting: the second is stale", [&] { + const auto first = bench.fold(id, "/#3", revisionOf(pass)); + require(!resyncOf(first)); + resynchronized(bench.fold(id, "/#4", revisionOf(pass))); + }); + then("a removal told only in a page that was lost is neither shown nor kept after the resynchronization", [&] { + values.resize(40); + const auto shrunk = bench.changes(id, revisionOf(pass)); // tells the root's children changed: this page is "lost" + requireEqual(flagsOf(nodesOf(shrunk).front()), flag::childrenChanged); + const auto lost = bench.changes(id, revisionOf(pass)); + require(resyncOf(lost)); + const auto page = bench.children(id, "", revisionOf(lost)); + requireEqual(nodesOf(page).size(), std::size_t{41}); + require(!hasNode(page, "/#45")); + requireEqual(memory->size(), std::size_t{41}); + }); + then("reset empties the memory and releases the pass", [&] { + const auto revision = bench.reset(id); + require(!memory->passing()); + requireEqual(memory->size(), std::size_t{0}); + requireEqual(nodesOf(bench.children(id, "", revision)).size(), std::size_t{51}); + }); + then("numbers that are not whole numbers are refused", [&] { + for (const double bad : {-1.0, 0.5, 1e300}) + checkEqual(codeOf([&] { + return bench.changes(id, bad); + }), + std::string{"exception"}); + require(memory->passing()); + }); + }}; + +const Scenario watchPassAtomicity{ + "A call that changed the memory always answers; one that is rejected changed nothing (ADR-027, section 3, \"Atomicité des refus\")", + {"inspector"}, + [] { + Bench bench; + then("children is refused before it interrupts, when the memory restored would be full", [&] { + bench.limits.maxNodes = 12; + std::vector> grid{ + {1, 2, 3, 4}, + {5, 6, 7, 8, 9} + }; + const auto id = bench.watch("grid", visiting(grid)); + auto page = bench.open(id); + page = bench.children(id, "/#0", revisionOf(page)); + page = bench.children(id, "/#1", revisionOf(page)); + const auto memory = bench.memory(id); + requireEqual(memory->size(), std::size_t{12}); + grid[0][0] = 10; + grid[1].pop_back(); + const auto pass = bench.changes(id, revisionOf(page), 0, 1); + requireEqual(pathsOf(pass), std::vector{"/#0/#0"}); + requireEqual(memory->size(), std::size_t{7}); // the children of /#1 left the memory, in a page not served yet + requireEqual(codeOf([&] { + return bench.children(id, "/#0", revisionOf(pass)); + }), + std::string{code::limit}); + require(memory->passing()); + requireEqual(static_cast(memory->revision()), revisionOf(pass)); + const auto rest = bench.changes(id, revisionOf(pass), nextOf(pass), 1); + requireEqual(pathsOf(rest), std::vector{"/#1"}); + // Once that page is served the memory has room, and the list is read again. + requireEqual(nodesOf(bench.children(id, "/#1", revisionOf(rest))).size(), std::size_t{5}); + }); + then("after an interruption, a formatter's exception is the value of its node: the page is served", [&] { + std::vector fragiles(20); + const auto id = bench.watch("fragiles", visiting(fragiles)); + auto page = bench.open(id); + for (auto& fragile : fragiles) + fragile.value = 1; + const auto pass = bench.changes(id, revisionOf(page), 0, 2); + fragiles[5].failing = true; + page = bench.children(id, "", revisionOf(pass)); + require(!resyncOf(page)); + requireEqual(nodesOf(page).size(), std::size_t{21}); + requireEqual(kindOf(nodesOf(page)[6]), std::string{"opaque"}); + require(valueOf(nodesOf(page)[6]).contains("broken")); + requireEqual(valueOf(nodesOf(page)[7]), std::string{"fragile 1"}); + // And a pass tells it like any other change. + fragiles[5].failing = false; + requireEqual(pathsOf(bench.changes(id, revisionOf(page))), std::vector{"/#5"}); + }); + then("after an interruption, an exception of key() makes its elements elements without a key", [&] { + Rows rows{ + .rows = {{"a", 1}, {"b", 2}, {"c", 3}}, + .keyFails = false + }; + const auto id = bench.watch("rows", visiting(rows)); + auto page = bench.open(id); + requireEqual(pathsOf(page), std::vector{"", "/ka", "/kb", "/kc"}); + rows.rows[0].second = 10; + rows.rows[1].second = 20; + const auto pass = bench.changes(id, revisionOf(page), 0, 1); + rows.keyFails = true; + page = bench.children(id, "", revisionOf(pass)); + require(!resyncOf(page)); + requireEqual(pathsOf(page), std::vector{"", "/#0", "/#1", "/#2"}); + for (std::size_t index = 1; index < 4; ++index) + checkEqual(flagsOf(nodesOf(page)[index]), 0u); + // A pass with keys that fail tells the parent's children changed, never an exception. + rows.keyFails = false; + page = bench.children(id, "", revisionOf(page)); + rows.keyFails = true; + const auto failing = bench.changes(id, revisionOf(page)); + requireEqual(pathsOf(failing), std::vector{""}); + requireEqual(flagsOf(nodesOf(failing).front()), flag::childrenChanged); + }); + then("a pass sees the keys of an unfolded parent reordered", [&] { + Rows rows{ + .rows = {{"a", 1}, {"b", 2}, {"c", 3}}, + .keyFails = false + }; + const auto id = bench.watch("rows", visiting(rows)); + auto page = bench.open(id); + std::swap(rows.rows[0], rows.rows[2]); + const auto pass = bench.changes(id, revisionOf(page)); + requireEqual(pathsOf(pass), std::vector{""}); + requireEqual(flagsOf(nodesOf(pass).front()), flag::childrenChanged); + requireEqual(bench.memory(id)->size(), std::size_t{1}); + // The positions are read again. + page = bench.children(id, "", revisionOf(pass)); + requireEqual(pathsOf(page), std::vector{"", "/kc", "/kb", "/ka"}); + require(nodesOf(bench.changes(id, revisionOf(page))).empty()); + }); + }}; +} // namespace watch_pass diff --git a/test/unit/WatchPolicyRejects.cpp b/test/unit/WatchPolicyRejects.cpp new file mode 100644 index 00000000..74426ca5 --- /dev/null +++ b/test/unit/WatchPolicyRejects.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-27 +// +// WebFront — tests/unit +// Role: Buffers policies too small for the inspectors: each REJECT_* case must fail to compile on its assertion (ADR-027, section 3). +// Thread: worker-safe | Alloc: zero-hot-path +// LLM: compiled by CTest with -fsyntax-only (WatchPolicyRejects.*); without a REJECT_* macro the file compiles + +#include + +using namespace webfront; + +#if defined(REJECT_SMALL_BUFFER) +// The encoding buffer cannot hold a page of one node. +using Policy = http::CustomBuffersPolicy<8192, 8192, 2048>; +#elif defined(REJECT_SMALL_MESSAGE) +// The buffer is large enough, but a message is not: only maxMessageSize is too small. +using Policy = http::CustomBuffersPolicy<8192, 8192, 32768, 4000>; +#elif defined(REJECT_SMALL_WRITE) +// A message so small that a write request has less than 1 KiB left for its text. +using Policy = http::CustomBuffersPolicy<8192, 8192, 32768, 2000>; +#else +using Policy = http::DefaultBuffersPolicy; +#endif + +/// What the developer environment does when it registers webfront.inspector.* (DeveloperApp.hpp). +static constexpr inspect::Limits limits = inspect::limitsOf(); + +int main() { + return limits.responseBudget >= inspect::minPageBytes ? 0 : 1; +} diff --git a/test/unit/WatchTerminates.cpp b/test/unit/WatchTerminates.cpp new file mode 100644 index 00000000..a1477678 --- /dev/null +++ b/test/unit/WatchTerminates.cpp @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-27 +// +// WebFront — tests/unit +// Role: A process that destroys the handle of a watch from its own visitor: it must write a diagnostic, then terminate (ADR-027, section 5). +// Thread: worker-safe | Alloc: unrestricted +// LLM: process test (WatchDestroyedFromItsVisitor); CTest reads its output, the process must not reach its last line + +#include + +#include +#include +#include +#include +#include + +using namespace webfront; + +int main() { + // Terminating must not open a dialog nor write a core file: the handler says so and leaves with a status of its own. + std::set_terminate([] { + std::fputs("terminated\n", stderr); + std::fflush(stderr); + std::_Exit(3); + }); + auto registry = std::make_shared(); + std::vector values{1, 2, 3}; + inspect::Watch handle; + // A source that refers to the application's objects: its handle cannot be destroyed from its own operation. + const auto source = [&](inspect::Visit> visit) { + handle.reset(); + visit(values); + }; + using Shape = inspect::SourceShape>; + handle = inspect::Watch{ + registry, + registry->add( + inspect::makeWatch("values", "app.cpp:12", source, std::shared_ptr{}, inspect::NoExecutor{}, inspect::NoMutator{}))}; + const auto session = registry->session(1); + const auto limits = inspect::Limits{.responseBudget = inspect::minPageBytes, .maxWriteTextBytes = 1024}; + const auto id = static_cast(handle.id()); + static_cast(registry->children(session, id, "", registry->reset(session, id), 0, 10, limits)); + std::fputs("the process survived\n", stderr); + return 0; +} diff --git a/test/unit/WatchTests.cpp b/test/unit/WatchTests.cpp index 22155adb..eb154e21 100644 --- a/test/unit/WatchTests.cpp +++ b/test/unit/WatchTests.cpp @@ -400,6 +400,46 @@ const Scenario watchHandles{ require(!app.watch("byName", sharedValues)); // a function given by name requireEqual(handle.id(), std::uint64_t{0}); }); + then("every form of watch() compiles and registers nothing there", [&] { + struct State { + std::vector values; + }; + auto state = std::make_shared(); + const auto reference = [&value]() -> int& { + return value; + }; + const auto visitor = [&value](inspect::Visit visit) { + visit(value); + }; + const auto mutator = [](int& target, std::string_view, std::string_view text) { + target = static_cast(text.size()); + }; + const auto owned = [](State& kept, inspect::Visit> visit) { + visit(kept.values); + }; + const auto ownedReference = [](State& kept) -> std::vector& { + return kept.values; + }; + const auto ownedMutator = [](std::vector& target, std::string_view, std::string_view) { + target.clear(); + }; + require(!app.watch("executor", reference, app.uiExecutor())); + require(!app.watch("mutator", visitor, mutator)); + require(!app.watch("both", reference, app.uiExecutor(), mutator)); + require(!app.watch("owned", state, owned)); + require(!app.watch("owned executor", state, ownedReference, app.uiExecutor())); + require(!app.watch("owned mutator", state, owned, ownedMutator)); + require(!app.watch("owned both", state, ownedReference, app.uiExecutor(), ownedMutator)); + // A source of an ordinary form is accepted with a state it keeps alive. + require(!app.watch("owned plain", state, visitor)); + checkThrows([&] { + static_cast(app.watch("no state", std::shared_ptr{}, owned)); + }); + static_assert(inspect::OwnedSourceShape, State>::writable); + static_assert(!inspect::OwnedSourceShape, State>::visitor); + static_assert(inspect::WatchExecutor && !inspect::WatchExecutor); + static_assert(inspect::WatchMutator && !inspect::WatchMutator); + }); then("an invalid name is refused all the same", [&] { checkThrows([&] { static_cast(app.watch("", [&value]() -> const int& { diff --git a/test/unit/WatchTreeTests.cpp b/test/unit/WatchTreeTests.cpp new file mode 100644 index 00000000..5a093cf8 --- /dev/null +++ b/test/unit/WatchTreeTests.cpp @@ -0,0 +1,967 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-27 +// +// WebFront — tests/unit +// Role: The trees of the watches (ADR-027, sections 3 to 5): kinds, paths, pages within their budget, lists, keys, full values and bounds. +// Thread: worker-safe | Alloc: unrestricted +// LLM: unit tests of WatchValues.hpp and of the reading side of WatchMemory.hpp; passes are in WatchPassTests.cpp, writes in WatchWriteTests.cpp + +#include "WatchHarness.hpp" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace webfront::bdd; +using namespace webfront; + +namespace watch_tree { +using namespace watch_fixture; + +struct Point { + int x = 0; + int y = 0; +}; +struct Opaque { }; +/// Its formatter throws while `failing` is set, and writes `size` characters straight to the output otherwise. +struct Wide { + std::size_t size = 0; + bool failing = false; +}; + +/// A container that pages itself, with keys: the names of its items. +struct Keyed { + std::string name; + std::string text; + std::vector items; + bool keyFails = false; + mutable int visits = 0; + + [[nodiscard]] std::size_t size() const { + return items.size(); + } + template + void visit(std::size_t first, std::size_t count, Each&& each) { + ++visits; + for (std::size_t index = first; index < items.size() && index - first < count; ++index) + each(items[index]); + } + [[nodiscard]] std::string key(std::size_t position) const { + if (keyFails) + throw std::runtime_error("no key"); + return items.at(position).name; + } + [[nodiscard]] std::optional find(std::string_view wanted) const { + for (std::size_t index = 0; index < items.size(); ++index) + if (items[index].name == wanted) + return index; + return std::nullopt; + } +}; + +/// A container that pages itself without keys, and gives its elements by value (computed on demand). +struct Squares { + std::size_t count = 0; + [[nodiscard]] std::size_t size() const { + return count; + } + template + void visit(std::size_t first, std::size_t wanted, Each&& each) const { + for (std::size_t index = first; index < count && index - first < wanted; ++index) + each(index * index); + } +}; + +/// A keyed paged source of numbers, whose keys may repeat. +struct Row { + std::string id; + int value = 0; +}; +struct Rows { + std::vector rows; + [[nodiscard]] std::size_t size() const { + return rows.size(); + } + void visit(std::size_t first, std::size_t count, auto&& each) { + for (std::size_t index = first; index < rows.size() && index - first < count; ++index) + each(rows[index].value); + } + [[nodiscard]] std::string key(std::size_t position) const { + return rows.at(position).id; + } + [[nodiscard]] std::optional find(std::string_view wanted) const { + for (std::size_t index = 0; index < rows.size(); ++index) + if (rows[index].id == wanted) + return index; + return std::nullopt; + } +}; + +/// A sequence of itself: as deep as wanted. +struct Tree : std::vector { }; + +struct Labelled { + int value = 1; +}; + +using Small = http::CustomBuffersPolicy<8192, 8192, 32768, 8192>; + +std::vector messageBytes(const websocket::Frame& frame) { + std::vector bytes; + const auto buffers = frame.toBuffers(); + for (auto buffer = std::next(buffers.begin()); buffer != buffers.end(); ++buffer) { + const auto* first = static_cast(buffer->data()); + bytes.insert(bytes.end(), first, first + buffer->size()); + } + return bytes; +} +} // namespace watch_tree + +template <> +struct std::formatter : std::formatter { + auto format(const watch_tree::Point& point, std::format_context& context) const { + return std::format_to(context.out(), "({}, {})", point.x, point.y); + } +}; +template <> +struct std::formatter { + constexpr auto parse(std::format_parse_context& context) { + return context.begin(); + } + auto format(const watch_tree::Wide& wide, std::format_context& context) const { + if (wide.failing) + throw std::runtime_error("formatter\nfailed"); + auto out = context.out(); + for (std::size_t written = 0; written < wide.size; ++written) + *out++ = 'w'; + return out; + } +}; +template <> +struct webfront::inspect::Described { + static webfront::forms::Description description() { + return {.name = "Labelled", .fields = {webfront::forms::field("value", &watch_tree::Labelled::value, std::string(1000, 'L'))}}; + } +}; + +namespace watch_tree { + +static_assert(inspect::PagedSource && inspect::KeyedPagedSource); +static_assert(inspect::PagedSource && !inspect::KeyedPagedSource); +static_assert(!inspect::PagedSource>); +static_assert(inspect::kindOf() == "sequence" && inspect::kindOf() == "described"); +static_assert(inspect::limitsOf().responseBudget == 8192); +static_assert(inspect::limitsOf().maxWriteTextBytes == 8192 - inspect::writeRequestFixedBytes - 3); +static_assert(inspect::limitsOf().responseBudget == 32768); + +const Scenario watchValueKinds{"Each kind of value is rendered as a node (ADR-027, section 4)", {"inspector"}, [] { + using Everything = std::tuple, + std::optional, + std::variant, + std::pair, + std::map, + forms_fixture::Settings, + Point, + Opaque, + std::vector>; + Everything all{ + true, + -3, + 0.5, + "a\nb", + std::bitset<4>{"0101"}, + 7, + std::string{"text"}, + {1, "x"}, + {{"one", 1}, {"two", 2}}, + forms_fixture::Settings{}, + Point{1, 2}, + Opaque{}, + {4, 5} + }; + Bench bench; + const auto id = bench.watch("all", visiting(all)); + auto page = bench.open(id); + auto revision = revisionOf(page); + const auto unfold = [&](std::string_view path) { + auto children = bench.children(id, path, revision); + revision = revisionOf(children); + return children; + }; + then("the root is the watched object, under the watch's name, and comes first", [&] { + requireEqual(nodesOf(page).size(), std::size_t{14}); + const auto& root = nodesOf(page).front(); + requireEqual(pathOf(root), std::string{}); + requireEqual(kindOf(root), std::string{"tuple"}); + requireEqual(labelOf(root), std::string{"all"}); + requireEqual(countOf(root), std::size_t{13}); + requireEqual(nextOf(page), 0.0); + require(!resyncOf(page)); + }); + then("scalars, strings and bitsets show their value and are writable through a Visit", [&] { + const auto expect = [&](std::string_view path, std::string_view kind, std::string_view value) { + const auto& node = nodeAt(page, path); + checkEqual(kindOf(node), std::string(kind)); + checkEqual(valueOf(node), std::string(value)); + checkEqual(flagsOf(node), flag::writable); + checkEqual(countOf(node), std::size_t{0}); + }; + expect("/#0", "bool", "true"); + expect("/#1", "integer", "-3"); + expect("/#2", "real", "0.5"); + expect("/#3", + "string", + "a\xE2\x90\x8A" + "b"); // the control character is made visible + expect("/#4", "bitset", "0101"); + checkEqual(labelOf(nodeAt(page, "/#1")), std::string{"1"}); + }); + then("optional, variant, pair and tuple have their content as children", [&] { + checkEqual(valueOf(nodeAt(page, "/#5")), std::string{"engaged"}); + checkEqual(countOf(nodeAt(page, "/#5")), std::size_t{1}); + checkEqual(flagsOf(nodeAt(page, "/#5")), 0u); + const auto optional = unfold("/#5"); + requireEqual(pathsOf(optional), std::vector{"/#5", "/#5/#0"}); + checkEqual(labelOf(nodesOf(optional)[1]), std::string{"value"}); + checkEqual(valueOf(nodesOf(optional)[1]), std::string{"7"}); + checkEqual(kindOf(nodeAt(page, "/#6")), std::string{"variant"}); + checkEqual(valueOf(nodeAt(page, "/#6")), std::string{"alternative 1"}); + const auto variant = unfold("/#6"); + requireEqual(pathsOf(variant), std::vector{"/#6", "/#6/#1"}); // the segment tells the alternative + checkEqual(kindOf(nodesOf(variant)[1]), std::string{"string"}); + checkEqual(valueOf(nodesOf(variant)[1]), std::string{"text"}); + const auto pair = unfold("/#7"); + requireEqual(pathsOf(pair), std::vector{"/#7", "/#7/#0", "/#7/#1"}); + checkEqual(valueOf(nodesOf(pair)[2]), std::string{"x"}); + }); + then("a sequence and an associative container have their elements as children, a map's labelled by their keys", [&] { + checkEqual(kindOf(nodeAt(page, "/#8")), std::string{"map"}); + const auto map = unfold("/#8"); + requireEqual(pathsOf(map), std::vector{"/#8", "/#8/#0", "/#8/#1"}); + checkEqual(labelOf(nodesOf(map)[1]), std::string{"one"}); + checkEqual(valueOf(nodesOf(map)[2]), std::string{"2"}); + checkEqual(kindOf(nodesOf(map)[2]), std::string{"integer"}); + const auto sequence = unfold("/#12"); + requireEqual(pathsOf(sequence), std::vector{"/#12", "/#12/#0", "/#12/#1"}); + checkEqual(labelOf(nodesOf(sequence)[1]), std::string{"[0]"}); + checkEqual(valuesOf(sequence), std::vector{"", "4", "5"}); + }); + then("a described type has one child per field, told by its rank and labelled by its description", [&] { + checkEqual(kindOf(nodeAt(page, "/#9")), std::string{"described"}); + checkEqual(valueOf(nodeAt(page, "/#9")), std::string{"Settings"}); + const auto described = unfold("/#9"); + requireEqual(pathsOf(described), std::vector{"/#9", "/#9/.0", "/#9/.1", "/#9/.2", "/#9/.3", "/#9/.4"}); + checkEqual(labelOf(nodesOf(described)[1]), std::string{"Speed"}); + checkEqual(kindOf(nodesOf(described)[1]), std::string{"integer"}); + checkEqual(valueOf(nodesOf(described)[1]), std::string{"5"}); + checkEqual(kindOf(nodesOf(described)[2]), std::string{"real"}); + checkEqual(kindOf(nodesOf(described)[3]), std::string{"bool"}); + checkEqual(kindOf(nodesOf(described)[4]), std::string{"enum"}); + checkEqual(valueOf(nodesOf(described)[4]), std::string{"glider"}); + checkEqual(kindOf(nodesOf(described)[5]), std::string{"string"}); + checkEqual(flagsOf(nodesOf(described)[4]), flag::writable); + }); + then("a formattable type is formatted, and any other shows its type as not displayable", [&] { + checkEqual(kindOf(nodeAt(page, "/#10")), std::string{"formatted"}); + checkEqual(valueOf(nodeAt(page, "/#10")), std::string{"(1, 2)"}); + checkEqual(flagsOf(nodeAt(page, "/#10")), 0u); + checkEqual(kindOf(nodeAt(page, "/#11")), std::string{"opaque"}); + check(valueOf(nodeAt(page, "/#11")).contains("Opaque")); + check(valueOf(nodeAt(page, "/#11")).ends_with("(not displayable)")); + }); + }}; + +const Scenario watchSourcesRead{"A watch reads through the source the application gives (ADR-027, section 5)", {"inspector"}, [] { + Bench bench; + std::vector values{1, 2, 3}; + then("a Visit shows the same tree, read-only", [&] { + const auto id = bench.watch("values", [&](Visit> visit) { + visit(values); + }); + const auto page = bench.open(id); + requireEqual(valuesOf(page), std::vector{"", "1", "2", "3"}); + for (const auto& node : nodesOf(page)) + checkEqual(flagsOf(node), 0u); + checkEqual(std::get<4>(std::get<0>(bench.registry->page(0, 0, 10, 4096)).front()), false); + }); + then("the whole operation runs inside the visit, under the application's lock", [&] { + bool locked = false; + int reads = 0; + const auto id = bench.watch("locked", [&](Visit> visit) { + static const std::list wides{ + Wide{.size = 1, .failing = false}, + Wide{.size = 2, .failing = false} + }; + locked = true; + visit(wides); + locked = false; + ++reads; + }); + // The formatter of each element runs while the source holds its "lock". + const auto page = bench.open(id); + requireEqual(valuesOf(page), std::vector{"", "w", "ww"}); + requireEqual(reads, 1); + require(!locked); + }); + then("an accessor that returns a reference or a copy is read where the call runs, and never written", [&] { + const auto byReference = bench.watch("reference", [&]() -> std::vector& { + return values; + }); + const auto byCopy = bench.watch("copy", [&] { + return values; + }); + for (const auto id : {byReference, byCopy}) { + const auto page = bench.open(id); + requireEqual(valuesOf(page), std::vector{"", "1", "2", "3"}); + checkEqual(flagsOf(nodesOf(page)[1]), 0u); + requireEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "/#0", "1", "9"); + }), + std::string{code::readOnly}); + } + requireEqual(values.front(), 1); + }); + then("a source that does not give its object, or fails before giving it, rejects the call and changes nothing", [&] { + bool give = true; + bool fail = false; + const auto id = bench.watch("shy", [&](Visit> visit) { + if (fail) + throw std::runtime_error("locked\nout"); + if (give) + visit(values); + }); + const auto page = bench.open(id); + const auto memory = bench.memory(id); + give = false; + requireEqual(codeOf([&] { + return bench.children(id, "", revisionOf(page)); + }), + std::string{code::unavailable}); + fail = true; + requireEqual(codeOf([&] { + return bench.changes(id, revisionOf(page)); + }), + std::string{"exception"}); + check(messageOf([&] { + return bench.changes(id, revisionOf(page)); + }).contains("locked\xE2\x90\x8Aout")); + requireEqual(static_cast(memory->revision()), revisionOf(page)); + requireEqual(memory->size(), std::size_t{4}); + }); + then("a source that fails after its visit is reported, and the answer is served", [&] { + const auto id = bench.watch("late", [&](Visit> visit) { + visit(values); + throw std::runtime_error("after the visit"); + }); + const auto page = bench.open(id); + requireEqual(nodesOf(page).size(), std::size_t{4}); + require(bench.lastDiagnostic().contains("'late'")); + require(bench.lastDiagnostic().contains("after the visit")); + }); + then("a paged source that gives its elements by value is read through copies", [&] { + Squares squares{.count = 1000}; + const auto id = bench.watch("squares", visiting(squares)); + const auto page = bench.children(id, "", bench.reset(id), 0, 3); + requireEqual(valuesOf(page), std::vector{"", "0", "1", "4"}); + checkEqual(kindOf(nodesOf(page).front()), std::string{"sequence"}); + checkEqual(flagsOf(nodesOf(page)[1]), 0u); // a copy is not the object + requireEqual(nextOf(page), 3.0); + const auto far = bench.children(id, "", revisionOf(page), 999, 10); + requireEqual(valuesOf(far), std::vector{"", "998001"}); + requireEqual(nextOf(far), 0.0); + }); + }}; + +const Scenario watchPaths{"Paths are ASCII, reversible and bounded (ADR-027, section 3)", {"inspector"}, [] { + then("a key is percent-encoded, and decoded back", [&] { + const std::string key = "a/b%c \xC3\xA9~"; + const auto encoded = inspect::encodeKey(key); + requireEqual(encoded, std::string{"a%2Fb%25c%20%C3%A9~"}); + const auto segments = inspect::parsePath("/#12/.3/k" + encoded); + require(segments.has_value()); + requireEqual(segments->size(), std::size_t{3}); + require((*segments)[0] == inspect::Segment{.letter = '#', .number = 12, .key = {}}); + require((*segments)[1] == inspect::Segment{.letter = '.', .number = 3, .key = {}}); + requireEqual((*segments)[2].key, key); + require(inspect::parsePath("")->empty()); + require(inspect::parsePath("/k")->front().key.empty()); + }); + then("an ill-formed path is refused", [&] { + for (const auto& bad : std::vector{"#0", + "/", + "/#0/", + "//#0", + "/#", + "/#01", + "/#-1", + "/#1x", + "/x1", + "/#18446744073709551616", + "/k%2", + "/k%2f", + "/k%41", + "/ka/b c", + "/k" + std::string(inspect::maxKeyBytes + 1, 'a'), + "/" + std::string(inspect::maxPathBytes, '#')}) + check(!inspect::parsePath(bad).has_value()); + std::string deep; + for (std::size_t level = 0; level < inspect::maxPathSegments; ++level) + deep += "/#0"; + require(inspect::parsePath(deep).has_value()); + require(!inspect::parsePath(deep + "/#0").has_value()); + Bench bench; + std::vector values{1}; + const auto id = bench.watch("values", visiting(values)); + const auto page = bench.open(id); + for (const std::string_view bad : {"#0", "/#0/", "/k%41"}) + checkEqual(codeOf([&] { + return bench.children(id, bad, revisionOf(page)); + }), + std::string{code::unknown}); + requireEqual(bench.memory(id)->size(), std::size_t{2}); + }); + then("the 64th level is not unfolded", [&] { + Tree root; + Tree* leaf = &root; + for (int level = 0; level < 70; ++level) + leaf = &leaf->emplace_back(); + Bench bench; + const auto id = bench.watch("tree", visiting(root)); + auto page = bench.open(id); + std::string path; + for (std::size_t level = 1; level <= inspect::maxPathSegments; ++level) { + path += "/#0"; + requireEqual(flagsOf(nodesOf(page).back()) & flag::depthReached, + level == inspect::maxPathSegments ? flag::depthReached : 0u); + if (level < inspect::maxPathSegments) + page = bench.children(id, path, revisionOf(page)); + } + requireEqual(pathOf(nodesOf(page).back()), path); + requireEqual(countOf(nodesOf(page).back()), std::size_t{1}); + requireEqual(codeOf([&] { + return bench.children(id, path, revisionOf(page)); + }), + std::string{code::limit}); + }); + then("a parent whose children's paths could pass 1 024 bytes is not unfolded", [&] { + Keyed root; + Keyed* leaf = &root; + for (int level = 0; level < 9; ++level) { + leaf->items.push_back( + Keyed{.name = std::string(inspect::maxKeyBytes, static_cast('a' + level)), .text = {}, .items = {}}); + leaf = &leaf->items.back(); + } + Bench bench; + const auto id = bench.watch("keyed", visiting(root)); + auto page = bench.open(id); + std::string path; + std::size_t level = 0; + while ((flagsOf(nodesOf(page).back()) & flag::depthReached) == 0) { + path = pathOf(nodesOf(page).back()); + page = bench.children(id, path, revisionOf(page)); + ++level; + require(level < 9); + } + const auto& last = nodesOf(page).back(); + requireEqual(level, std::size_t{6}); // 7 segments of 130 bytes: an eighth would pass the bound + require(pathOf(last).size() <= inspect::maxPathBytes); + require(pathOf(last).size() + 1 + inspect::maxKeySegment > inspect::maxPathBytes); + require(inspect::detail::nodeBytes(last) <= inspect::maxNodeBytes); + requireEqual(codeOf([&] { + return bench.children(id, pathOf(last), revisionOf(page)); + }), + std::string{code::limit}); + }); + then("a field whose label is very long is told by its rank, its label cut, and is not writable", [&] { + Labelled labelled; + Bench bench; + const auto id = bench.watch("labelled", visiting(labelled)); + const auto page = bench.open(id); + const auto& node = nodesOf(page).back(); + requireEqual(pathOf(node), std::string{"/.0"}); + require(labelOf(node).size() <= inspect::maxTextBytes); + require(labelOf(node).ends_with("\xE2\x80\xA6")); + requireEqual(flagsOf(node), 0u); + }); + }}; + +const Scenario watchPagesBudget{"A page of children is paged, and reduced to the answer's budget (ADR-027, section 3)", {"inspector"}, [] { + Bench bench; + then("a list is read page after page, each starting with the parent", [&] { + std::vector values(1000); + for (std::size_t index = 0; index < values.size(); ++index) + values[index] = static_cast(index); + const auto id = bench.watch("values", visiting(values)); + auto page = bench.open(id); + requireEqual(nodesOf(page).size(), std::size_t{201}); + requireEqual(nextOf(page), 200.0); + std::size_t read = 200; + while (nextOf(page) != 0) { + const auto start = nextOf(page); + page = bench.children(id, "", revisionOf(page), start); + requireEqual(pathOf(nodesOf(page).front()), std::string{}); + requireEqual(countOf(nodesOf(page).front()), std::size_t{1000}); + requireEqual(valueOf(nodesOf(page)[1]), std::to_string(read)); + read += nodesOf(page).size() - 1; + } + requireEqual(read, std::size_t{1000}); + // A window anywhere in the container is read directly, and a count is at most 1 000. + page = bench.children(id, "", revisionOf(page), 990, 5000); + requireEqual(nodesOf(page).size(), std::size_t{11}); + requireEqual(pathOf(nodesOf(page).back()), std::string{"/#999"}); + bench.limits.responseBudget = 1 << 20; + page = bench.children(id, "", revisionOf(page), 0, 5000); + requireEqual(nodesOf(page).size(), std::size_t{1001}); + page = bench.children(id, "", revisionOf(page), 0, 0); + requireEqual(nodesOf(page).size(), std::size_t{1}); + }); + then("a page stops where the budget ends, and can fill it to the byte", [&] { + bench.limits.responseBudget = inspect::limitsOf().responseBudget; + std::vector texts(100, std::string(100, 't')); + const auto id = bench.watch("texts", visiting(texts)); + auto page = bench.open(id); + const auto held = nodesOf(page).size() - 1; + require(held > 10 && held < 100); + require(bytesOf(page) <= bench.limits.responseBudget); + requireEqual(nextOf(page), static_cast(held)); + // The last element served grows by exactly the room left: the page is then the budget, to the byte. + texts[held - 1].append(bench.limits.responseBudget - bytesOf(page), 't'); + page = bench.open(id); + requireEqual(nodesOf(page).size() - 1, held); + requireEqual(bytesOf(page), bench.limits.responseBudget); + // The message it makes is what the policy allows, and no more: maxMessageSize is here below the encoding buffer. + msg::FunctionReturn message; + websocket::Frame frame{ + std::span(reinterpret_cast(message.header().data()), message.header().size())}; + message.encodeParameter(page, frame); + const auto bytes = messageBytes(frame); + requireEqual(bytes.size(), http::maxMessageSize()); + auto decoded = msg::FunctionReturn::castFromRawData(bytes); + auto payload = decoded->payload(); + inspect::Page read; + decoded->decodeParameter(read, payload); + require(payload.empty()); + require(read == page); + // One byte more, and the element waits for the next page. + texts[held - 1] += 't'; + page = bench.open(id); + requireEqual(nodesOf(page).size() - 1, held - 1); + requireEqual(nextOf(page), static_cast(held - 1)); + }); + then("the smallest budget still holds a parent and a child whose every field is at its bound", [&] { + bench.limits.responseBudget = inspect::minPageBytes; + Keyed root; + for (int index = 0; index < 4; ++index) + root.items.push_back( + Keyed{.name = std::string(inspect::maxKeyBytes, static_cast('a' + index)), .text = {}, .items = {}}); + const auto id = bench.watch(std::string(inspect::maxTextBytes, 'n'), visiting(root)); + auto page = bench.open(id); + require(nodesOf(page).size() >= 2); + require(bytesOf(page) <= inspect::minPageBytes); + }); + }}; + +const Scenario watchMemoryLimit{"The memory of a connection for a watch holds 10 000 nodes at most (ADR-027, section 3)", {"inspector"}, [] { + Bench bench; + std::vector values(30'000, 1); + const auto id = bench.watch("values", visiting(values)); + auto page = bench.open(id, 1000); + std::string refused; + while (nextOf(page) != 0 && refused.empty()) { + const auto start = nextOf(page), revision = revisionOf(page); + refused = codeOf([&] { + page = bench.children(id, "", revision, start, 1000); + return 0; + }); + } + then("children is refused once it is full, and nothing was changed by the refusal", [&] { + requireEqual(refused, std::string{code::limit}); + requireEqual(bench.memory(id)->size(), inspect::maxMemoryNodes); + requireEqual(static_cast(bench.memory(id)->revision()), revisionOf(page)); + }); + then("folding makes room again", [&] { + const auto folded = bench.fold(id, "", revisionOf(page)); + require(!resyncOf(folded)); + requireEqual(bench.memory(id)->size(), std::size_t{1}); + requireEqual(nodesOf(bench.children(id, "", revisionOf(folded), 20'000, 10)).size(), std::size_t{11}); + }); + }}; + +const Scenario watchFirstOpening{ + "The root is always unfoldable, and the other calls need it in the memory (ADR-027, section 3)", + {"inspector"}, + [] { + Bench bench; + std::vector> rows{ + {"a", "b"}, + {"c"} + }; + const auto id = bench.watch("rows", visiting(rows)); + then("a watch found by watches() is opened by children of the root, on an empty memory", [&] { + const auto listed = bench.registry->page(0, 0, 10, 4096); + requireEqual(std::get<0>(std::get<0>(listed).front()), static_cast(id)); + requireEqual(std::get<2>(std::get<0>(listed).front()), std::string{"sequence"}); + require(std::get<4>(std::get<0>(listed).front())); + const auto revision = bench.reset(id); + // Nothing is in the memory yet: the root itself is refused to value, fold and write. + checkEqual(codeOf([&] { + return bench.value(id, ""); + }), + std::string{code::unknown}); + checkEqual(codeOf([&] { + return bench.fold(id, "", revision); + }), + std::string{code::unknown}); + checkEqual(codeOf([&] { + return bench.write(id, revision, "", "", "x"); + }), + std::string{code::unknown}); + checkEqual(codeOf([&] { + return bench.children(id, "/#0", revision); + }), + std::string{code::unknown}); + const auto page = bench.children(id, "", revision); + requireEqual(pathsOf(page), std::vector{"", "/#0", "/#1"}); + require(revisionOf(page) != revision); + require(bench.memory(id)->contains("") && bench.memory(id)->contains("/#1")); + requireEqual(bench.memory(id)->size(), std::size_t{3}); + }); + then("a first call with a revision the memory does not have is answered by a resynchronization, whose revision opens the root", [&] { + const auto first = bench.children(id, "", 0); + require(resyncOf(first) && nodesOf(first).empty()); + const auto page = bench.children(id, "", revisionOf(first)); + require(!resyncOf(page)); + requireEqual(nodesOf(page).size(), std::size_t{3}); + }); + then("after reset the tree is built again from the root, and the unfolded paths are found again", [&] { + auto page = bench.open(id); + page = bench.children(id, "/#0", revisionOf(page)); + requireEqual(bench.memory(id)->size(), std::size_t{5}); + const auto revision = bench.reset(id); + requireEqual(bench.memory(id)->size(), std::size_t{0}); + checkEqual(codeOf([&] { + return bench.children(id, "/#0", revision); + }), + std::string{code::unknown}); + page = bench.children(id, "", revision); + require(hasNode(page, "/#0")); + page = bench.children(id, "/#0", revisionOf(page)); + requireEqual(pathsOf(page), std::vector{"/#0", "/#0/#0", "/#0/#1"}); + }); + then("fold forgets a node's descendants and gives a new revision; the root's keeps the root", [&] { + auto page = bench.open(id); + page = bench.children(id, "/#0", revisionOf(page)); + page = bench.children(id, "/#1", revisionOf(page)); + requireEqual(bench.memory(id)->size(), std::size_t{6}); + auto folded = bench.fold(id, "/#0", revisionOf(page)); + require(nodesOf(folded).empty() && !resyncOf(folded) && revisionOf(folded) != revisionOf(page)); + requireEqual(bench.memory(id)->size(), std::size_t{4}); + require(bench.memory(id)->contains("/#0") && !bench.memory(id)->contains("/#0/#0")); + folded = bench.fold(id, "", revisionOf(folded)); + requireEqual(bench.memory(id)->size(), std::size_t{1}); + require(bench.memory(id)->contains("")); + // An older revision folds nothing: the memory is emptied and the inspector reads again. + page = bench.children(id, "", revisionOf(folded)); + const auto stale = bench.fold(id, "", revisionOf(folded)); + require(resyncOf(stale)); + requireEqual(bench.memory(id)->size(), std::size_t{0}); + }); + then("a scalar root gives a page of itself alone", [&] { + int answer = 42; + const auto scalar = bench.watch("answer", visiting(answer)); + const auto page = bench.open(scalar); + requireEqual(nodesOf(page).size(), std::size_t{1}); + requireEqual(valueOf(nodesOf(page).front()), std::string{"42"}); + requireEqual(flagsOf(nodesOf(page).front()), flag::writable); + requireEqual(nextOf(page), 0.0); + }); + then("a node that is gone from the object is told removed, and leaves the memory with its descendants", [&] { + auto page = bench.open(id); + page = bench.children(id, "/#1", revisionOf(page)); + rows.pop_back(); + page = bench.children(id, "/#1", revisionOf(page)); + requireEqual(nodesOf(page).size(), std::size_t{1}); + requireEqual(flagsOf(nodesOf(page).front()), flag::removed); + require(!bench.memory(id)->contains("/#1") && !bench.memory(id)->contains("/#1/#0")); + }); + }}; + +const Scenario watchListsStayCoherent{"A list of children is read on one state, or starts again (ADR-027, section 3, \"Cohérence des listes d'enfants\")", + {"inspector"}, + [] { + Bench bench; + then("an insertion at the head between two pages makes the list start again, and its last element is read", [&] { + std::vector letters{"a", "b", "c", "d"}; + const auto id = bench.watch("letters", visiting(letters)); + auto page = bench.open(id, 2); + requireEqual(valuesOf(page), std::vector{"", "a", "b"}); + requireEqual(nextOf(page), 2.0); + letters.insert(letters.begin(), "x"); + page = bench.children(id, "", revisionOf(page), 2, 2); + requireEqual(nodesOf(page).size(), std::size_t{1}); + requireEqual(flagsOf(nodesOf(page).front()), flag::childrenChanged); + requireEqual(countOf(nodesOf(page).front()), std::size_t{5}); + requireEqual(nextOf(page), 0.0); + requireEqual(bench.memory(id)->size(), std::size_t{1}); + std::vector read; + double start = 0; + do { + page = bench.children(id, "", revisionOf(page), start, 2); + requireEqual(pathOf(nodesOf(page).front()), std::string{}); + for (std::size_t index = 1; index < nodesOf(page).size(); ++index) + read.push_back(valueOf(nodesOf(page)[index])); + start = nextOf(page); + } while (start != 0); + requireEqual(read, std::vector{"x", "a", "b", "c", "d"}); + }); + then("with keys, an insertion that keeps the number of children is seen by the key of the last child served", [&] { + Keyed root; + for (const auto* name : {"a", "b", "c", "d"}) + root.items.push_back(Keyed{.name = name, .text = name, .items = {}, .keyFails = false, .visits = 0}); + const auto id = bench.watch("keyed", visiting(root)); + auto page = bench.open(id, 2); + requireEqual(pathsOf(page), std::vector{"", "/ka", "/kb"}); + root.items.insert(root.items.begin(), + Keyed{.name = "x", .text = "x", .items = {}, .keyFails = false, .visits = 0}); + root.items.pop_back(); // still four children: only the key of "b", now third, tells the change + page = bench.children(id, "", revisionOf(page), 2, 2); + requireEqual(nodesOf(page).size(), std::size_t{1}); + requireEqual(flagsOf(nodesOf(page).front()), flag::childrenChanged); + page = bench.children(id, "", revisionOf(page), 0, 10); + requireEqual(pathsOf(page), std::vector{"", "/kx", "/ka", "/kb", "/kc"}); + }); + }}; + +const Scenario watchKeys{ + "A paged source's keys name its elements in the paths, within what can be checked locally (ADR-027, section 5)", + {"inspector"}, + [] { + Bench bench; + Keyed root; + then("a key with '/', '%' and bytes that are not ASCII is carried by the path, and found again", [&] { + root.items.push_back(Keyed{.name = "a/b%\xC3\xA9", + .text = "odd", + .items = {Keyed{.name = "in", .text = "inner", .items = {}, .keyFails = false, .visits = 0}}, + .keyFails = false, + .visits = 0}); + const auto id = bench.watch("keyed", visiting(root)); + auto page = bench.open(id); + requireEqual(pathOf(nodesOf(page)[1]), std::string{"/ka%2Fb%25%C3%A9"}); + requireEqual(labelOf(nodesOf(page)[1]), std::string{"a/b%\xC3\xA9"}); + page = bench.children(id, pathOf(nodesOf(page)[1]), revisionOf(page)); + requireEqual(pathsOf(page), std::vector{"/ka%2Fb%25%C3%A9", "/ka%2Fb%25%C3%A9/kin"}); + }); + then("a key whose encoding passes 128 bytes, or that fails, tells its element by position, not writable", [&] { + root.items.push_back(Keyed{.name = std::string(inspect::maxKeyBytes + 1, 'k'), .text = "long", .items = {}, .keyFails = false, .visits = 0}); + root.items.push_back( + Keyed{.name = std::string(43, '/'), .text = "encoded long", .items = {}, .keyFails = false, .visits = 0}); // 129 bytes once encoded + root.items.push_back(Keyed{.name = "short", .text = "short", .items = {}, .keyFails = false, .visits = 0}); + const auto id = bench.watch("keyed", visiting(root)); + auto page = bench.open(id); + requireEqual(pathsOf(page), std::vector{"", "/#0", "/#1", "/kshort"}); + // The elements are sequences here: writability is read on a scalar member below. + root.keyFails = true; + page = bench.children(id, "", revisionOf(page)); + requireEqual(pathsOf(page), std::vector{"", "/#0", "/#1", "/#2"}); + require(!bench.memory(id)->contains("/kshort")); + }); + then("two elements of a page with one key are told by position, with one diagnostic", [&] { + Rows rows{ + .rows = {{"a", 1}, {"dup", 2}, {"dup", 3}, {"b", 4}, {"dup", 5}} + }; + const auto id = bench.watch("rows", visiting(rows)); + auto page = bench.open(id, 4); + requireEqual(pathsOf(page), std::vector{"", "/ka", "/#1", "/#2", "/kb"}); + checkEqual(flagsOf(nodeAt(page, "/ka")), flag::writable); + checkEqual(flagsOf(nodeAt(page, "/#1")), 0u); + checkEqual(flagsOf(nodeAt(page, "/#2")), 0u); + requireEqual(bench.diagnosticCount(), std::size_t{1}); + require(bench.lastDiagnostic().contains("'rows'")); + page = bench.children(id, "", revisionOf(page), 0, 4); + requireEqual(bench.diagnosticCount(), std::size_t{1}); + // A pass keeps them by position: their keys are not compared, so nothing is told changed. + const auto pass = bench.changes(id, revisionOf(page)); + require(nodesOf(pass).empty()); + // The same key in another page escapes the check: its element takes the path, and the precondition of a write + // then compares what is shown with what find() reaches. + page = bench.children(id, "", revisionOf(pass), 4, 4); + requireEqual(pathsOf(page), std::vector{"", "/kdup"}); + requireEqual(valueOf(nodesOf(page)[1]), std::string{"5"}); + const auto answer = bench.write(id, revisionOf(page), "/kdup", "5", "50"); + requireEqual(std::get<1>(answer), std::string{code::stale}); + requireEqual(rows.rows[1].value, 2); + requireEqual(rows.rows[4].value, 5); + }); + then("a key that find() resolves to an element with another key is a node removed", [&] { + struct Lying : Keyed { + [[nodiscard]] std::optional find(std::string_view) const { + return 0; // always the first element, whatever the key + } + }; + Lying lying; + lying.items.push_back(Keyed{.name = "a", .text = "a", .items = {Keyed{.name = "x", .text = {}, .items = {}}}}); + lying.items.push_back(Keyed{.name = "b", .text = "b", .items = {Keyed{.name = "y", .text = {}, .items = {}}}}); + const auto id = bench.watch("lying", visiting(lying)); + auto page = bench.open(id); + requireEqual(pathsOf(page), std::vector{"", "/ka", "/kb"}); + page = bench.children(id, "/kb", revisionOf(page)); + requireEqual(nodesOf(page).size(), std::size_t{1}); + requireEqual(flagsOf(nodesOf(page).front()), flag::removed); + require(!bench.memory(id)->contains("/kb")); + }); + }}; + +const Scenario watchFullValues{"A full value is read by fragments of an identified snapshot (ADR-027, section 3, \"Valeur complète\")", {"inspector"}, [] { + Bench bench; + bench.limits.responseBudget = inspect::limitsOf().responseBudget; + std::vector texts{std::string{}, "second"}; + for (int index = 0; index < 20'000; ++index) + texts[0] += "h\xC3\xA9\xE2\x82\xAC"; // 1, 2 and 3 bytes: fragments must not cut them + const auto id = bench.watch("texts", visiting(texts)); + const auto page = bench.open(id); + const auto read = [&](std::string_view path) { + std::string whole; + auto answer = bench.value(id, path); + while (true) { + const auto& [part, total, next, capped, snapshot] = answer; + require(part.size() <= bench.limits.responseBudget - inspect::responseHeaderBytes); + require(part.empty() || (static_cast(part.front()) & 0xC0u) != 0x80u); + whole += part; + if (next == 0) + return std::pair{whole, capped}; + requireEqual(next, static_cast(whole.size())); + answer = bench.value(id, path, snapshot, next); + } + }; + then("a value larger than a message is read whole, never cutting a character", [&] { + require(texts[0].size() > http::maxMessageSize()); + require((flagsOf(nodeAt(page, "/#0")) & flag::truncated) != 0); + require(valueOf(nodeAt(page, "/#0")).size() <= inspect::maxTextBytes); + const auto [whole, capped] = read("/#0"); + require(whole == texts[0]); + require(!capped); + require(!bench.session->hasSnapshot()); // freed with its last fragment + requireEqual(read("/#1").first, std::string{"second"}); + }); + then("the snapshot stays what it was when the object changes between two fragments", [&] { + const auto expected = texts[0]; + auto answer = bench.value(id, "/#0"); + texts[0] = "changed"; + std::string whole = std::get<0>(answer); + while (std::get<2>(answer) != 0) { + answer = bench.value(id, "/#0", std::get<4>(answer), std::get<2>(answer)); + whole += std::get<0>(answer); + } + require(whole == expected); + }); + then("a snapshot is cut at its cap, which the answer tells", [&] { + bench.limits.maxSnapshotBytes = 10'000; + const auto [whole, capped] = read("/#0"); + require(capped); + require(whole.size() <= 10'000 && whole.size() > 9'990); + require(texts[0].starts_with(whole)); + }); + then("a second reading replaces the snapshot, and the rest of the first one is refused", [&] { + const auto first = bench.value(id, "/#0"); + const auto second = bench.value(id, "/#0"); + require(std::get<4>(first) != std::get<4>(second)); + requireEqual(codeOf([&] { + return bench.value(id, "/#0", std::get<4>(first), std::get<2>(first)); + }), + std::string{code::stale}); + // The second reading goes on; an offset it was not given, another path or a snapshot of 0 with an offset do not. + checkEqual(codeOf([&] { + return bench.value(id, "/#0", std::get<4>(second), std::get<2>(second) - 1); + }), + std::string{code::stale}); + checkEqual(codeOf([&] { + return bench.value(id, "/#1", std::get<4>(second), std::get<2>(second)); + }), + std::string{code::stale}); + checkEqual(codeOf([&] { + return bench.value(id, "/#0", 0, 12); + }), + std::string{code::stale}); + require(!std::get<0>(bench.value(id, "/#0", std::get<4>(second), std::get<2>(second))).empty()); + }); + then("a node that left the object, or a path the memory does not hold, has no value", [&] { + checkEqual(codeOf([&] { + return bench.value(id, "/#5"); + }), + std::string{code::unknown}); + texts.pop_back(); + checkEqual(codeOf([&] { + return bench.value(id, "/#1"); + }), + std::string{code::stale}); + }); + }}; + +const Scenario watchBoundedFormatting{"A value is written into a bounded receiver, never formatted whole then cut (ADR-027, section 3, \"Formatage borné\")", + {"inspector"}, + [] { + Bench bench; + then("a string of 100 MiB is copied up to the bound only", [&] { + std::vector texts{std::string(100u * 1024 * 1024, 's')}; + const auto id = bench.watch("texts", visiting(texts)); + const auto page = bench.open(id); + const auto& node = nodesOf(page)[1]; + require(valueOf(node).size() <= inspect::maxTextBytes); + require(valueOf(node).ends_with("\xE2\x80\xA6")); + requireEqual(flagsOf(node), flag::truncated); // cut, hence not writable + const auto answer = bench.value(id, "/#0"); + requireEqual(std::get<1>(answer), static_cast(inspect::maxSnapshotBytes)); + require(std::get<3>(answer)); + }); + then("a formatter that writes more than 1 GiB to the output iterator is cut, and the cut is told", [&] { + std::vector wides{ + Wide{.size = (std::size_t{1} << 30) + 5, .failing = false}, + Wide{ .size = 3, .failing = false} + }; + const auto id = bench.watch("wides", visiting(wides)); + const auto page = bench.open(id); + requireEqual(kindOf(nodesOf(page)[1]), std::string{"formatted"}); + require(valueOf(nodesOf(page)[1]).size() <= inspect::maxTextBytes); + requireEqual(flagsOf(nodesOf(page)[1]), flag::truncated); + requireEqual(valueOf(nodesOf(page)[2]), std::string{"www"}); + requireEqual(flagsOf(nodesOf(page)[2]), 0u); + }); + then("the receiver stores no more than its bound, and knows what it lost", [&] { + inspect::TextSink sink{8}; + sink.append(std::string_view{"abc"}); + sink.format(123456789); + requireEqual(sink.text(), std::string{"abc12345"}); + require(sink.truncated() && sink.full()); + inspect::TextSink exact{4}; + exact.format(1234); + require(!exact.truncated()); + }); + then("an exception of a formatter becomes the value of its node, which is opaque", [&] { + std::vector wides{ + Wide{.size = 1, .failing = true}, + Wide{.size = 2, .failing = false} + }; + const auto id = bench.watch("wides", visiting(wides)); + const auto page = bench.open(id); + requireEqual(kindOf(nodesOf(page)[1]), std::string{"opaque"}); + requireEqual(valueOf(nodesOf(page)[1]), + std::string{"\xE2\x80\xB9" + "exception : formatter\xE2\x90\x8A" + "failed\xE2\x80\xBA"}); + requireEqual(valueOf(nodesOf(page)[2]), std::string{"ww"}); + }); + }}; +} // namespace watch_tree diff --git a/test/unit/WatchWriteTests.cpp b/test/unit/WatchWriteTests.cpp new file mode 100644 index 00000000..619ff4d3 --- /dev/null +++ b/test/unit/WatchWriteTests.cpp @@ -0,0 +1,659 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-27 +// +// WebFront — tests/unit +// Role: Writes through a watch, its executor and the destruction of its handle (ADR-027, sections 5 and 6). +// Thread: worker-safe | Alloc: unrestricted +// LLM: unit tests of Memory::write and of WatchRegistry's lifecycle; the process that must terminate is WatchTerminates.cpp + +#include "WatchHarness.hpp" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace webfront::bdd; +using namespace webfront; +using namespace std::chrono_literals; + +namespace watch_write { +using namespace watch_fixture; + +struct Player { + std::string name; + int score = 0; +}; +struct Game { + forms_fixture::Settings settings; + int turn = 0; +}; + +/// A keyed paged source of scores. +struct Scores { + std::vector players; + [[nodiscard]] std::size_t size() const { + return players.size(); + } + void visit(std::size_t first, std::size_t count, auto&& each) { + for (std::size_t index = first; index < players.size() && index - first < count; ++index) + each(players[index].score); + } + [[nodiscard]] std::string key(std::size_t position) const { + return players.at(position).name; + } + [[nodiscard]] std::optional find(std::string_view wanted) const { + for (std::size_t index = 0; index < players.size(); ++index) + if (players[index].name == wanted) + return index; + return std::nullopt; + } +}; + +/// Lets a test hold an operation inside its source, and know that it is there. +struct Gate { + std::mutex mutex; + std::condition_variable changed; + bool inside = false; + bool open = false; + + void pass() { + std::unique_lock lock{mutex}; + inside = true; + changed.notify_all(); + changed.wait(lock, [this] { + return open; + }); + } + void waitInside() { + std::unique_lock lock{mutex}; + changed.wait(lock, [this] { + return inside; + }); + } + void release() { + std::scoped_lock lock{mutex}; + open = true; + changed.notify_all(); + } +}; + +using Small = http::CustomBuffersPolicy<8192, 8192, 32768, 8192>; + +/// A thread that runs a loop, as the thread that owns an object does: the executor of a watch. +struct LoopThread { + networking::ex::run_loop loop; + std::thread thread; + + void start() { + thread = std::thread{[this] { + loop.run(); + }}; + } + ~LoopThread() { + loop.finish(); + if (thread.joinable()) + thread.join(); + } +}; + +template +Result await(ResultTask task) { + return std::get<0>(*networking::ex::sync_wait(std::move(task))); +} +} // namespace watch_write + +template <> +struct webfront::inspect::Described { + static webfront::forms::Description description() { + return {.name = "Game", .fields = {webfront::forms::field("turn", &watch_write::Game::turn, "Turn", webfront::forms::Bounds{0, 100})}}; + } +}; + +namespace watch_write { + +const Scenario watchWrites{"A value is written only where the application allows it, and only if it still shows what was displayed (ADR-027, section 6)", + {"inspector"}, + [] { + Bench bench; + using Board = std::tuple, std::string, bool, std::bitset<4>, double, std::pair>; + Board board{ + {1, 2, 3}, + "name", + false, + std::bitset<4>{"0001"}, + 1.5, + {7, 8} + }; + const auto id = bench.watch("board", visiting(board)); + auto page = bench.open(id); + page = bench.children(id, "/#0", revisionOf(page)); + const auto write = [&](std::string_view path, std::string_view expected, std::string_view text) { + const auto answer = bench.write(id, revisionOf(page), path, expected, text); + std::get<2>(page) = std::get<0>(answer); // the inspector adopts the revision of every answer + return answer; + }; + then("an accepted write changes the object, the memory, and gives a new revision", [&] { + const auto before = revisionOf(page); + const auto answer = write("/#0/#1", "2", "20"); + requireEqual(std::get<1>(answer), std::string{}); + require(std::get<0>(answer) != before); + requireEqual(std::get<0>(board)[1], 20); + require(nodesOf(bench.changes(id, std::get<0>(answer))).empty()); // the memory already holds the new value + }); + then("each writable kind parses its own text", [&] { + checkEqual(std::get<1>(write("/#1", "name", "other\nname")), std::string{}); + checkEqual(std::get<1>(board), std::string{"other\nname"}); + checkEqual(std::get<1>(write("/#2", "false", "true")), std::string{}); + check(std::get<2>(board)); + checkEqual(std::get<1>(write("/#3", "0001", "1010")), std::string{}); + checkEqual(std::get<3>(board).to_string(), std::string{"1010"}); + checkEqual(std::get<1>(write("/#4", "1.5", "-0.25")), std::string{}); + checkEqual(std::get<4>(board), -0.25); + }); + then("a text that is not a value of the node rejects, and nothing changes", [&] { + const auto memory = bench.memory(id); + for (const auto& [path, expected, text] : std::vector>{ + {"/#0/#1", "2", "two"}, + {"/#0/#1", "2", "99999999999"}, + {"/#0/#1", "2", ""}, + { "/#2", "false", "yes"}, + { "/#3", "0001", "101"}, + { "/#3", "0001", "10102"}, + { "/#4", "1.5", "nan"} + }) + checkEqual(codeOf([&] { + return bench.write(id, revisionOf(page), path, expected, text); + }), + std::string{code::parse}); + requireEqual(static_cast(memory->revision()), revisionOf(page)); + requireEqual(std::get<0>(board)[1], 2); + }); + then("a node that is not writable rejects", [&] { + for (const std::string_view path : {"", "/#0", "/#5"}) + checkEqual(codeOf([&] { + return bench.write(id, revisionOf(page), path, "", "1"); + }), + std::string{code::readOnly}); + checkEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "/#5/#0", "7", "1"); // not in the memory: its parent is folded + }), + std::string{code::unknown}); + }); + then("a text longer than the bound rejects", [&] { + checkEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "/#1", "name", std::string(bench.limits.maxWriteTextBytes + 1, 'x')); + }), + std::string{code::tooLarge}); + checkEqual(std::get<1>(write("/#1", "name", std::string(bench.limits.maxWriteTextBytes, 'x'))), std::string{}); + requireEqual(std::get<1>(board).size(), bench.limits.maxWriteTextBytes); + }); + then("an insertion before the target makes the write stale: an ancestor no longer shows what it did", [&] { + std::get<0>(board).insert(std::get<0>(board).begin(), 0); // /#0/#1 now names the former first element + const auto answer = write("/#0/#1", "2", "20"); + requireEqual(std::get<1>(answer), std::string{code::stale}); + requireEqual(std::get<0>(board), std::vector({0, 1, 2, 3})); + }); + then("a target that was replaced makes the write stale", [&] { + std::get<0>(board)[1] = 5; + requireEqual(std::get<1>(write("/#0/#1", "2", "20")), std::string{code::stale}); + requireEqual(std::get<0>(board)[1], 5); + // And so does a value the inspector did not show, whatever the memory holds. + requireEqual(std::get<1>(write("/#0/#0", "100", "20")), std::string{code::stale}); + requireEqual(std::get<0>(board)[0], 1); + }); + then("an older revision rejects the write, with no effect", [&] { + const auto old = revisionOf(page); + page = bench.children(id, "/#5", old); + requireEqual(codeOf([&] { + return bench.write(id, old, "/#0/#1", "2", "20"); + }), + std::string{code::stale}); + requireEqual(std::get<0>(board)[1], 2); + requireEqual(static_cast(bench.memory(id)->revision()), revisionOf(page)); + }); + then("a node that left the object makes the write stale", [&] { + std::get<0>(board).clear(); + requireEqual(std::get<1>(write("/#0/#1", "2", "20")), std::string{code::stale}); + }); + }}; + +const Scenario watchWritesDescribed{"The fields of a described type are written within their description, and a scalar root is written itself", + {"inspector"}, + [] { + Bench bench; + then("a field takes a value inside its bounds, a choice one of its names", [&] { + forms_fixture::Settings settings; + const auto id = bench.watch("settings", visiting(settings)); + auto page = bench.open(id); + auto answer = bench.write(id, revisionOf(page), "/.0", "5", "9"); + requireEqual(std::get<1>(answer), std::string{}); + requireEqual(settings.speed, 9); + for (const std::string_view text : {"11", "0", "2.5", "fast"}) + checkEqual(codeOf([&] { + return bench.write(id, std::get<0>(answer), "/.0", "9", text); + }), + std::string{code::parse}); + answer = bench.write(id, std::get<0>(answer), "/.3", "glider", "pulsar"); + requireEqual(std::get<1>(answer), std::string{}); + require(settings.pattern == forms_fixture::Pattern::pulsar); + checkEqual(codeOf([&] { + return bench.write(id, std::get<0>(answer), "/.3", "pulsar", "spaceship"); + }), + std::string{code::parse}); + answer = bench.write(id, std::get<0>(answer), "/.1", "0.25", "0.75"); + requireEqual(settings.density, 0.75); + answer = bench.write(id, std::get<0>(answer), "/.4", "Life", "Death"); + requireEqual(settings.title, std::string{"Death"}); + requireEqual(settings.speed, 9); + }); + then("a scalar root is written by the empty path", [&] { + int answer = 42; + const auto id = bench.watch("answer", visiting(answer)); + const auto page = bench.open(id); + const auto done = bench.write(id, revisionOf(page), "", "42", "43"); + requireEqual(std::get<1>(done), std::string{}); + requireEqual(answer, 43); + }); + then("an element of a paged source is written by its key, wherever it moved", [&] { + Scores scores{ + .players = {{"ada", 1}, {"bob", 2}, {"cy", 3}} + }; + const auto id = bench.watch("scores", visiting(scores)); + const auto page = bench.open(id); + requireEqual(pathsOf(page), std::vector{"", "/kada", "/kbob", "/kcy"}); + std::swap(scores.players[0], scores.players[2]); // bob stays second, ada is now last + const auto answer = bench.write(id, revisionOf(page), "/kada", "1", "100"); + requireEqual(std::get<1>(answer), std::string{}); + requireEqual(scores.players[2].name, std::string{"ada"}); + requireEqual(scores.players[2].score, 100); + requireEqual(scores.players[0].score, 3); + }); + }}; + +const Scenario watchMutators{"The application's mutator applies a write its own way, or refuses it (ADR-027, section 6)", {"inspector"}, [] { + Bench bench; + std::vector values{1, 2, 3}; + then("it receives the object, the path and the text, in place of the assignment", [&] { + std::string seenPath, seenText; + const auto id = bench.watch("values", + visiting(values), + [&](std::vector& object, std::string_view path, std::string_view text) { + seenPath = path; + seenText = text; + object.assign(3, 7); // its own way: keeps an invariant of the application + }); + const auto page = bench.open(id); + const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "5"); + requireEqual(std::get<1>(answer), std::string{}); + requireEqual(seenPath, std::string{"/#1"}); + requireEqual(seenText, std::string{"5"}); + requireEqual(values, std::vector({7, 7, 7})); + // The memory holds what the target shows now; the other nodes are found by the next pass. + requireEqual(pathsOf(bench.changes(id, std::get<0>(answer))), std::vector({"/#0", "/#2"})); + // The text was parsed for the node first: the mutator is not called for a text that is not a number. + seenText.clear(); + checkEqual(codeOf([&] { + return bench.write(id, std::get<0>(answer), "/#1", "7", "seven"); + }), + std::string{code::stale}); // the revision moved with the pass: refused before anything + require(seenText.empty()); + }); + then("a message of 1 MiB is cut to 256 bytes on a character, and the answer fits the smallest budget", [&] { + // 254 bytes then characters of 3 bytes: the first of them straddles the bound. + std::string message(254, 'm'); + while (message.size() < 1024 * 1024) + message += "\xE2\x82\xAC"; + const auto id = bench.watch("values", visiting(values), [&](std::vector&, std::string_view, std::string_view) { + throw std::runtime_error(message); + }); + const auto page = bench.open(id); + const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "5"); + requireEqual(std::get<1>(answer), std::string{code::refused}); + const auto& text = std::get<2>(answer); + require(text.size() <= inspect::maxTextBytes); + requireEqual(text, std::string(253, 'm') + "\xE2\x80\xA6"); // back to a whole character, then the ellipsis + require(std::get<0>(answer) != revisionOf(page)); + requireEqual(values[1], 2); + const auto bytes = 8 + 2 + 9 + inspect::detail::stringBytes(std::get<1>(answer).size()) + + inspect::detail::stringBytes(text.size()); + require(bytes <= inspect::minPageBytes); + // The revision was received: the next call is not a resynchronization. + require(!resyncOf(bench.changes(id, std::get<0>(answer)))); + }); + }}; + +const Scenario watchWriteRequestBudget{ + "A write request fits the message size, its text bounded on both sides (ADR-027, section 3, \"Budget d'une requête\")", + {"inspector"}, + [] { + const auto limits = inspect::limitsOf(); + then("with every argument at its largest, the request is exactly the largest message", [&] { + msg::FunctionCall call; + websocket::Frame frame{std::span(reinterpret_cast(call.header().data()), call.header().size())}; + const std::string path(inspect::maxPathBytes, 'p'), expected(inspect::maxTextBytes, 'e'), text(limits.maxWriteTextBytes, 't'); + call.encodeParameter(std::string_view{"webfront.inspector.write"}, frame); + call.encodeParameter(9007199254740992.0, frame); + call.encodeParameter(9007199254740992.0, frame); + call.encodeParameter(path, frame); + call.encodeParameter(expected, frame); + call.encodeParameter(text, frame); + requireEqual(call.header().size() + call.getPayloadSize(), http::maxMessageSize()); + requireEqual(inspect::requestBudget, http::maxMessageSize()); + }); + then("C++ refuses a text one byte too long, whatever the page checked", [&] { + Bench bench; + bench.limits = limits; + std::string text = "t"; + const auto id = bench.watch("text", visiting(text)); + const auto page = bench.open(id); + requireEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "", "t", std::string(limits.maxWriteTextBytes + 1, 'x')); + }), + std::string{code::tooLarge}); + requireEqual(std::get<1>(bench.write(id, revisionOf(page), "", "t", std::string(limits.maxWriteTextBytes, 'x'))), std::string{}); + requireEqual(std::get<0>(inspect::WatchRegistry::limits(limits)), static_cast(limits.maxWriteTextBytes)); + requireEqual(std::get<1>(inspect::WatchRegistry::limits(limits)), 8192.0); + requireEqual(std::get<2>(inspect::WatchRegistry::limits(limits)), 10'000.0); + }); + }}; + +const Scenario watchRegistrations{ + "A watch is known by an identifier that is never reused (ADR-027, section 3, \"Découverte\")", + {"inspector"}, + [] { + Bench bench; + int value = 1; + then("a watch removed then declared again under its name is another watch: calls to the old one are refused", [&] { + const auto first = bench.watch("value", visiting(value)); + const auto page = bench.open(first); + bench.registry->remove(first); + const auto second = bench.watch("value", visiting(value)); + require(second != first); + for (const auto& call : std::vector>{[&] { + static_cast(bench.children(first, "", revisionOf(page))); + }, + [&] { + static_cast(bench.changes(first, revisionOf(page))); + }, + [&] { + static_cast(bench.fold(first, "", revisionOf(page))); + }, + [&] { + static_cast(bench.reset(first)); + }, + [&] { + static_cast(bench.value(first, "")); + }, + [&] { + static_cast(bench.write(first, revisionOf(page), "", "1", "2")); + }}) + checkEqual(codeOf([&] { + call(); + return 0; + }), + std::string{code::unknown}); + requireEqual(value, 1); + requireEqual(nodesOf(bench.open(second)).size(), std::size_t{1}); + }); + then("removing a watch frees its memories and its snapshot, for every connection", [&] { + std::string text(20'000, 't'); + bench.limits.responseBudget = inspect::minPageBytes; + const auto id = bench.watch("text", visiting(text)); + const auto other = bench.registry->session(2); + static_cast(bench.open(id)); + static_cast( + bench.registry->children(other, static_cast(id), "", bench.registry->reset(other, static_cast(id)), 0, 10, bench.limits)); + static_cast(bench.value(id, "")); + require(bench.session->hasSnapshot()); + require(bench.session->find(id) != nullptr && other->find(id) != nullptr); + bench.registry->remove(id); + require(!bench.session->hasSnapshot()); + require(bench.session->find(id) == nullptr && other->find(id) == nullptr); + }); + then("a closed connection frees what was kept for it", [&] { + const auto id = bench.watch("value", visiting(value)); + static_cast(bench.open(id)); + requireEqual(bench.registry->sessionCount(), std::size_t{1}); + bench.registry->forget(1); + requireEqual(bench.registry->sessionCount(), std::size_t{0}); + require(bench.session->find(id) == nullptr); + requireEqual(codeOf([&] { + return bench.open(id); + }), + std::string{bridge_code::disconnected}); + }); + }}; + +const Scenario watchDestruction{"Destroying a watch's handle waits for an operation, unless the source owns its state (ADR-027, section 5)", {"inspector"}, [] { + Bench bench; + then("a source that refers to the application's objects: the destruction, outside the lock, waits for the operation", [&] { + std::mutex mutex; + std::vector values{1, 2, 3}; + Gate gate; + const auto id = bench.watch("values", [&](Visit> visit) { + std::scoped_lock lock{mutex}; + gate.pass(); + visit(values); + }); + auto reading = std::async(std::launch::async, [&] { + return codeOf([&] { + return bench.open(id); + }); + }); + gate.waitInside(); + std::atomic removed{false}; + auto removing = std::async(std::launch::async, [&] { + bench.registry->remove(id); // outside the lock of the source + removed = true; + }); + std::this_thread::sleep_for(50ms); + require(!removed); // the operation still reads the application's objects + gate.release(); + removing.get(); + require(removed); + // The operation ended on live objects, and its answer is the terminal refusal. + requireEqual(reading.get(), std::string{code::unknown}); + requireEqual(bench.diagnosticCount(), std::size_t{0}); + }); + then("a destruction that waits longer than the delay says which watch, and goes on waiting", [&] { + bench.registry->destructionWarning = 20ms; + std::vector values{1}; + Gate gate; + const auto id = bench.watch("slow", [&](Visit> visit) { + gate.pass(); + visit(values); + }); + auto reading = std::async(std::launch::async, [&] { + return codeOf([&] { + return bench.open(id); + }); + }); + gate.waitInside(); + auto removing = std::async(std::launch::async, [&] { + bench.registry->remove(id); + }); + requireEventually([&] { + return bench.diagnosticCount() == 1; + }); + require(bench.lastDiagnostic().contains("'slow'")); + require(bench.lastDiagnostic().contains("test.cpp:1")); + require(removing.wait_for(0ms) != std::future_status::ready); + gate.release(); + removing.get(); + requireEqual(reading.get(), std::string{code::unknown}); + requireEqual(bench.diagnosticCount(), std::size_t{1}); + }); + then("a source that owns its state: destroyed under the source's lock while an operation waits for it, without deadlock", + [&] { + struct State { + std::mutex mutex; + std::vector values{1, 2, 3}; + bool read = false; + }; + auto state = std::make_shared(); + std::weak_ptr alive = state; + std::atomic asked{false}; + const auto id = bench.owning("owned", state, [&asked](State& owned, Visit> visit) { + asked = true; + std::scoped_lock lock{owned.mutex}; + owned.read = true; + visit(owned.values); + }); + std::future reading; + { + std::scoped_lock lock{state->mutex}; + reading = std::async(std::launch::async, [&] { + return codeOf([&] { + return bench.open(id); + }); + }); + requireEventually([&] { + return asked.load(); + }); + bench.registry->remove(id); // under the lock the source takes: it does not wait + require(!bench.registry->contains(id)); + } + state.reset(); // the operation is now the only owner of the state + requireEqual(reading.get(), std::string{code::unknown}); + require(alive.expired()); // it lived until the operation ended, and no longer + }); + then("a source that owns its state: destroyed from its own operation, the state lives until the operation ends", [&] { + struct State { + std::vector values{1, 2, 3}; + inspect::Watch handle; + bool finished = false; + }; + auto state = std::make_shared(); + std::weak_ptr alive = state; + bool finished = false; + const auto id = bench.owning("self", state, [&finished](State& owned, Visit> visit) { + owned.handle.reset(); // the handle was the last other owner of the state + owned.values.push_back(4); + visit(owned.values); + owned.finished = true; + finished = true; + }); + state->handle = inspect::Watch{bench.registry, id}; + state.reset(); + require(!alive.expired()); + requireEqual(codeOf([&] { + return bench.open(id); + }), + std::string{code::unknown}); + require(finished); + require(alive.expired()); + require(!bench.registry->contains(id)); + }); + then("a write that was applied when the watch is removed says so in its refusal", [&] { + struct State { + int value = 1; + inspect::Watch handle; + }; + auto state = std::make_shared(); + bool drop = false; + const auto id = bench.registry->add(inspect::makeWatch), State>>( + "written", + "test.cpp:1", + +[](State& owned, Visit visit) { + visit(owned.value); + }, + state, + inspect::NoExecutor{}, + [&](int& value, std::string_view, std::string_view text) { + value = std::stoi(std::string(text)); + if (drop) + state->handle.reset(); + })); + state->handle = inspect::Watch{bench.registry, id}; + const auto page = bench.open(id); + drop = true; + const auto error = messageOf([&] { + return bench.write(id, revisionOf(page), "", "1", "2"); + }); + requireEqual(error, std::string{"The watch was removed after the write"}); + requireEqual(state->value, 2); + }); + }}; + +const Scenario watchExecutors{"With an executor, a watch's operations run on the thread that owns its object, in the order asked (ADR-027, section 5)", + {"inspector"}, + [] { + Bench bench; + LoopThread owner; + std::vector values{1, 2, 3}; + std::atomic reads{0}; + std::atomic reader{}; + const auto scheduler = owner.loop.get_scheduler(); + using Accessor = std::function&()>; + const auto id = bench.registry->add( + inspect::makeWatch>("values", + "test.cpp:1", + Accessor{[&]() -> std::vector& { + ++reads; + reader = std::this_thread::get_id(); + return values; + }}, + std::shared_ptr{}, + scheduler, + inspect::NoMutator{})); + const auto children = [&](double revision) { + return inspect::onWatch(bench.registry, static_cast(id), [&, revision] { + return bench.children(id, "", revision); + }); + }; + then("the source and the whole operation run on the executor's thread, and a non-constant reference there is writable", [&] { + owner.start(); + const auto revision = await(inspect::onWatch(bench.registry, static_cast(id), [&] { + return bench.reset(id); + })); + const auto page = await(children(revision)); + requireEqual(nodesOf(page).size(), std::size_t{4}); + require(reader.load() == owner.thread.get_id()); + requireEqual(flagsOf(nodesOf(page)[1]), flag::writable); + const auto answer = await(inspect::onWatch(bench.registry, static_cast(id), [&] { + return bench.write(id, revisionOf(page), "/#0", "1", "10"); + })); + requireEqual(std::get<1>(answer), std::string{}); + requireEqual(values[0], 10); + }); + then("calls sent together are run one by one, in order: the second, with the same revision, is stale", [&] { + const auto revision = bench.reset(id); // nothing runs yet: the loop has not started + auto both = std::async(std::launch::async, [&] { + return networking::ex::sync_wait(networking::ex::when_all(children(revision), children(revision))); + }); + std::this_thread::sleep_for(20ms); + requireEqual(reads.load(), 0); // queued on the executor, not run where they were asked + owner.start(); + const auto [first, second] = *both.get(); + require(!resyncOf(first)); + requireEqual(nodesOf(first).size(), std::size_t{4}); + require(resyncOf(second)); + }); + then("an operation queued when the watch is removed is refused without calling the source", [&] { + const auto revision = bench.reset(id); + auto queued = std::async(std::launch::async, [&] { + return codeOf([&] { + return await(children(revision)); + }); + }); + std::this_thread::sleep_for(20ms); + bench.registry->remove(id); // nothing has started: it does not wait + owner.start(); + requireEqual(queued.get(), std::string{code::unknown}); + requireEqual(reads.load(), 0); + // And a call made afterwards is refused the same way, before it reaches the executor. + requireEqual(codeOf([&] { + return await(children(revision)); + }), + std::string{code::unknown}); + }); + }}; +} // namespace watch_write From 2f77837f28dd13493f3ca0fc25d35d8665be9d22 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:07:17 +0100 Subject: [PATCH 02/14] Inspector: unfold, refresh and edit the watches in the Watches panel (#682) inspector-watches.mjs holds the tree of a watch: the calls that change C++'s memory are sent one at a time, each with the revision the previous answer gave; a pass of differences stops as soon as an unfolding, a folding or a write waits, and the next pass finds the rest; a resynchronization reads the tree again from the root with the paths that were unfolded. The view edits a writable value in place (Enter writes, Escape cancels), highlights what the last pass changed, reads any position of a large container and the full text of a value that is cut. Every text of the application is set as text. The panel has the period of the other panels, and Pause stops the discovery and the passes together. bundles.json is regenerated by wf; the pinned release header is left as it is. --- js/developer/environment/bundles.json | 7 +- .../environment/inspector-registry.mjs | 2 +- .../environment/inspector-watches.mjs | 521 ++++++++++++++++++ js/developer/environment/inspector.mjs | 125 ++++- js/developer/tools/bundle-inputs.json | 1 + js/developer/webfront.project.json | 1 + .../specs/inspector-watches-specs.mjs | 444 +++++++++++++++ 7 files changed, 1082 insertions(+), 19 deletions(-) create mode 100644 js/developer/environment/inspector-watches.mjs create mode 100644 test/developer/specs/inspector-watches-specs.mjs diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 053c5807..a9048b04 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -25,8 +25,9 @@ "js/developer/environment/workspace.mjs": "e82ec4df21ffb2b112550e0212504aba05af4f924b5645c0712f40f8466257fc", "js/developer/environment/menu.mjs": "b4fe4c38e6b8cc6c1101df842e282ab85e6c6e029b2225738b9d27bc5efbc88d", "js/developer/environment/inspector-host.mjs": "bffcef61b8a5778f53adfea5096c5d5fa277868bbaa39e60142a3493210076fb", - "js/developer/environment/inspector.mjs": "47d631dbc0cd3e8a4ef3c2e4883b303804694f790e87dd06799257ec3828d1a8", - "js/developer/environment/inspector-registry.mjs": "431153f7d7eb562262361f2f8eb60d8690f42cdfbf5ed9586270270d9e2b6038", + "js/developer/environment/inspector.mjs": "99b150f6692dca0f4e45347354ab6bfaf6bf1cb9db6bbb97672f00a530f989fc", + "js/developer/environment/inspector-registry.mjs": "bdddca4f710567b9c5030a741ed96ca6b79ebbd080da6e0bb3336e91bb1f7b39", + "js/developer/environment/inspector-watches.mjs": "f5765dedf2b8b351e7febf4412e2a78a1fb8fde9d3659094b5fa62c49fc0f775", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", @@ -54,7 +55,7 @@ "js/developer/tools/archive.mjs": "da63bb9d796ddfd24ed945b15c53f66a0400eb177886fd4f1c8fd10cafb5a91b", "js/developer/tools/distribution.mjs": "43dfdccc912693db46fd095fd78ae79325abab672d99f89fd569914ef3499cad", "js/developer/scripts/build.mjs": "a6b64a8a75c9a30118e7f5c843a0feee89ee1372ccd19b7e468c816b23fd1367", - "js/developer/webfront.project.json": "1c6ac7dbb4282692f3f23d3e598d00735dfc99b72d7f1072f7438d29beceb7c1", + "js/developer/webfront.project.json": "f84a08ea4593814cde958bd980c79828e77207c4e482da626e07e6c87dd88b15", "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 index 8420ce00..a164a10e 100644 --- a/js/developer/environment/inspector-registry.mjs +++ b/js/developer/environment/inspector-registry.mjs @@ -356,7 +356,7 @@ export function keptPeriod(view) { } catch { return periods[0]; } } -function keepPeriod(view, period) { +export function keepPeriod(view, period) { try { view.localStorage?.setItem(periodKey, String(period)); } catch { /* a convenience only: the choice lasts as long as the page */ } } diff --git a/js/developer/environment/inspector-watches.mjs b/js/developer/environment/inspector-watches.mjs new file mode 100644 index 00000000..d74edd16 --- /dev/null +++ b/js/developer/environment/inspector-watches.mjs @@ -0,0 +1,521 @@ +// The trees of the watches (#682, ADR-027 sections 3 to 6): the content of an object or a container that the application +// declared with app.watch, unfolded level by level and refreshed while the interface is used. C++ keeps what it sent to this +// connection; the page reads pages of children (webfront.inspector.children), passes of differences (changes), full values by +// fragments (value), and writes the values the application made writable (write). +// +// One rule orders the calls: a call that changes C++'s memory of a watch (children, fold, write, the first page of a pass) +// is sent only after the answer of the previous one, since each answer carries the revision the next call must give. The +// tree therefore keeps a queue per watch. A pass never makes the user wait: an unfolding, a folding or a write goes first, +// and C++ interrupts the pass when it receives it. Reads of a full value change nothing and are sent at any time. +// +// Every text shown comes from the application: it is set as text, never as HTML. + +/** The bits of a node's flags (ADR-027, section 3). */ +export const flags = Object.freeze({writable: 1, truncated: 2, removed: 4, depthReached: 8, childrenChanged: 16}); + +export const functions = Object.freeze({ + children: 'webfront.inspector.children', changes: 'webfront.inspector.changes', value: 'webfront.inspector.value', + fold: 'webfront.inspector.fold', reset: 'webfront.inspector.reset', write: 'webfront.inspector.write', limits: 'webfront.inspector.limits', +}); + +/** The codes of the refusals, as C++ sends them and as this page gives them to a text it refuses itself. */ +export const codes = Object.freeze({ + unknown: 'webfront.inspector.unknown', stale: 'webfront.inspector.stale', tooLarge: 'webfront.inspector.tooLarge', + limit: 'webfront.inspector.limit', refused: 'webfront.inspector.refused', parse: 'webfront.inspector.parse', + readOnly: 'webfront.inspector.readOnly', unavailable: 'webfront.inspector.unavailable', +}); + +/** The children asked by a page of a list, and the nodes of a pass (ADR-027: 200 by default). */ +export const pageCount = 200; + +const whole = value => Number.isSafeInteger(value) && value >= 0; + +/** A node of a page as an object; throws when it is not one. */ +export function readNode(tuple) { + if (!Array.isArray(tuple) || tuple.length !== 6) throw new Error('The inspector answered a node that is not one'); + const [path, kind, label, value, children, bits] = tuple; + if (![path, kind, label, value].every(text => typeof text === 'string') || !whole(children) || !whole(bits)) + throw new Error('The inspector answered a node that is not one'); + return {path, kind, label, value, children, flags: bits}; +} + +/** A page of nodes: {nodes, next, revision, resync}; throws when it is not one. */ +export function readNodePage(answer) { + if (!Array.isArray(answer) || answer.length !== 4) throw new Error('The inspector answered a page that is not one'); + const [nodes, next, revision, resync] = answer; + if (!Array.isArray(nodes) || !whole(next) || !whole(revision) || typeof resync !== 'boolean') + throw new Error('The inspector answered a page that is not one'); + return {nodes: nodes.map(readNode), next, revision, resync}; +} + +/** What webfront.inspector.limits answers, as an object. */ +export function readLimits(answer) { + if (!Array.isArray(answer) || answer.length < 6 || !answer.every(whole)) throw new Error('The inspector answered limits that are not'); + const [maxWriteTextBytes, responseBudget, maxNodes, maxSnapshotBytes, maxPageCount, defaultPageCount] = answer; + return {maxWriteTextBytes, responseBudget, maxNodes, maxSnapshotBytes, maxPageCount, defaultPageCount}; +} + +export const parentOf = path => path.slice(0, path.lastIndexOf('/')); +const under = (path, parent) => path.startsWith(`${parent}/`); + +/** The bytes of a text once encoded as UTF-8, which is what the bounds count. */ +export const utf8Bytes = text => new TextEncoder().encode(text).length; + +/** + * The longest text a write may carry: what C++ accepts, and what this page's own codec lets a message hold once the other + * arguments of the request are at their largest (ADR-027, "Budget d'une requête"). `maxMessageBytes` is the codec's bound. + */ +export function writeBound(limits, maxMessageBytes = Infinity) { + const overhead = 8 + 26 + 9 + 9 + 1027 + 259 + 5; + return Math.max(0, Math.min(limits?.maxWriteTextBytes ?? 0, maxMessageBytes - overhead)); +} + +/** + * The tree of one watch for this connection. + * + * `nodes` maps a path to {node, positions (Map of position to path, the children loaded), changed (the pass that last + * changed it)}; `expanded` holds the paths the user unfolded, which survive a resynchronization. `onUpdate()` is called + * after each change of the model, `onGone()` once C++ says that the watch no longer exists. + */ +export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () => {}, onGone = () => {}, maxMessageBytes = Infinity}) { + const call = name => bridge.cppFunction(name); + const nodes = new Map(); + const expanded = new Set(); + let revision = 0, limits = null, gone = false, stopped = false, passes = 0, problem = null; + // The calls that change C++'s memory, sent one at a time. A pass in progress stops when one is waiting. + const waiting = []; + let running = null; + + const fail = error => { + if (error?.code === codes.unknown && !gone) { + gone = true; + waiting.length = 0; + onGone(); + } + throw error; + }; + const enqueue = work => new Promise((resolve, reject) => { + waiting.push({work, resolve, reject}); + drain(); + }); + function drain() { + if (running || !waiting.length) return; + const {work, resolve, reject} = waiting.shift(); + running = (async () => { + if (gone || stopped) throw Object.assign(new Error('The watch is gone'), {code: codes.unknown}); + return work(); + })().then( + // Free before the caller goes on: what it asks next, having awaited this answer, is not "busy" for it. + value => { running = null; resolve(value); }, + error => { running = null; reject(error); }, + ).finally(drain); + } + + const forget = path => { + for (const key of [...nodes.keys()]) if (under(key, path)) nodes.delete(key); + const kept = nodes.get(path); + if (kept) kept.positions = new Map(); + }; + const remove = path => { + forget(path); + nodes.delete(path); + if (path !== '') { + const parent = nodes.get(parentOf(path)); + if (parent) for (const [position, child] of parent.positions) if (child === path) parent.positions.delete(position); + } + }; + const keep = (node, changed = 0) => { + const kept = nodes.get(node.path); + if (kept) { + if (changed && (kept.node.value !== node.value || kept.node.children !== node.children || kept.node.kind !== node.kind)) kept.changed = changed; + kept.node = {...node, flags: node.flags & ~flags.childrenChanged}; + return kept; + } + const entry = {node: {...node, flags: node.flags & ~flags.childrenChanged}, positions: new Map(), changed}; + nodes.set(node.path, entry); + return entry; + }; + + /** C++ emptied its memory: everything shown is thrown away, and read again from the root with the paths that were unfolded. */ + async function resynchronize(answered) { + revision = answered; + nodes.clear(); + await list('', 0); + } + + /** One page of the children of `path` from `start`, then the unfolded children that came back. Runs inside the queue. */ + async function list(path, start) { + let page; + try { page = readNodePage(await call(functions.children)(watch, path, revision, start, count)); } + catch (error) { + // A node that is no longer in the memory, or too deep, stays folded; the tree goes on. + if (error?.code === codes.unknown && path !== '') { expanded.delete(path); return; } + if (error?.code === codes.limit) { problem = error.message; expanded.delete(path); return; } + return fail(error); + } + if (page.resync) return resynchronize(page.revision); + revision = page.revision; + const [parent, ...children] = page.nodes; + if (!parent) return; + if (parent.flags & flags.removed) { remove(parent.path); expanded.delete(parent.path); return; } + const entry = keep(parent); + if (parent.flags & flags.childrenChanged) { + // The list changed while it was read: it starts again from its first position. + forget(path); + return list(path, 0); + } + if (start === 0) for (const position of [...entry.positions.keys()]) if (position >= parent.children) remove(entry.positions.get(position)); + children.forEach((child, index) => { + const position = start + index; + const previous = entry.positions.get(position); + if (previous !== undefined && previous !== child.path && ![...entry.positions.values()].includes(child.path)) remove(previous); + entry.positions.set(position, child.path); + keep(child); + }); + entry.next = page.next; + onUpdate(); + for (const child of children) + if (expanded.has(child.path) && nodes.get(child.path)?.positions.size === 0 && child.children > 0 && !(child.flags & flags.depthReached)) + await list(child.path, 0); + } + + /** One pass of differences. It stops as soon as another call waits: C++ interrupts it then, and the next pass finds the rest. */ + async function pass() { + const stamp = ++passes; + let cursor = 0; + do { + const page = readNodePage(await call(functions.changes)(watch, revision, cursor, count).catch(fail)); + if (page.resync) return resynchronize(page.revision); + revision = page.revision; + const reload = []; + for (const node of page.nodes) { + if (node.flags & flags.removed) { remove(node.path); continue; } + if (!nodes.has(node.path)) continue; + const entry = keep(node, stamp); + if (node.flags & flags.childrenChanged) { + entry.changed = stamp; + forget(node.path); + if (expanded.has(node.path)) reload.push(node.path); + } + } + cursor = page.next; + if (page.nodes.length) onUpdate(); + // Reading a list again changes the memory: it interrupts the pass, whose remaining differences the next one finds. + for (const path of reload) waiting.unshift({work: () => list(path, 0), resolve() {}, reject() {}}); + } while (cursor !== 0 && !waiting.length && !stopped); + } + + const tree = { + watch, + nodes, + expanded, + get revision() { return revision; }, + get limits() { return limits; }, + get gone() { return gone; }, + /** The pass that ran last: a node whose `changed` equals it changed in that pass. */ + get pass() { return passes; }, + /** Why the last unfolding was refused (memory full, node too deep), until the next one succeeds. */ + get problem() { return problem; }, + /** Whether a call is running or waiting. */ + get busy() { return running !== null || waiting.length > 0; }, + /** Resolves once every call asked so far is answered. */ + async settled() { while (running || waiting.length) await (running ?? Promise.resolve()).catch(() => {}); }, + + /** Opens the watch: C++'s memory of it is emptied, then the root and its first children are read. */ + open() { + return enqueue(async () => { + limits ??= readLimits(await call(functions.limits)()); + revision = await call(functions.reset)(watch).catch(fail); + nodes.clear(); + expanded.add(''); + await list('', 0); + onUpdate(); + }); + }, + /** Unfolds a node: its first page of children. */ + expand(path) { + expanded.add(path); + problem = null; + return enqueue(async () => { await list(path, 0); onUpdate(); }); + }, + /** Reads the children of `path` from `start`: the next page of a list, or a window anywhere in a large container. */ + load(path, start) { + return enqueue(async () => { await list(path, start); onUpdate(); }); + }, + /** Folds a node: C++ forgets its descendants, and so does the page. */ + collapse(path) { + expanded.delete(path); + for (const key of [...expanded]) if (under(key, path)) expanded.delete(key); + return enqueue(async () => { + if (!nodes.has(path)) return; + const page = readNodePage(await call(functions.fold)(watch, path, revision).catch(fail)); + if (page.resync) await resynchronize(page.revision); + else { + revision = page.revision; + forget(path); + } + onUpdate(); + }); + }, + /** A pass of differences, unless a call is already running or waiting: the period only reads when nothing else does. */ + refresh() { + if (tree.busy || gone || stopped || !nodes.size) return Promise.resolve(false); + return enqueue(async () => { await pass(); onUpdate(); return true; }); + }, + /** + * Writes `text` into the node. Resolves with {code, message}: an empty code when the value was written, else why it + * was not. A text longer than the bound is refused here, without a call. After a `stale` refusal the node is read again. + */ + write(path, text) { + const bound = writeBound(limits, maxMessageBytes); + if (utf8Bytes(text) > bound) + return Promise.resolve({code: codes.tooLarge, message: `The text is longer than ${bound} bytes`}); + return enqueue(async () => { + const entry = nodes.get(path); + if (!entry) return {code: codes.unknown, message: 'The node is no longer shown'}; + let answer; + try { answer = await call(functions.write)(watch, revision, path, entry.node.value, text); } + catch (error) { + if (error?.code === codes.unknown) return fail(error); + // Rejected before any effect: nothing changed, the revision included. A stale revision is cured by reading again. + if (error?.code === codes.stale) await list(path, 0); + onUpdate(); + return {code: error?.code ?? 'webfront.error', message: error?.message ?? String(error)}; + } + const [answered, code, message] = answer; + revision = answered; + // Written or not, what the node shows now is read again: the parent of a leaf gives it with its siblings' state. + await list(path, 0); + onUpdate(); + return {code, message}; + }); + }, + /** + * The whole value of a node, read by fragments of one snapshot: {text, total, capped}. A reading that another one + * replaced starts again, a few times at most. + */ + async fullValue(path, {attempts = 3} = {}) { + for (let attempt = 0; ; ++attempt) { + try { + let [part, total, next, capped, snapshot] = await call(functions.value)(watch, path, 0, 0); + let text = part; + while (next !== 0) { + [part, total, next, capped] = await call(functions.value)(watch, path, snapshot, next); + text += part; + } + return {text, total, capped}; + } catch (error) { + if (error?.code !== codes.stale || attempt + 1 >= attempts) throw error; + } + } + }, + /** Stops the tree: nothing more is sent. C++ frees its memory when the connection closes, or at the next open. */ + stop() { + stopped = true; + waiting.length = 0; + }, + }; + return tree; +} + +// --- Rendering ------------------------------------------------------------------------------------------------- + +export const watchTreeStyles = ` +ul.watches li{display:block} +ul.watches .head{display:grid;grid-template-columns:auto 1fr auto;gap:2px 12px;align-items:baseline} +ul.watches .head .location{grid-column:2/4} +ul.watches button.toggle,ul.tree button.toggle{width:24px;min-height:24px;padding:0;border:0;background:none;color:#a9b3c4;font:inherit;cursor:pointer} +ul.watches button.toggle:focus-visible,ul.tree button:focus-visible,ul.tree input:focus-visible{outline:2px solid #d7fa85;outline-offset:1px} +ul.tree{list-style:none;margin:4px 0 0;padding:0 0 0 16px;font:12px ui-monospace,monospace} +ul.tree li{padding:1px 0;border:0} +ul.tree .row{display:flex;gap:6px;align-items:baseline;min-height:24px} +ul.tree .spacer{display:inline-block;width:24px} +ul.tree .label{color:#8fd0ff} +ul.tree .kind{color:#a9b3c4;justify-self:auto} +ul.tree .value{overflow-wrap:anywhere;white-space:pre-wrap} +ul.tree .value.writable{cursor:text;border-bottom:1px dotted #46536a} +ul.tree .changed>.row .value,ul.tree .changed>.row .kind{background:#4a3d12} +ul.tree .note{color:#ffbd2e} +ul.tree input{min-width:12ch;border:1px solid #46536a;border-radius:3px;background:#141821;color:inherit;font:inherit} +ul.tree button.more,ul.tree button.full{min-height:24px;padding:0 6px;border:1px solid #46536a;border-radius:3px;background:#2f3a50;color:inherit;font:inherit;cursor:pointer} +ul.tree pre.full{max-height:240px;overflow:auto;margin:2px 0;padding:4px;background:#0f131b;white-space:pre-wrap;overflow-wrap:anywhere}`; + +/** The most characters of a full value that the page shows; the rest is told by its size. */ +export const shownValueCharacters = 64 * 1024; + +const reasons = { + [codes.stale]: 'The value changed since it was shown: it was read again.', + [codes.readOnly]: 'This value is not writable.', + [codes.limit]: 'The inspector\'s memory is full, or the node is too deep: fold some nodes.', +}; + +/** Why a write was not applied, for the user. */ +export const writeFailure = ({code, message}) => message || reasons[code] || code; + +/** + * Shows a tree in `list` (a `ul`), and wires its controls: unfolding and folding, the next page of a list, a position in a + * large container, the edition in place of a writable value (Enter writes, Escape cancels), and the full value of one that + * is cut. `render()` draws the model again; it keeps the focus and an edition in progress. + */ +export function createTreeView({tree, list, view = globalThis}) { + const page = list.ownerDocument; + const notes = new Map(); // path, why the last write was not applied + const full = new Map(); // path, the full value read + let editing = null; // {path, text}: kept across the renderings that a refresh causes + list.className = 'tree'; + list.setAttribute('role', 'tree'); + + const element = (tag, className, text) => { + const made = page.createElement(tag); + if (className) made.className = className; + if (text !== undefined) made.textContent = text; + return made; + }; + const button = (className, text, label, act) => { + const made = element('button', className, text); + made.type = 'button'; + made.setAttribute('aria-label', label); + made.addEventListener('click', act); + return made; + }; + const report = work => Promise.resolve(work).catch(() => {}).finally(render); + + function edit(path) { + const entry = tree.nodes.get(path); + if (!entry || !(entry.node.flags & flags.writable)) return; + editing = {path, text: entry.node.value}; + notes.delete(path); + render(); + list.querySelector('input.edit')?.select(); + } + async function commit() { + const {path, text} = editing; + editing = null; + const answer = await tree.write(path, text).catch(error => ({code: error?.code ?? 'webfront.error', message: error?.message ?? String(error)})); + if (answer.code) notes.set(path, writeFailure(answer)); + render(); + } + + function row(path, depth) { + const entry = tree.nodes.get(path); + const {node} = entry; + const item = element('li'); + item.setAttribute('role', 'treeitem'); + item.dataset.path = path; + if (entry.changed && entry.changed === tree.pass) item.classList.add('changed'); + const line = element('div', 'row'); + const unfolds = node.children > 0 && !(node.flags & flags.depthReached); + const open = unfolds && tree.expanded.has(path); + if (unfolds) { + item.setAttribute('aria-expanded', String(open)); + line.append(button('toggle', open ? '▾' : '▸', `${open ? 'Fold' : 'Unfold'} ${node.label}`, + () => report(open ? tree.collapse(path) : tree.expand(path)))); + } else line.append(element('span', 'spacer')); + line.append(element('span', 'label', node.label), element('span', 'kind', node.children > 0 ? `${node.kind} [${node.children}]` : node.kind)); + if (editing?.path === path) { + const input = element('input', 'edit'); + input.value = editing.text; + input.setAttribute('aria-label', `New value of ${node.label}`); + input.addEventListener('input', () => { editing.text = input.value; }); + input.addEventListener('keydown', event => { + if (event.key === 'Enter') { event.preventDefault(); commit(); } + else if (event.key === 'Escape') { event.preventDefault(); editing = null; render(); } + }); + line.append(input); + } else if (node.value !== '' || node.children === 0) { + const value = element('span', 'value', node.value); + if (node.flags & flags.writable) { + value.classList.add('writable'); + value.tabIndex = 0; + value.setAttribute('role', 'button'); + value.setAttribute('aria-label', `Edit ${node.label}: ${node.value}`); + value.addEventListener('click', () => edit(path)); + value.addEventListener('keydown', event => { if (event.key === 'Enter' || event.key === 'F2') { event.preventDefault(); edit(path); } }); + } + line.append(value); + } + if (node.flags & flags.truncated) + line.append(button('full', 'Full value', `Read the full value of ${node.label}`, async () => { + try { full.set(path, await tree.fullValue(path)); } + catch (error) { notes.set(path, `The full value cannot be read: ${error?.message ?? error}`); } + render(); + })); + if (node.flags & flags.depthReached) line.append(element('span', 'note', 'too deep to be unfolded')); + if (notes.has(path)) line.append(element('span', 'note', notes.get(path))); + item.append(line); + if (full.has(path)) { + const {text, total, capped} = full.get(path); + const shown = text.length > shownValueCharacters ? `${text.slice(0, shownValueCharacters)}…` : text; + item.append(element('pre', 'full', shown), + element('span', 'note', `${total} bytes${capped ? ', cut at the inspector\'s limit' : ''}`)); + } + if (open) { + const group = element('ul', 'tree'); + group.setAttribute('role', 'group'); + let expected = 0; + const gap = (from, to) => { + const more = element('li'); + more.append(button('more', from === to - 1 ? `[${from}] not loaded` : `[${from}] to [${to - 1}] not loaded`, + `Load the children of ${node.label} from ${from}`, () => report(tree.load(path, from)))); + more.dataset.from = String(from); + return more; + }; + for (const [position, child] of [...entry.positions].sort((a, b) => a[0] - b[0])) { + if (position > expected) group.append(gap(expected, position)); + if (tree.nodes.has(child)) group.append(row(child, depth + 1)); + expected = position + 1; + } + if (expected < node.children) { + group.append(gap(expected, node.children)); + // A large container: any position is read directly. + if (node.children > tree.limits?.defaultPageCount) { + const jump = element('li'); + const input = element('input', 'position'); + input.type = 'number'; + input.min = '0'; + input.max = String(node.children - 1); + input.placeholder = 'position'; + input.setAttribute('aria-label', `Go to a position in ${node.label}`); + input.addEventListener('keydown', event => { + const position = Number(input.value); + if (event.key === 'Enter' && Number.isSafeInteger(position) && position >= 0 && position < node.children) + report(tree.load(path, position)); + }); + jump.append(input); + group.append(jump); + } + } + item.append(group); + } + return item; + } + + function render() { + const focused = page.activeElement; + const within = focused && list.contains(focused); + const where = within ? {path: focused.closest('li')?.dataset.path, name: focused.className.split(' ')[0]} : null; + for (const path of [...notes.keys()]) if (!tree.nodes.has(path)) notes.delete(path); + for (const path of [...full.keys()]) if (!tree.nodes.has(path)) full.delete(path); + if (editing && !tree.nodes.has(editing.path)) editing = null; + list.replaceChildren(...(tree.nodes.has('') ? [row('', 0)] : [])); + if (tree.problem) list.append(element('li', 'note', tree.problem)); + if (where?.path !== undefined) { + const item = [...list.querySelectorAll('li')].find(candidate => candidate.dataset.path === where.path); + const again = item?.querySelector(`:scope > .row .${where.name || 'toggle'}`); + again?.focus(); + if (again?.tagName === 'INPUT' && editing) again.setSelectionRange(again.value.length, again.value.length); + } + // The positions that are not loaded are read when they come into view. + if (typeof view.IntersectionObserver === 'function') { + observer?.disconnect(); + observer = new view.IntersectionObserver(entries => { + for (const entry of entries) + if (entry.isIntersecting && !tree.busy) entry.target.click(); + }); + for (const more of list.querySelectorAll('button.more')) observer.observe(more); + } + } + let observer = null; + + return {render, edit, get editing() { return editing; }, stop() { observer?.disconnect(); }}; +} diff --git a/js/developer/environment/inspector.mjs b/js/developer/environment/inspector.mjs index 3d16167f..a25ae391 100644 --- a/js/developer/environment/inspector.mjs +++ b/js/developer/environment/inspector.mjs @@ -1,10 +1,12 @@ // 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"). The -// panels of the functions and of the browsers are in inspector-registry.mjs (#681, section 7). +// watches lists them by webfront.inspector.watches and follows the registrations and removals (section 3, "Découverte"); the +// tree of each is in inspector-watches.mjs (#682). 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'; +import {showFunctionsPanel, showBrowsersPanel, registryStyles, periods, formatPeriod, keptPeriod, keepPeriod, createPoller} from './inspector-registry.mjs'; +import {createWatchTree, createTreeView, watchTreeStyles} from './inspector-watches.mjs'; // --- Bridge ---------------------------------------------------------------------------------------------------- @@ -202,8 +204,11 @@ const placeholders = { 'typescript.bridge': 'The state of the bridge in the page comes with the next versions of the environment.', }; -/** Renders the list of the watches in `list`, one item per watch, kept by id so that a removal removes its item. */ -export function renderWatches(list, watches) { +/** + * Renders the list of the watches in `list`, one item per watch, kept by id so that a removal removes its item. With + * `onToggle(watch, item)`, each item has a button that unfolds the tree of its watch. + */ +export function renderWatches(list, watches, {onToggle = null} = {}) { const page = list.ownerDocument; const items = new Map([...list.children].map(item => [Number(item.dataset.watch), item])); const ids = new Set(watches.map(watch => watch.id)); @@ -218,8 +223,21 @@ export function renderWatches(list, watches) { element.textContent = text; return element; }; - item.append(cell('name', watch.name), cell('kind', watch.kind), cell('location', watch.location)); - if (watch.writable) item.append(cell('writable', 'writable')); + const head = page.createElement('div'); + head.className = 'head'; + if (onToggle) { + const toggle = page.createElement('button'); + toggle.type = 'button'; + toggle.className = 'toggle'; + toggle.textContent = '▸'; + toggle.setAttribute('aria-expanded', 'false'); + toggle.setAttribute('aria-label', `Show the content of ${watch.name}`); + toggle.addEventListener('click', () => onToggle(watch, item)); + head.append(toggle); + } + head.append(cell('name', watch.name), cell('kind', watch.kind), cell('location', watch.location)); + if (watch.writable) head.append(cell('writable', 'writable')); + item.append(head); list.append(item); } } @@ -254,7 +272,7 @@ export async function main(view = window) { page.title = `WebFront inspector: ${panelTitle(id)}`; reloadWhenRestored(view); const style = page.createElement('style'); - style.textContent = styles + registryStyles; + style.textContent = styles + registryStyles + watchTreeStyles; page.head.append(style); const header = page.createElement('header'); const heading = page.createElement('h1'); @@ -316,30 +334,107 @@ export async function main(view = window) { pause.className = 'pause'; pause.textContent = 'Pause'; header.insertBefore(pause, header.children[1] ?? null); + 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); + header.insertBefore(periodLabel, pause); const describe = watches => { status.classList.remove('error'); status.textContent = watches.length ? '' : 'The application declares no watch (app.watch).'; }; + const denied = error => error?.code === 'webfront.inspector.denied' + ? 'The inspectors answer only a view of the application: this page is not admitted.' : null; + + // The trees that are unfolded, by the identifier of their watch. Each is read again at the period, unless paused. + const trees = new Map(); + const close = id => { + const shown = trees.get(id); + if (!shown) return; + shown.tree.stop(); + shown.view.stop(); + shown.element.remove(); + trees.delete(id); + }; + const toggle = async (watch, item) => { + const button = item.querySelector('button.toggle'); + if (trees.has(watch.id)) { + close(watch.id); + button.textContent = '▸'; + button.setAttribute('aria-expanded', 'false'); + return; + } + const element = page.createElement('ul'); + item.append(element); + let shown = null; + const tree = createWatchTree({ + bridge, + watch: watch.id, + maxMessageBytes: bridge.maxMessageBytes ?? Infinity, + onUpdate: () => shown?.render(), + // A watch that C++ no longer knows leaves the list at once, without waiting for the next discovery. + onGone: () => { close(watch.id); discovery.forget(watch.id); }, + }); + shown = createTreeView({tree, list: element, view}); + trees.set(watch.id, {tree, view: shown, element}); + button.textContent = '▾'; + button.setAttribute('aria-expanded', 'true'); + try { await tree.open(); } + catch (error) { + if (trees.has(watch.id)) { + status.classList.add('error'); + status.textContent = denied(error) ?? `The watch cannot be read: ${error?.message ?? error}`; + } + } + }; const discovery = createWatchDiscovery({ bridge, - onChange: ({watches}) => renderWatches(list, watches), + onChange: ({watches, removed}) => { + for (const id of removed) close(id); + renderWatches(list, watches, {onToggle: toggle}); + }, // Every read that succeeds says so, also after an error and when nothing changed. onRead: describe, onError: error => { status.classList.add('error'); - status.textContent = error?.code === 'webfront.inspector.denied' - ? 'The inspectors answer only a view of the application: this page is not admitted.' - : `The watches cannot be read: ${error?.message ?? error}`; + status.textContent = denied(error) ?? `The watches cannot be read: ${error?.message ?? error}`; }, timers: view, }); + // One pass of differences per tree and per period; a tree that is busy (the user unfolds, writes) is skipped this time. + const refresher = createPoller({ + read: async () => { await Promise.all([...trees.values()].map(({tree}) => tree.refresh().catch(() => false))); return true; }, + onData: () => {}, + period: chosen, + timers: view, + }); + period.addEventListener('change', () => { + const value = Number(period.value); + keepPeriod(view, value); + refresher.setPeriod(value); + }); pause.addEventListener('click', () => { - if (discovery.paused) discovery.resume(); else discovery.pause(); + if (discovery.paused) { discovery.resume(); refresher.resume(); } + else { discovery.pause(); refresher.pause(); } pause.textContent = discovery.paused ? 'Resume' : 'Pause'; }); - view.addEventListener('pagehide', () => discovery.stop()); + view.addEventListener('pagehide', () => { + discovery.stop(); + refresher.stop(); + for (const id of [...trees.keys()]) close(id); + }); await discovery.start(); - return {bridge, discovery, list}; + refresher.start(); + return {bridge, discovery, list, trees, refresher, toggle}; } /** diff --git a/js/developer/tools/bundle-inputs.json b/js/developer/tools/bundle-inputs.json index cdd1b0f4..1291ef22 100644 --- a/js/developer/tools/bundle-inputs.json +++ b/js/developer/tools/bundle-inputs.json @@ -27,6 +27,7 @@ "js/developer/environment/inspector-host.mjs", "js/developer/environment/inspector.mjs", "js/developer/environment/inspector-registry.mjs", + "js/developer/environment/inspector-watches.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 d88082ec..7c7a39cc 100644 --- a/js/developer/webfront.project.json +++ b/js/developer/webfront.project.json @@ -34,6 +34,7 @@ "test/developer/specs/workspace-specs.mjs", "test/developer/specs/inspector-specs.mjs", "test/developer/specs/inspector-registry-specs.mjs", + "test/developer/specs/inspector-watches-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-watches-specs.mjs b/test/developer/specs/inspector-watches-specs.mjs new file mode 100644 index 00000000..d7882537 --- /dev/null +++ b/test/developer/specs/inspector-watches-specs.mjs @@ -0,0 +1,444 @@ +// Specs of the trees of the watches (#682, ADR-027 sections 3 to 6): the nodes and the pages, the order of the calls that +// change C++'s memory, the passes of differences and what interrupts them, the resynchronization, writes and full values, +// and the view that shows a tree. A fake of the C++ side answers here; the real one is read in a browser by +// test/web/suite/specs/inspector-specs.mjs. +import {flags, functions, codes, readNode, readNodePage, readLimits, writeBound, utf8Bytes, parentOf, createWatchTree, createTreeView, + writeFailure} from '../../../js/developer/environment/inspector-watches.mjs'; + +const node = (path, kind, label, value, children = 0, bits = 0) => [path, kind, label, value, children, bits]; +const refusal = (code, message = code) => Object.assign(new Error(message), {code}); +const limits = [4096, 32768, 10000, 16 * 1024 * 1024, 1000, 200]; + +/** + * A fake of C++ for one watch: a vector of texts, with a memory under a revision, as WatchMemory.hpp keeps one. Its calls + * are recorded; `hold(name)` makes the next call of that function wait until the function it returns is called. + */ +function fakeWatch(values, {writable = true, pageSize = Infinity} = {}) { + const calls = []; + const held = new Map(); + let revision = 1, loaded = new Set(), pass = null, snapshot = 0; + const memory = new Map(); + const bits = writable ? flags.writable : 0; + const root = () => node('', 'sequence', 'values', '', values.length); + const child = index => node(`/#${index}`, 'string', `[${index}]`, values[index], 0, bits); + const resync = () => { loaded = new Set(); memory.clear(); pass = null; return [[], 0, ++revision, true]; }; + const answers = { + [functions.limits]: () => limits, + [functions.reset]: () => { loaded = new Set(); memory.clear(); pass = null; return ++revision; }, + [functions.children]: (watch, path, asked, start, count) => { + if (asked !== revision) return resync(); + pass = null; + if (path !== '') { + const index = Number(path.slice(2)); + if (!loaded.has(index)) throw refusal(codes.unknown); + if (index >= values.length) return [[node(path, 'string', `[${index}]`, '', 0, flags.removed)], 0, ++revision, false]; + memory.set(index, values[index]); + return [[child(index)], 0, ++revision, false]; + } + const served = []; + for (let index = start; index < values.length && served.length < Math.min(count, pageSize); ++index) { + loaded.add(index); + memory.set(index, values[index]); + served.push(child(index)); + } + const after = start + served.length; + return [[root(), ...served], after < values.length ? after : 0, ++revision, false]; + }, + [functions.changes]: (watch, asked, cursor, count) => { + if (asked !== revision) return resync(); + if (cursor === 0) { + pass = [...loaded].filter(index => index < values.length && memory.get(index) !== values[index]).map(index => { + memory.set(index, values[index]); + return child(index); + }); + ++revision; + } else if (!pass) return resync(); + const served = pass.splice(0, Math.min(count, pageSize)); + const next = pass.length ? cursor + served.length : 0; + if (!next) pass = null; + return [served, next, revision, false]; + }, + [functions.fold]: (watch, path, asked) => { + if (asked !== revision) return resync(); + pass = null; + if (path === '') { loaded = new Set(); memory.clear(); } + return [[], 0, ++revision, false]; + }, + [functions.write]: (watch, asked, path, expected, text) => { + if (asked !== revision) throw refusal(codes.stale); + pass = null; + const index = Number(path.slice(2)); + if (values[index] !== expected) return [++revision, codes.stale, '']; + if (text === 'refuse') return [++revision, codes.refused, 'not this value']; + values[index] = text; + memory.set(index, text); + return [++revision, '', '']; + }, + [functions.value]: (watch, path, asked, offset) => { + const text = values[Number(path.slice(2))].repeat(3); + if (asked === 0) return [text.slice(0, 4), text.length, text.length > 4 ? 4 : 0, false, ++snapshot]; + if (asked !== snapshot) throw refusal(codes.stale); + const end = offset + 4; + return [text.slice(offset, end), text.length, end < text.length ? end : 0, false, snapshot]; + }, + }; + return { + calls, + answers, + get revision() { return revision; }, + get passing() { return pass !== null; }, + /** Makes the next call of `name` wait; the returned function lets it go on. */ + hold(name) { + let release; + held.set(name, new Promise(resolve => { release = resolve; })); + return release; + }, + cppFunction: name => async (...args) => { + calls.push([name, ...args]); + const waiting = held.get(name); + if (waiting) { + held.delete(name); + await waiting; + } + return answers[name](...args); + }, + }; +} + +const names = bridge => bridge.calls.map(([name]) => name.replace('webfront.inspector.', '')); +const valuesOf = tree => [...tree.nodes.values()].map(({node: shown}) => shown.value); + +describe('The nodes and pages of a watch', () => { + it('are read from the tuples C++ answers', () => { + expect(readNode(node('/#1', 'integer', '[1]', '42', 0, 3))).toEqual({path: '/#1', kind: 'integer', label: '[1]', value: '42', children: 0, flags: 3}); + expect(readNodePage([[node('', 'sequence', 'grid', '', 2)], 0, 7, false])) + .toEqual({nodes: [{path: '', kind: 'sequence', label: 'grid', value: '', children: 2, flags: 0}], next: 0, revision: 7, resync: false}); + expect(readLimits(limits).maxWriteTextBytes).toBe(4096); + }); + + it('are refused when they are not what C++ sends', () => { + for (const bad of [null, [], ['', 'k', 'l', 'v', 0], ['', 'k', 'l', 1, 0, 0], ['', 'k', 'l', 'v', -1, 0], ['', 'k', 'l', 'v', 0.5, 0]]) + expect(() => readNode(bad)).toThrowError(/node/); + for (const bad of [null, [[], 0, 1], [{}, 0, 1, false], [[], 0, 1, 0], [[], -1, 1, false]]) expect(() => readNodePage(bad)).toThrowError(/page/); + expect(() => readLimits([1, 2])).toThrowError(/limits/); + }); + + it('have paths whose parent is the path without its last segment', () => { + expect(parentOf('/#1/.2/kab')).toBe('/#1/.2'); + expect(parentOf('/#1')).toBe(''); + }); + + it('bound the text of a write in UTF-8 bytes, by C++ and by the page\'s own codec', () => { + expect(utf8Bytes('é€')).toBe(5); + expect(writeBound(readLimits(limits))).toBe(4096); + expect(writeBound(readLimits(limits), 2000)).toBe(2000 - 1343); + expect(writeBound(null)).toBe(0); + }); +}); + +describe('The tree of a watch', () => { + it('opens on an empty memory: reset, then the root and its children', async () => { + const bridge = fakeWatch(['a', 'b']); + let updates = 0; + const tree = createWatchTree({bridge, watch: 7, onUpdate: () => ++updates}); + await tree.open(); + expect(names(bridge)).toEqual(['limits', 'reset', 'children']); + expect(bridge.calls[2]).toEqual([functions.children, 7, '', 2, 0, 200]); + expect([...tree.nodes.keys()]).toEqual(['', '/#0', '/#1']); + expect(tree.nodes.get('').positions).toEqual(new Map([[0, '/#0'], [1, '/#1']])); + expect(tree.revision).toBe(bridge.revision); + expect(tree.expanded.has('')).toBeTrue(); + expect(updates).toBeGreaterThan(0); + }); + + it('sends a call that changes the memory only after the answer of the previous one, with its revision', async () => { + const bridge = fakeWatch(['a', 'b', 'c']); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + const release = bridge.hold(functions.fold); + const before = bridge.calls.length; + const folded = tree.collapse(''); + const unfolded = tree.expand(''); + await Promise.resolve(); + await Promise.resolve(); + expect(bridge.calls.length).toBe(before + 1); // the unfolding waits for the answer of the folding + release(); + await Promise.all([folded, unfolded]); + const [, , , asked] = bridge.calls.at(-1); + expect(names(bridge).slice(before)).toEqual(['fold', 'children']); + expect(asked).toBe(tree.revision - 1); // the revision the folding answered + expect(tree.nodes.size).toBe(4); + }); + + it('reads the next page of a list, and any window of a large container', async () => { + const bridge = fakeWatch(Array.from({length: 10}, (unused, index) => `v${index}`), {pageSize: 4}); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + expect(tree.nodes.get('').next).toBe(4); + await tree.load('', 8); + expect([...tree.nodes.get('').positions.keys()]).toEqual([0, 1, 2, 3, 8, 9]); + expect(tree.nodes.get('/#9').node.value).toBe('v9'); + }); + + it('reads a pass of differences, and marks what it changed', async () => { + const values = ['a', 'b', 'c']; + const bridge = fakeWatch(values); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + values[1] = 'B'; + expect(await tree.refresh()).toBeTrue(); + expect(tree.nodes.get('/#1').node.value).toBe('B'); + expect(tree.nodes.get('/#1').changed).toBe(tree.pass); + expect(tree.nodes.get('/#0').changed).toBe(0); + await tree.refresh(); + expect(tree.nodes.get('/#1').changed).not.toBe(tree.pass); // nothing changed in the last pass + }); + + it('does not make an unfolding wait for the end of a pass: the pass stops, and the next one finds the rest', async () => { + const values = Array.from({length: 6}, (unused, index) => `v${index}`); + const bridge = fakeWatch(values, {pageSize: 2}); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + await tree.load('', 2); + await tree.load('', 4); + for (let index = 0; index < 6; ++index) values[index] = `w${index}`; + const release = bridge.hold(functions.changes); + const before = bridge.calls.length; + const passing = tree.refresh(); + await Promise.resolve(); + const reading = tree.load('', 0); // asked while the first page of the pass is awaited + release(); + await Promise.all([passing, reading]); + // One page of the pass, then the unfolding: the second page of the pass was never asked. + expect(names(bridge).slice(before)).toEqual(['changes', 'children']); + expect(valuesOf(tree).slice(1)).toEqual(['w0', 'w1', 'v2', 'v3', 'v4', 'v5']); + expect(bridge.passing).toBeFalse(); + // The period reads only when nothing else does. + const held = bridge.hold(functions.children); + const busy = tree.load('', 2); + expect(await tree.refresh()).toBeFalse(); + held(); + await busy; + }); + + it('reads everything again from the root after a resynchronization, with the paths that were unfolded', async () => { + const bridge = fakeWatch(['a', 'b']); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + bridge.answers[functions.reset](); // C++'s memory moved without this page: its revision is stale + const before = bridge.calls.length; + await tree.refresh(); + expect(names(bridge).slice(before)).toEqual(['changes', 'children']); + expect([...tree.nodes.keys()]).toEqual(['', '/#0', '/#1']); + expect(tree.revision).toBe(bridge.revision); + expect(await tree.refresh()).toBeTrue(); + expect(names(bridge).at(-1)).toBe('changes'); + }); + + it('reads a list again when a pass tells that its children changed', async () => { + const values = ['a', 'b']; + const bridge = fakeWatch(values); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + values.push('c'); + const changes = bridge.answers[functions.changes]; + bridge.answers[functions.changes] = (...args) => { + bridge.answers[functions.changes] = changes; + const [, asked] = args; + const page = changes(...args); + return asked === page[2] ? page : [[node('', 'sequence', 'values', '', 3, flags.childrenChanged)], 0, page[2], false]; + }; + await tree.refresh(); + await tree.settled(); + expect(names(bridge).slice(-2)).toEqual(['changes', 'children']); + expect([...tree.nodes.keys()]).toEqual(['', '/#0', '/#1', '/#2']); + expect(tree.nodes.get('').changed).toBe(tree.pass); + }); + + it('folds a node: the page forgets what C++ forgets', async () => { + const bridge = fakeWatch(['a', 'b']); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + await tree.collapse(''); + expect([...tree.nodes.keys()]).toEqual(['']); + expect(tree.expanded.has('')).toBeFalse(); + expect(tree.revision).toBe(bridge.revision); + }); + + it('writes a value with what it shows, and adopts the revision of the answer', async () => { + const values = ['a', 'b']; + const bridge = fakeWatch(values); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + expect(await tree.write('/#1', 'B')).toEqual({code: '', message: ''}); + expect(bridge.calls.find(([name]) => name === functions.write).slice(3)).toEqual(['/#1', 'b', 'B']); + expect(values).toEqual(['a', 'B']); + expect(tree.nodes.get('/#1').node.value).toBe('B'); + expect(tree.revision).toBe(bridge.revision); + expect(await tree.write('/#1', 'refuse')).toEqual({code: codes.refused, message: 'not this value'}); + expect(tree.revision).toBe(bridge.revision); + }); + + it('reads a node again after a stale refusal, so that the write is offered on what the object shows', async () => { + const values = ['a', 'b']; + const bridge = fakeWatch(values); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + values[1] = 'changed'; + const answer = await tree.write('/#1', 'B'); + expect(answer.code).toBe(codes.stale); + expect(values[1]).toBe('changed'); + expect(tree.nodes.get('/#1').node.value).toBe('changed'); + expect(names(bridge).slice(-2)).toEqual(['write', 'children']); + expect((await tree.write('/#1', 'B')).code).toBe(''); + }); + + it('refuses in the page, without a call, a text longer than the bound', async () => { + const bridge = fakeWatch(['a']); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + const before = bridge.calls.length; + expect((await tree.write('/#0', 'é'.repeat(2049))).code).toBe(codes.tooLarge); // 4 098 bytes + expect(bridge.calls.length).toBe(before); + expect((await tree.write('/#0', 'é'.repeat(2048))).code).toBe(''); + const narrow = createWatchTree({bridge, watch: 1, maxMessageBytes: 1343 + 10}); + await narrow.open(); + expect((await narrow.write('/#0', 'x'.repeat(11))).code).toBe(codes.tooLarge); + }); + + it('reads a full value by fragments of one snapshot, and starts again when another reading replaced it', async () => { + const bridge = fakeWatch(['abcdefgh']); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + expect(await tree.fullValue('/#0')).toEqual({text: 'abcdefgh'.repeat(3), total: 24, capped: false}); + const value = bridge.answers[functions.value]; + let interleaved = false; + bridge.answers[functions.value] = (...args) => { + if (!interleaved && args[2] !== 0) { + interleaved = true; + value(1, '/#0', 0, 0); // another reading takes the snapshot + } + return value(...args); + }; + expect((await tree.fullValue('/#0')).text).toBe('abcdefgh'.repeat(3)); + expect(interleaved).toBeTrue(); + bridge.answers[functions.value] = () => { throw refusal(codes.stale); }; + await expectAsync(tree.fullValue('/#0')).toBeRejectedWithError(codes.stale); + }); + + it('tells once that its watch is gone, and sends nothing more', async () => { + const bridge = fakeWatch(['a']); + let gone = 0; + const tree = createWatchTree({bridge, watch: 1, onGone: () => ++gone}); + await tree.open(); + bridge.answers[functions.changes] = () => { throw refusal(codes.unknown); }; + await expectAsync(tree.refresh()).toBeRejected(); + expect(gone).toBe(1); + expect(tree.gone).toBeTrue(); + const before = bridge.calls.length; + expect(await tree.refresh()).toBeFalse(); + await expectAsync(tree.expand('')).toBeRejected(); + expect(bridge.calls.length).toBe(before); + expect(gone).toBe(1); + }); +}); + +describe('The view of a tree', () => { + async function shown(values, options) { + const bridge = fakeWatch(values, options); + const list = document.createElement('ul'); + document.body.append(list); + let view = null; + const tree = createWatchTree({bridge, watch: 1, onUpdate: () => view?.render()}); + view = createTreeView({tree, list, view: {}}); + await tree.open(); + return {bridge, tree, view, list}; + } + const rows = list => [...list.querySelectorAll('li[role="treeitem"]')]; + afterEach(() => { for (const list of document.querySelectorAll('ul.tree')) list.remove(); }); + + it('shows a row per node, its texts as text and never as HTML', async () => { + const {list} = await shown(['', 'b']); + expect(rows(list).map(item => item.dataset.path)).toEqual(['', '/#0', '/#1']); + expect(list.querySelector('img')).toBeNull(); + expect(rows(list)[1].querySelector('.value').textContent).toBe(''); + expect(rows(list)[0].getAttribute('aria-expanded')).toBe('true'); + expect(rows(list)[0].querySelector('.kind').textContent).toBe('sequence [2]'); + }); + + it('folds and unfolds with the toggle', async () => { + const {list, tree} = await shown(['a', 'b']); + list.querySelector('button.toggle').click(); + await tree.settled(); + expect(rows(list).length).toBe(1); + expect(rows(list)[0].getAttribute('aria-expanded')).toBe('false'); + list.querySelector('button.toggle').click(); + await tree.settled(); + expect(rows(list).length).toBe(3); + }); + + it('edits a writable value in place: Enter writes, Escape cancels', async () => { + const values = ['a', 'b']; + const {list, tree, view} = await shown(values); + rows(list)[2].querySelector('.value').click(); + let input = list.querySelector('input.edit'); + expect(input.value).toBe('b'); + input.value = 'cancelled'; + input.dispatchEvent(new Event('input')); + input.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape'})); + expect(list.querySelector('input.edit')).toBeNull(); + expect(values[1]).toBe('b'); + view.edit('/#1'); + input = list.querySelector('input.edit'); + input.value = 'B'; + input.dispatchEvent(new Event('input')); + // A refresh while the user types keeps the edition and its text. + await tree.refresh(); + expect(list.querySelector('input.edit').value).toBe('B'); + list.querySelector('input.edit').dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter'})); + await tree.settled(); + await Promise.resolve(); + expect(values[1]).toBe('B'); + expect(rows(list)[2].querySelector('.value').textContent).toBe('B'); + }); + + it('says why a write was not applied, beside the node', async () => { + const {list, tree, view} = await shown(['a']); + view.edit('/#0'); + const input = list.querySelector('input.edit'); + input.value = 'refuse'; + input.dispatchEvent(new Event('input')); + input.dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter'})); + await tree.settled(); + await new Promise(resolve => setTimeout(resolve)); + expect(rows(list)[1].querySelector('.note').textContent).toBe('not this value'); + expect(writeFailure({code: codes.stale, message: ''})).toContain('read again'); + }); + + it('offers no edition of a value that is not writable', async () => { + const {list} = await shown(['a'], {writable: false}); + rows(list)[1].querySelector('.value').click(); + expect(list.querySelector('input.edit')).toBeNull(); + expect(rows(list)[1].querySelector('.value').classList.contains('writable')).toBeFalse(); + }); + + it('highlights what the last pass changed', async () => { + const values = ['a', 'b']; + const {list, tree} = await shown(values); + values[0] = 'A'; + await tree.refresh(); + expect(rows(list).map(item => item.classList.contains('changed'))).toEqual([false, true, false]); + await tree.refresh(); + expect(rows(list).some(item => item.classList.contains('changed'))).toBeFalse(); + }); + + it('tells the positions that are not loaded, and loads them on demand', async () => { + const {list, tree} = await shown(Array.from({length: 7}, (unused, index) => `v${index}`), {pageSize: 3}); + const more = list.querySelector('button.more'); + expect(more.textContent).toBe('[3] to [6] not loaded'); + more.click(); + await tree.settled(); + expect(rows(list).length).toBe(7); + expect(list.querySelector('button.more').textContent).toBe('[6] not loaded'); + }); +}); From f760902852a6b45623810e88ee2794da7812c792 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:07:18 +0100 Subject: [PATCH 03/14] Tests: read and write the watches in a real browser (#682) The Jasmine suite reads two watches of its application through the bridge of the page that holds its frame: discovery, pages from the root, a pass of differences interrupted by an unfolding, writes accepted, stale and rejected, a full value read by fragments that never cut a character, and the terminal refusal once the handle is destroyed. The frame's own connection is refused each function. The developer journey unfolds a watch in the floating inspector. No wire type is added: nodes and pages are lists of tuples of the bridge's existing types (the exception of ADR-003). --- test/web/JasmineTest.cpp | 38 ++++++ test/web/developer-specs.mjs | 11 ++ test/web/suite/specs/inspector-specs.mjs | 144 +++++++++++++++++++++++ 3 files changed, 193 insertions(+) diff --git a/test/web/JasmineTest.cpp b/test/web/JasmineTest.cpp index 23664d3d..b121da78 100644 --- a/test/web/JasmineTest.cpp +++ b/test/web/JasmineTest.cpp @@ -168,6 +168,7 @@ class BrowserIntegrationTest { }); registerBitsetCallbacks(); registerListCallbacks(); + registerWatchCallbacks(); lifeReactSubscription = demo::installLifeReact(app); registerHostLoop(app); registerMediaRoute(app); @@ -252,6 +253,12 @@ class BrowserIntegrationTest { std::array domEventCounts{}; std::map documentTexts, documentInputs; std::map documentReads; + // What inspector-specs.mjs watches (#682). The handles are declared last: destroyed before what their sources read. + struct WatchedFixture { + vector rows; + string text; + inspect::Watch rowsWatch, textWatch; + } watched; // The forms of #383 built for each browser, with the object their events write. struct FormsFixture { std::shared_ptr object; @@ -455,6 +462,37 @@ class BrowserIntegrationTest { co_return reason; } + /// The watches that inspector-specs.mjs reads (#682). They are declared by a call of the specs, once bootstrap has + /// enabled the inspectors; their objects are touched by the server thread only, as the callbacks are. + void registerWatchCallbacks() { + webFront->cppFunction("watchFixture.declare", [this] { + watched.rows.clear(); + for (int index = 0; index < 500; ++index) + watched.rows.push_back("row " + to_string(index)); + watched.text.clear(); + while (watched.text.size() < 100'000) + watched.text += "h\xC3\xA9llo \xE2\x82\xAC "; // characters of 1, 2 and 3 bytes + watched.rowsWatch = webFront->watch("suite.rows", [this](inspect::Visit> visit) { + visit(watched.rows); + }); + watched.textWatch = webFront->watch("suite.text", [this](inspect::Visit visit) { + visit(watched.text); + }); + return tuple{static_cast(watched.rowsWatch.id()), static_cast(watched.textWatch.id())}; + }); + webFront->cppFunction("watchFixture.changeAll", [this](const string& prefix) { + for (size_t index = 0; index < watched.rows.size(); ++index) + watched.rows[index] = prefix + ' ' + to_string(index); + }); + webFront->cppFunction("watchFixture.row", [this](double index) { + return watched.rows.at(static_cast(index)); + }); + webFront->cppFunction("watchFixture.remove", [this] { + watched.rowsWatch.reset(); + watched.textWatch.reset(); + }); + } + void registerListCallbacks() { webFront->cppFunction("deepEcho", [](const vector::type>& value) { return value; diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index 9fa613ad..71819626 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -959,6 +959,17 @@ try { // A watch registered while the inspector is open appears, and disappears once removed (ADR-027, section 3). await webFront.cppFunction('test.watch')('integration'); await until(() => listed().includes('integration'), `A registered watch must appear in the inspector: ${listed()}`); + // Its content unfolds as a tree, read through the bridge of the page that holds the frame (#682): here a + // string, which this watch does not let the inspector write. + const watched = [...frame.contentDocument.querySelectorAll('ul.watches > li')] + .find(item => item.querySelector('.name')?.textContent === 'integration'); + watched.querySelector('button.toggle').click(); + await until(() => watched.querySelector('ul.tree li[role="treeitem"] .kind'), 'The watch must unfold its content'); + const root = watched.querySelector('ul.tree li[role="treeitem"]'); + assert(root.querySelector('.kind').textContent === 'string' && root.querySelector('.label').textContent === 'integration', + `The tree must show the watched string: ${root.textContent}`); + assert(root.querySelector('.value').textContent !== '' && !root.querySelector('.value').classList.contains('writable'), + `The watched string must be shown, read-only: ${root.textContent}`); // The list that showed it must be the one that loses it: the same document, still shown. const shownDocument = frame.contentDocument, shownList = shownDocument.querySelector('ul.watches'); const inShownList = () => [...shownList.querySelectorAll('li .name')].map(item => item.textContent).includes('integration'); diff --git a/test/web/suite/specs/inspector-specs.mjs b/test/web/suite/specs/inspector-specs.mjs index 2e607f79..467c30ad 100644 --- a/test/web/suite/specs/inspector-specs.mjs +++ b/test/web/suite/specs/inspector-specs.mjs @@ -112,3 +112,147 @@ describe('The inspectors\' registry', () => { expect(Number.isSafeInteger(tasks) && tasks >= rows.length).withContext(`tasks: ${tasks}`).toBeTrue(); }); }); + +// The trees of the watches in a real browser (#682, ADR-027 sections 3 to 6): nodes and pages travel with the bridge's +// existing types (lists of tuples, numbers, strings, a boolean), which the JavaScript codec decodes unchanged. +describe('The inspectors\' watches', () => { + const inspector = name => hostBridge().cppFunction(`webfront.inspector.${name}`); + const flags = {writable: 1, truncated: 2, removed: 4, depthReached: 8, childrenChanged: 16}; + let rows = 0, text = 0; + + /** Reads a pass to its end from its first page; returns every node it told. */ + async function finishPass(watch, page) { + const nodes = [...page[0]]; + let [, next, revision] = page; + while (next !== 0) { + const [more, following, same, resync] = await inspector('changes')(watch, revision, next, 200); + expect(resync).toBeFalse(); + expect(same).toBe(revision); + nodes.push(...more); + next = following; + } + return nodes; + } + + beforeAll(async () => { + await hostBridge().ready; + [rows, text] = await webFront.cppFunction('watchFixture.declare')(); + }); + afterAll(() => webFront.cppFunction('watchFixture.remove')()); + + it('are refused to this frame, which is not a view of the application', async () => { + const calls = {limits: [], reset: [rows], children: [rows, '', 1, 0, 10], changes: [rows, 1, 0, 10], value: [rows, '', 0, 0], + fold: [rows, '', 1], write: [rows, 1, '/#0', 'row 0', 'x']}; + for (const [name, args] of Object.entries(calls)) { + const error = await webFront.cppFunction(`webfront.inspector.${name}`)(...args).then(() => null, failure => failure); + expect(error?.code).withContext(name).toBe('webfront.inspector.denied'); + } + expect(await webFront.cppFunction('watchFixture.row')(0)).toBe('row 0'); + }); + + it('are discovered, then read page after page from the root', async () => { + const [descriptors] = await inspector('watches')(0, 0, 200); + const found = descriptors.find(descriptor => descriptor[0] === rows); + expect(found.slice(1, 3)).toEqual(['suite.rows', 'sequence']); + expect(found[3]).toMatch(/JasmineTest\.cpp:\d+$/); + expect(found[4]).toBeTrue(); + const [maxWriteTextBytes, responseBudget, maxNodes, maxSnapshotBytes] = await inspector('limits')(); + expect(responseBudget).toBeGreaterThanOrEqual(4096); + expect(maxWriteTextBytes).toBeGreaterThanOrEqual(1024); + expect([maxNodes, maxSnapshotBytes]).toEqual([10000, 16 * 1024 * 1024]); + + const revision = await inspector('reset')(rows); + let [nodes, next, answered, resync] = await inspector('children')(rows, '', revision, 0, 200); + expect(resync).toBeFalse(); + // (path, kind, label, value, children, flags): the first node is the parent, here the root. + expect(nodes[0]).toEqual(['', 'sequence', 'suite.rows', '', 500, 0]); + expect(nodes[1]).toEqual(['/#0', 'string', '[0]', 'row 0', 0, flags.writable]); + expect(nodes.length).toBe(201); + expect(next).toBe(200); + expect(answered).toBeGreaterThan(revision); + let read = 200; + while (next !== 0) { + [nodes, next, answered] = await inspector('children')(rows, '', answered, next, 200); + expect(nodes[0][0]).toBe(''); + read += nodes.length - 1; + } + expect(read).toBe(500); + // A revision that is not the memory's: C++ emptied it, and says so. + [nodes, next, answered, resync] = await inspector('children')(rows, '', revision, 0, 10); + expect([nodes, next, resync]).toEqual([[], 0, true]); + expect((await inspector('children')(rows, '', answered, 0, 10))[0].length).toBe(11); + }); + + it('tell their differences by passes, which an unfolding interrupts without losing any', async () => { + let revision = await inspector('reset')(rows); + let next = 0; + do { [, next, revision] = await inspector('children')(rows, '', revision, next, 200); } while (next !== 0); + await webFront.cppFunction('watchFixture.changeAll')('changed'); + const first = await inspector('changes')(rows, revision, 0, 50); + expect(first[0].length).toBe(50); + expect(first[0][0]).toEqual(['/#0', 'string', '[0]', 'changed 0', 0, flags.writable]); + expect(first[1]).toBe(50); + // An unfolding during the pass, with the revision of the pass: served at once, fresh, and no resynchronization. + const [page, , answered, resync] = await inspector('children')(rows, '', first[2], 100, 10); + expect(resync).toBeFalse(); + expect(page[1].slice(0, 4)).toEqual(['/#100', 'string', '[100]', 'changed 100']); + // The next pass finds what the interrupted one had not served: 500, less the 50 served and the 10 just read. + const rest = await finishPass(rows, await inspector('changes')(rows, answered, 0, 200)); + expect(rest.length).toBe(440); + expect(rest.some(node => node[0] === '/#49' || node[0] === '/#105')).toBeFalse(); + expect(rest.every(node => node[3].startsWith('changed '))).toBeTrue(); + await webFront.cppFunction('watchFixture.changeAll')('row'); + }); + + it('write a value only where it still shows what was displayed', async () => { + const revision = await inspector('reset')(rows); + const [, , opened] = await inspector('children')(rows, '', revision, 0, 10); + const [written, code, message] = await inspector('write')(rows, opened, '/#3', 'row 3', 'écrit €'); + expect([code, message]).toEqual(['', '']); + expect(written).toBeGreaterThan(opened); + expect(await webFront.cppFunction('watchFixture.row')(3)).toBe('écrit €'); + // What the inspector showed is no longer true: the answer says so, with the revision to go on with. + const [after, stale] = await inspector('write')(rows, written, '/#3', 'row 3', 'again'); + expect(stale).toBe('webfront.inspector.stale'); + expect(await webFront.cppFunction('watchFixture.row')(3)).toBe('écrit €'); + // A refusal seen before any effect rejects: a node that is not writable, an older revision. + const refused = await inspector('write')(rows, after, '', '', 'x').then(() => null, failure => failure); + expect(refused?.code).toBe('webfront.inspector.readOnly'); + const old = await inspector('write')(rows, opened, '/#4', 'row 4', 'x').then(() => null, failure => failure); + expect(old?.code).toBe('webfront.inspector.stale'); + expect((await inspector('write')(rows, after, '/#3', 'écrit €', 'row 3'))[1]).toBe(''); + }); + + it('give a full value by fragments of one snapshot, which never cut a character', async () => { + const revision = await inspector('reset')(text); + const [[root]] = await inspector('children')(text, '', revision, 0, 10); + expect(root.slice(0, 3)).toEqual(['', 'string', 'suite.text']); + expect(root[5]).toBe(flags.truncated); + expect(new TextEncoder().encode(root[3]).length).toBeLessThanOrEqual(256); + let [part, total, next, capped, snapshot] = await inspector('value')(text, '', 0, 0); + let whole = part, fragments = 1; + while (next !== 0) { + [part, total, next, capped] = await inspector('value')(text, '', snapshot, next); + expect(part.includes('�')).withContext('a fragment cut a character').toBeFalse(); + whole += part; + ++fragments; + } + expect(fragments).toBeGreaterThan(2); + expect(capped).toBeFalse(); + expect(total).toBe(new TextEncoder().encode(whole).length); + expect(whole).toBe('héllo € '.repeat(whole.length / 8)); + expect(total).toBeGreaterThanOrEqual(100000); + // The snapshot was freed with its last fragment: its identifier no longer reads anything. + const late = await inspector('value')(text, '', snapshot, 4).then(() => null, failure => failure); + expect(late?.code).toBe('webfront.inspector.stale'); + }); + + it('answer that a watch is gone once its handle is destroyed', async () => { + const revision = await inspector('reset')(rows); + await webFront.cppFunction('watchFixture.remove')(); + const gone = await inspector('children')(rows, '', revision, 0, 10).then(() => null, failure => failure); + expect(gone?.code).toBe('webfront.inspector.unknown'); + const [descriptors] = await inspector('watches')(0, 0, 200); + expect(descriptors.some(descriptor => descriptor[0] === rows)).toBeFalse(); + }); +}); From 3e21f75ad63b163f530edc4c7906b856a97fcc95 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:07:18 +0100 Subject: [PATCH 04/14] Life: watch the grid and the generations of the developer stage (#682) WebFrontLifeDeveloper keeps the last grid it computed and counts the generations, and declares them as watches: visitors called under a mutex, the handles declared after it so that they are destroyed first and outside any lock. The generations are writable from the inspector. --- examples/life/LifeDeveloper.cpp | 13 +++++- examples/life/LifeWatches.hpp | 70 ++++++++++++++++++++++++++++++ test/cmake/CheckNewcomerDocs.cmake | 5 +++ 3 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 examples/life/LifeWatches.hpp diff --git a/examples/life/LifeDeveloper.cpp b/examples/life/LifeDeveloper.cpp index 983f9d58..6ef54c92 100644 --- a/examples/life/LifeDeveloper.cpp +++ b/examples/life/LifeDeveloper.cpp @@ -11,6 +11,7 @@ #include "Life.hpp" #include "LifeDeveloperOptions.hpp" #include "LifeFrontend.hpp" +#include "LifeWatches.hpp" #include #include @@ -27,12 +28,20 @@ int main(int argc, char** argv) { } try { webfront::demo::prepareLifeProject(options->project); - webfront::demo::LifeApp app{options->project}; - app.cppFunction("life.step", &webfront::demo::nextLife); + // What the inspectors show of the simulation (State C++ > Watches in the menu of the WebFront tab): declared before + // the application, whose callback refers to it. + webfront::demo::LifeObserved observed; + webfront::demo::LifeApp app{options->project}; + // The simulation is webfront::demo::nextLife, as in the console and embedded stages; this stage keeps its last result. + app.cppFunction("life.step", [&observed](const webfront::demo::LifeGrid& cells) { + return observed.step(cells); + }); if (!options->environment) app.bootstrap("developer"); else app.bootstrap("developer", {.environment = *options->environment, .integrity = *options->integrity}); + // After bootstrap, which enables the inspectors, and after `observed`: the handles are destroyed before its mutex. + const auto watches = webfront::demo::watchLife(app, observed); app.show(); } catch (const std::exception& error) { std::cerr << error.what() << '\n'; diff --git a/examples/life/LifeWatches.hpp b/examples/life/LifeWatches.hpp new file mode 100644 index 00000000..5a1256b8 --- /dev/null +++ b/examples/life/LifeWatches.hpp @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-27 +// +// WebFront — examples +// Role: What the Life developer example shows in the inspectors (docs/WATCHES.md): the last grid computed and the number of generations. +// Thread: thread-safe | Alloc: heap-init +// LLM: example of app.watch; the visitor runs under the mutex, the handles are destroyed before it and outside any lock + +#pragma once + +#include "Life.hpp" +#include + +#include +#include +#include +#include +#include + +namespace webfront::demo { + +/** + * The state the example keeps for the inspectors. The page owns the simulation and calls `life.step` for each generation; + * C++ keeps the last grid it computed, as rows of text, and counts the generations. + * + * Here every access is on the server thread, which runs `life.step` and the inspectors' reads alike. The mutex is what an + * application needs as soon as another thread computes: the watches below are written for that case. + */ +struct LifeObserved { + std::mutex mutex; + std::vector grid = std::vector(32, std::string(32, '.')); + std::uint64_t generations = 0; + + /// The next generation, kept for the inspectors. + LifeGrid step(const LifeGrid& cells) { + const auto next = nextLife(cells); + std::scoped_lock lock{mutex}; + for (std::size_t y = 0; y < grid.size(); ++y) + for (std::size_t x = 0; x < grid[y].size(); ++x) + grid[y][x] = next[y * 32 + x] ? '#' : '.'; + ++generations; + return next; + } +}; + +/** + * Declares the watches of the example: `grid`, read-only, and `generations`, which the inspector can write. + * + * Each source is a visitor: WebFront calls it, it takes the lock and calls `visit` once with the object, so that a whole + * operation of the inspector (a page, a pass of differences, a write) runs under the lock. A source that took the lock and + * returned a reference would protect nothing: the lock would be released before the object is read. + * + * Keep the returned handles in a variable declared after `observed`: they are then destroyed before its mutex, and outside + * any lock, which is what the destruction of a watch requires since it waits for an operation in progress. + */ +template +[[nodiscard]] std::array watchLife(App& app, LifeObserved& observed) { + return {app.watch("grid", + [&observed](inspect::Visit> visit) { + std::scoped_lock lock{observed.mutex}; + visit(observed.grid); + }), + app.watch("generations", [&observed](inspect::Visit visit) { + std::scoped_lock lock{observed.mutex}; + visit(observed.generations); + })}; +} + +} // namespace webfront::demo diff --git a/test/cmake/CheckNewcomerDocs.cmake b/test/cmake/CheckNewcomerDocs.cmake index 49398b82..d5fd8802 100644 --- a/test/cmake/CheckNewcomerDocs.cmake +++ b/test/cmake/CheckNewcomerDocs.cmake @@ -64,8 +64,13 @@ _require("${readme}" "target_link_libraries(MyApp PRIVATE WebFront::WebFront)" " _require("${readme}" "mkdir build\ncd build\ncmake ..\ncmake --build .\n" "Life standard build") foreach(line "app.cppFunction(\"life.step\", &webfront::demo::nextLife);" "app.bootstrap(\"developer\");" "app.show();") _require("${readme}" "${line}" "Life bootstrap snippet") +endforeach() +# The compiled developer stage registers the same simulation through what it keeps for the inspectors (LifeWatches.hpp). +foreach(line "app.cppFunction(\"life.step\", " "webfront::demo::nextLife" "app.bootstrap(\"developer\");" "app.show();") _require("${life}" "${line}" "compiled Life bootstrap") endforeach() +_read(life_watches examples/life/LifeWatches.hpp) +_require("${life_watches}" "const auto next = nextLife(cells);" "the developer stage steps with the shared simulation") foreach(line "#include " "Grid nextLife(const Grid& cells)" "app.cppFunction(\"life.step\", &nextLife);") _require("${readme}" "${line}" "self-contained introductory Life application") endforeach() From 459e8a98e8d0a80fac750aa02441ac1716e44734 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:07:18 +0100 Subject: [PATCH 05/14] Document the watches, and what ADR-027 left open about them (#682) docs/WATCHES.md is the guide: the sources and the rule of one operation in one access, what is rendered, large containers and keys, writes and their refusals, the destruction of the handle, the bounds. ADR-027 (version 1.3) records the choices of the implementation in a section 6 bis. --- AGENTS.md | 1 + docs/CHANGELOG.md | 5 + docs/DEVELOPER_ENVIRONMENT.md | 5 +- docs/WATCHES.md | 219 ++++++++++++++++++ ...-inspecteurs-de-l-etat-de-l-application.md | 47 ++++ 5 files changed, 276 insertions(+), 1 deletion(-) create mode 100644 docs/WATCHES.md diff --git a/AGENTS.md b/AGENTS.md index a646b2ec..9653fbef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,7 @@ The README introduces WebFront through the Game of Life walkthrough, demonstrati - `docs/PROJECT_STATUS.md`: current supported paths, validation scope and known limitations; completed work belongs in the changelog and Git history. - `docs/adr/README.md`: architecture decision index, Git history, tradeoffs and implementation rules; read the relevant ADRs before changing their contracts. - `docs/DEVELOPING_WITH_AGENTS.md`: what an agent developing a consuming application reads first (the model, the loop, each `wf` command in JSON and MCP); the README section, `wf help agents`, the starters' `AGENTS.md` and the `AgentGuidance` CTest case keep to it. +- `docs/WATCHES.md`: the watches an application declares for the inspectors with `app.watch` (sources and their lock or executor, kinds rendered, writes, destruction of the handle, bounds); `include/webfront/Watches.hpp`, `WatchMemory.hpp` and `WatchValues.hpp` implement ADR-027 sections 3 to 6. - `docs/DEVELOPER_ENVIRONMENT.md`: the reference of the developer environment (`wf` commands, manifest and lock, TypeScript and `wf check`, tests, limits, distribution); `docs/EMBEDDED_ASSETS.md`: the core's embedded resources and their regeneration. The historical `webfront/` prototype and the former top-level `webtest/` are gone: use `test/unit/` for current C++ tests and `test/web/` for browser tests. Do not revive legacy code without a specific issue and regression coverage. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 7e5ee597..37d3418e 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -19,6 +19,10 @@ these entries stays in the GitHub releases and the Git history. - 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). +- Explore an object or a container of the application as a tree in the **Watches** panel, refreshed while you use the interface: scalars, strings, containers, described and formattable types, by pages, with a chosen period and a pause, the changed values highlighted (#682, ADR-027, `docs/WATCHES.md`). +- Choose how a watch reaches its object: a visitor called under your lock (`Visit`), a reference on the executor that owns the object, a copy, or a source that owns its state (`app.watch(name, std::shared_ptr, source)`), whose handle can be destroyed under its lock (#682, ADR-027, `docs/WATCHES.md`). +- Let a very large container page itself for the inspectors with `inspect::PagedSource`, whose optional keys follow its elements when it changes (#682, ADR-027, `docs/WATCHES.md`). +- Edit a value in place from the inspector when the application makes its watch writable (`Visit`, an optional mutator): the write is applied only if the target and its ancestors still show what was displayed, and a refusal says why (#682, ADR-027, `docs/WATCHES.md`). - 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`). @@ -32,6 +36,7 @@ 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 +- Destroying the handle of a watch (`inspect::Watch`) waits for an operation of the inspectors in progress on another thread: destroy it outside every lock its source takes, or declare the watch with the state it owns (#682, ADR-027, `docs/WATCHES.md`). - 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). diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index cf0e47cd..139e7de4 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -469,7 +469,10 @@ 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 come with the next versions of the environment. + The arrow beside a watch unfolds its content as a tree: scalars, strings, containers, described and formattable types, + read by pages of 200 children and refreshed at the chosen period, the values that changed highlighted. A value the + application made writable is edited in place (Enter writes, Escape cancels); a value that is cut offers its full text. + [Watches](WATCHES.md) tells how to declare them, under which lock or on which thread they are read, and their bounds. 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) => diff --git a/docs/WATCHES.md b/docs/WATCHES.md new file mode 100644 index 00000000..e65e9a75 --- /dev/null +++ b/docs/WATCHES.md @@ -0,0 +1,219 @@ +# Watches: reading and writing C++ objects from the inspectors + +A watch names an object or a container of your application. The **C++ state ▸ Watches** panel of the +[developer environment](DEVELOPER_ENVIRONMENT.md) shows it as a tree, unfolded level by level and refreshed while you use the +interface. It needs no debugger, no pause of the program and no `printf`. The contracts are those of +[ADR-027](adr/ADR-027-inspecteurs-de-l-etat-de-l-application.md), sections 3 to 6. + +```cpp +#include + +std::mutex mutex; +std::vector grid; // written by another thread +std::uint64_t generations = 0; + +app.bootstrap("developer"); +auto gridWatch = app.watch("grid", [&](webfront::inspect::Visit> visit) { + std::scoped_lock lock{mutex}; + visit(grid); +}); +auto countWatch = app.watch("generations", [&](webfront::inspect::Visit visit) { + std::scoped_lock lock{mutex}; + visit(generations); // a Visit of a non-constant T: the inspector can write it +}); +``` + +`examples/life/LifeWatches.hpp` is this example, compiled in `WebFrontLifeDeveloper`. + +A watch exists while its handle (`webfront::inspect::Watch`) lives. Declare the watches **after** `bootstrap("developer")`: +outside the developer environment, and in a distribution build (`WEBFRONT_DISTRIBUTION=ON`), `watch` registers nothing +and returns an empty handle, so an application does not surround its watches with `#if`. A name is unique while its handle +lives and takes 256 bytes at most (`std::invalid_argument` otherwise). Each `watch` records the file and the line of its +call, which the panel shows. + +This is a development tool, not a sandbox. Only a page that is admitted reads or writes a watch: the view of an embedded +frontend, or a loopback page when the application chose `trustLoopbackClients` (see +[the menu and the inspectors](DEVELOPER_ENVIRONMENT.md)). + +## Sources: one operation, one access + +Every operation of the inspector (a page of children, a pass of differences, a full value, a write) runs **whole** inside +one access to the object, which the source defines. No reference to the object leaves it. + +| Source | Form | Use it for | Writes | +| --- | --- | --- | --- | +| Visitor | `[&](Visit visit) { std::scoped_lock lock{m}; visit(object); }` | an object shared between threads: the operation runs during `visit`, under your lock | with `Visit` | +| Reference on an executor | `watch(name, [&] -> T& { return object; }, app.uiExecutor())` | an object that one thread owns: the accessor and the operation run on that thread | with a non-constant reference | +| Reference without an executor | `[&] -> const T& { return object; }` | an object that only the server thread touches (the thread of the `cppFunction` callbacks) | never | +| Copy | `[&] { return object; }` | a small object: it is copied at each operation, and none of the costs below is bounded | never | +| Owning source | `watch(name, std::shared_ptr, source)` | an order of destruction you cannot guarantee (see [Destroying the handle](#destroying-the-handle)) | as its form | + +A source calls its `visit` once, with the object. A source that does not call it makes the operation fail with +`webfront.inspector.unavailable`; one that throws before calling it rejects the call, with nothing changed; one that throws +after it is written to the diagnostics, and the answer is served. + +**A lock taken inside an accessor protects nothing.** `[&] -> const T& { std::scoped_lock lock{m}; return object; }` releases +the lock before the object is read. That is the mistake the visitor avoids. + +**Executor.** An executor is anything whose `schedule()` returns a sender that completes on the thread owning the object: +`app.uiExecutor()`, the loop of a [host](HOST_INTEGRATION.md), or your own. The calls of a connection on a watch run one by +one, in the order they were received; the executor must run what it is given in order, as a thread's loop does. A watch +whose executor has no running loop answers `webfront.inspector.unavailable`. + +## What is shown + +The kind and the value of a node are chosen in this order: + +| Kind | Types | Value | Children | +| --- | --- | --- | --- | +| `bool`, `integer`, `real` | `bool`, integers, floating-point numbers | the value | none | +| `string` | `std::string`, `std::string_view` | the text | none | +| `bitset` | `std::bitset` | N binary digits, most significant first | none | +| `optional` | `std::optional` | `engaged` or `nullopt` | the value, when there is one | +| `variant` | `std::variant<...>` | `alternative ` | the alternative it holds | +| `tuple` | `std::pair`, `std::tuple` | empty | its members | +| `sequence` | any `std::ranges::sized_range`, a `PagedSource` | empty | its elements, labelled `[index]` or by their key | +| `map` | associative containers (`key_type` and `mapped_type`) | empty | its mapped values, labelled by their formatted key | +| `described` | a type with a description (below) | the name of the description | one per field; a choice has the kind `enum` | +| `formatted` | a type `std::format` writes | the formatted text | none | +| `opaque` | anything else | the type's name and "(not displayable)" | none | + +Control characters are shown as their visible pictures (`␊` for a line feed). A label and a value take 256 bytes at most: +a longer value is cut, flagged, and its node offers **Full value**, which reads it by fragments up to 16 MiB. + +**Described types.** Give a type the description that [forms](FORMS.md) use, and its fields become nodes, each with its +label and, when written, its bounds and choices: + +```cpp +template <> +struct webfront::inspect::Described { + static webfront::forms::Description description() { + using namespace webfront::forms; + return {.name = "Settings", .fields = {field("speed", &Settings::speed, "Speed", Bounds{1, 10})}}; + } +}; +``` + +With C++26 reflection (GCC 16, `components/forms/Reflection.hpp`), `description()` returns `forms::describe()`. A +field's value is read through its accessor, which copies a text member whole. + +**Formatters.** WebFront never formats a value whole to cut it afterwards: a value is written into a bounded receiver, a +string copied up to the bound only. For the kinds it renders itself, the memory of a value is bounded. For `formatted`, +it bounds what it stores of the output, not what your `std::formatter` allocates or how long it runs, and it runs **under +your source's lock**. Describe a type whose formatting is costly, or page it, rather than rely on its formatter. An +exception thrown by a formatter becomes the value of its node (`‹exception : message›`, kind `opaque`). + +## Large containers + +With a visitor or a reference, no operation copies the object, and the memory and the message of an operation are +proportional to the page (200 children by default, 1 000 at most, fewer when the answer's budget is reached). The time +depends on the container: + +- a `std::ranges::random_access_range` reaches a position at once: a page costs its size; +- another range (`std::list`, `std::map`) is walked from its start to the position: a late page of a very large one is + linear, **under your lock**; +- a `PagedSource` pages itself, at the cost you decide. + +```cpp +struct Rows { // webfront::inspect::PagedSource + std::size_t size() const; + void visit(std::size_t first, std::size_t count, auto&& each); // each(element), in order + std::string key(std::size_t position) const; // optional, with find() + std::optional find(std::string_view key) const; +}; +``` + +`key` and `find` give the elements an identity. The contract is a primary key's: a key names at most one element, and an +element keeps its key while it exists. The path of an element then carries its key, so the inspector follows it when the +container changes, and a write reaches the element it was typed for. WebFront checks what is local: the key at the +position `find` returns must be the same key (else the node is gone), and two elements of one page with the same key are +shown by their position, not writable, with one diagnostic. A key whose percent-encoding passes 128 bytes also falls back +to the position. + +Without keys an element is known by its position. When the container changes between two reads the inspector may show a +neighbour for a moment; the next pass corrects it, and a list read in several pages starts again when the container +changed between two of them. + +A tree is unfolded down to 64 levels, and each connection keeps 10 000 nodes of a watch at most: beyond, the panel asks you +to fold some. + +## Writing a value + +A watch is read-only unless its source writes: a `Visit` of a non-constant `T`, or a non-constant reference on an +executor. A copy never writes. In a writable watch the panel edits in place (Enter writes, Escape cancels) the booleans, +numbers, `std::string`, `std::bitset` (N binary digits) and the fields of a described type, within their bounds and +choices. A node whose label or value is cut, a constant member, and a keyed element shown by its position are not writable. + +A write carries what the panel displayed. Inside the same access as the assignment, WebFront checks that the target **and +each of its ancestors** still show it (label, value, number of children); otherwise the write is refused as stale, the +object is left as it is, and the panel reads the node again. It is a compare-and-swap on what you saw. It cannot tell two +elements without keys that look the same in every visible way: give such a container keys when the identity matters. + +To keep an invariant, pass a mutator, which replaces the assignment and throws to refuse: + +```cpp +auto watch = app.watch("settings", source, [](Settings& settings, std::string_view path, std::string_view text) { + if (path == "/.0" && text == "0") + throw std::invalid_argument("The speed cannot be 0"); // shown beside the value, bounded to 256 bytes + apply(settings, path, text); // all or nothing: that is the mutator's contract +}); +``` + +`path` tells the node: each segment is `/` then `#` and an index, `.` and the rank of a described field, or `k` and a +percent-encoded key (`webfront::inspect::parsePath` decodes it). `text` was already checked against the node's kind. + +| Refusal | Meaning | +| --- | --- | +| `webfront.inspector.parse` | the text is not a value of the node, or is out of its bounds | +| `webfront.inspector.readOnly` | the node is not writable | +| `webfront.inspector.tooLarge` | the text is longer than the bound of the buffers policy | +| `webfront.inspector.stale` | what was displayed is no longer true | +| `webfront.inspector.refused` | the mutator, or the member itself, refused the value | + +## Destroying the handle + +A source usually captures references to your objects (the object, its mutex). Destroying the handle must guarantee that no +operation touches them afterwards. + +- **By default the destruction waits** for an operation that another thread started, as joining a thread does. Destroy the + handle **outside every lock its source takes**, and outside the watch's executor; otherwise the operation waits for the + lock held by the thread that waits for the operation. Declaring the handle after the mutex is enough: it is destroyed + first. A destruction that waits for more than five seconds writes a diagnostic that names the watch and where it was + declared, then goes on waiting. +- **From the operation itself** (the source, the visitor, the mutator) the destruction can neither wait nor let the + operation go on over objects you may destroy next: WebFront writes the diagnostic and calls `std::terminate`. +- **An owning source never waits.** Give `watch` a `std::shared_ptr` to the state the source uses; each operation keeps it + alive, so the handle may be destroyed under the source's lock and from the operation itself: + +```cpp +struct Stats { std::mutex mutex; std::map values; }; +auto state = std::make_shared(); +auto watch = app.watch("stats", state, [](Stats& stats, webfront::inspect::Visit> visit) { + std::scoped_lock lock{stats.mutex}; + visit(stats.values); +}); +``` + +Once a watch is removed, an operation in progress ends, and its answer, like every later call, is +`webfront.inspector.unknown`; the panel removes the watch. A write that was already applied says so in that refusal. + +## Bounds + +| Bound | Value | +| --- | --- | +| Answer | `responseBudget = min(functionCallBufferSize, maxMessageSize)` of the buffers policy, 32 KiB by default; at least 4 KiB or the developer environment does not compile | +| Text of a write | `maxWriteTextBytes`: what `maxMessageSize` leaves beside the other arguments, at least 1 KiB; checked by the page, then by C++ | +| Label, value, name, message of an exception | 256 bytes of UTF-8, cut on a character | +| Path | 1 024 bytes and 64 segments; a key, 128 bytes once encoded | +| Memory of a connection for a watch | 10 000 nodes | +| Full value | 16 MiB, read by fragments of one snapshot | +| Page | 200 entries by default, 1 000 at most | + +## How the panel reads + +The panel reads at a period you choose (250 ms by default) and can be paused; C++ sends nothing by itself, and a watch +that no inspector reads costs an entry in a table. Each period is a *pass of differences*: C++ compares what it sent to +this connection with the object, in one access, and answers the nodes that changed, by pages. An unfolding, a folding or a +write never waits for the end of a pass: it interrupts it, and the next pass finds the rest. The protocol +(`webfront.inspector.children`, `changes`, `value`, `fold`, `reset`, `limits`, `write`) is described in section 3 of the +ADR; it uses the bridge's existing types only. 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 12f99421..68b3f368 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.3 | 2026-11-27 | Proposée | Ambroise Leclerc | Observateurs (#682) : précisions de la section « Précisions des observateurs » (6 bis) — `fold` répond par une page vide, `limits` par six nombres, la source propriétaire reçoit son état, le mutateur reçoit le texte déjà validé, un parent signalé « enfants modifiés » perd ses enfants en mémoire, la mémoire de 10 000 nœuds se compte par connexion et par observateur, `maxWriteTextBytes` tient compte de l'en-tête réel du texte, un formateur écrit pour `std::format_context` est accepté. | À renseigner après intégration. | | 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. | @@ -628,6 +629,52 @@ un refus du mutateur (`webfront.inspector.refused`, avec le message de son excep est inchangé et l'inspecteur affiche la raison. Un mutateur fourni par l'application doit être tout ou rien ; c'est son contrat. +### 6 bis. Précisions des observateurs (#682) + +L'implémentation (`Watches.hpp`, `WatchMemory.hpp`, `WatchValues.hpp`, guide [Observateurs](../WATCHES.md)) fixe ce que +les sections 3 à 6 laissaient ouvert : + +- **Réponses.** `fold` répond par une page `(liste vide, 0, révision, resynchroniser)`, pour porter la resynchronisation + d'une révision périmée comme `children` et `changes`. `limits()` répond `(maxWriteTextBytes, responseBudget, nœuds de la + mémoire, octets d'un instantané, nombre maximal d'une page, nombre par défaut)`. `value` rend 0 comme décalage suivant + avec le dernier fragment, et l'instantané est libéré à ce moment : son identifiant ne lit plus rien ensuite. +- **Première ouverture.** L'inspecteur ouvre un observateur par `reset`, qui lui donne la révision d'une mémoire vide, + puis par `children` de la racine. Un premier appel avec une révision inconnue reçoit une resynchronisation, ce qui + revient au même. +- **Valeurs affichées.** `optional` montre `engaged` ou `nullopt`, `variant` montre `alternative `, un type décrit + le nom de sa description ; un tuple, une séquence et un tableau associatif n'ont pas de valeur, leurs enfants étant leur + contenu. Les membres d'un tuple, la valeur d'un `optional` et l'alternative d'un `variant` ont un segment `#` : l'indice + du membre, 0, ou l'indice de l'alternative, de sorte qu'un changement d'alternative change le chemin de l'enfant. +- **« Enfants modifiés ».** Le drapeau a un seul sens, dans une page de `children` comme dans une passe : C++ a retiré de + sa mémoire tous les descendants de ce parent, et l'inspecteur relit la liste depuis la position 0, puis redéplie les + chemins qu'il avait dépliés et qui existent encore. Une passe le pose quand le nombre d'enfants d'un parent déplié a + changé, ou quand le segment d'un enfant chargé n'est plus celui que la mémoire a enregistré (clé déplacée, alternative + changée, `optional` vidé). Un nœud « retiré » n'est donc rapporté que par `children`, pour un chemin qui ne résout plus. +- **Mémoire.** La limite de 10 000 nœuds se compte par connexion **et par observateur**. Une page de `children` s'arrête + quand elle l'atteindrait et rend le `suivant` qui la reprend ; l'appel suivant est refusé (`webfront.inspector.limit`). +- **Clés.** Les clés d'une `PagedSource` sont des chaînes (`key` rend un type convertible en `std::string`, `find` reçoit + un `std::string_view`). Un élément désigné par sa position sous un parent à clés (clé trop longue, dupliquée dans la + page, ou `key` qui lève) garde sa clé pour libellé quand elle se lit, et une passe ne compare pas sa clé. +- **Source propriétaire.** Elle reçoit son état : `[](État& état, Visit visit)` ou `[](État& état) -> T&`. Une source + des formes ordinaires est acceptée aussi, quand elle ne capture rien que l'état ne garde vivant. +- **Mutateur.** `mutate(T& objet, std::string_view chemin, std::string_view texte)` : le texte a déjà été analysé pour le + genre du nœud, et le mutateur lève une exception pour refuser. Le chemin se décode par `inspect::parsePath`. +- **Champs décrits.** Le texte d'un champ est validé sans l'objet autant que la description le dit (genre, bornes, choix) ; + le type du membre, que seul son accesseur connaît, est vérifié à l'écriture, dont le refus résout la Promise avec + `webfront.inspector.refused`. La lecture d'un champ passe par son accesseur, qui copie un membre texte en entier : la + borne d'allocation de la section 3 ne vaut pas pour lui. +- **Exécuteur.** Un exécuteur est tout objet dont `schedule()` rend un émetteur ; l'ordre des appels repose sur le sien, + qui doit exécuter dans l'ordre ce qu'on lui confie, comme la boucle d'un thread. Tous les appels d'un observateur à + exécuteur y passent, `fold`, `reset` et `value` compris. Un exécuteur sans boucle donne `webfront.inspector.unavailable`. +- **Budget d'une requête.** `maxWriteTextBytes` vaut ce que `requestBudget` laisse une fois les autres arguments à leur + maximum (`writeRequestFixedBytes`) et l'en-tête du texte compté à sa taille réelle (2, 3 ou 5 octets) : la requête la + plus longue fait exactement `requestBudget`. Comme `minPageBytes` laisse déjà plus de 1 Kio au texte, l'assertion sur + `maxWriteTextBytes` ne peut échouer qu'avec celle sur `responseBudget`. +- **Formateurs.** Un type est `formatted` quand `std::formattable` l'accepte, ou quand son `std::formatter` se construit + et formate dans un `std::format_context` : les formateurs écrits pour ce seul contexte, que `std::format` accepte, + échappent sinon au concept selon la bibliothèque. +- **Diagnostics.** Ils vont au journal de l'application (`log::warn`). + ### 7. Fichier et ligne d'enregistrement `cppFunction` et `watch` prennent un dernier paramètre `std::source_location location = std::source_location::current()`. From eeec635d09ff57b1ca552a6938ac95f7f8109e68 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:07:59 +0100 Subject: [PATCH 06/14] Watches: name the owner in the source's closure, which keeps it alive (#682) A source of an ordinary form given with the state it owns does not receive that state: the closure captures it only to keep it alive, which Clang reports as an unused capture. --- include/webfront/Watches.hpp | 1 + 1 file changed, 1 insertion(+) diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index a2fec538..87da127c 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -744,6 +744,7 @@ makeWatch(std::string name, std::string location, Source&& source, std::shared_p core->access.writable = writable; auto kept = std::make_shared(std::forward(source)); core->access.open = [kept, owner](detail::FunctionRef use) { + static_cast(owner); // kept alive by the watch even when the source does not receive it if constexpr (Shape::visitor) { bool visited = false; Visit visit{[&](Object& object) { From 48c144b0fef58b17db441c2f1f38f31a435f6d50 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:12:26 +0100 Subject: [PATCH 07/14] Inspector: write against the value shown when the edition began (#682) A pass of differences that ran while the user typed refreshed the tree, and the write then gave C++ the refreshed value as what was displayed: a change of the application that the user never saw was overwritten. The edition keeps the value it started from, and the write gives that one, so C++ refuses it as stale. --- js/developer/environment/bundles.json | 2 +- .../environment/inspector-watches.mjs | 12 ++++++----- .../specs/inspector-watches-specs.mjs | 20 +++++++++++++++++++ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index a9048b04..4e6da4e8 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -27,7 +27,7 @@ "js/developer/environment/inspector-host.mjs": "bffcef61b8a5778f53adfea5096c5d5fa277868bbaa39e60142a3493210076fb", "js/developer/environment/inspector.mjs": "99b150f6692dca0f4e45347354ab6bfaf6bf1cb9db6bbb97672f00a530f989fc", "js/developer/environment/inspector-registry.mjs": "bdddca4f710567b9c5030a741ed96ca6b79ebbd080da6e0bb3336e91bb1f7b39", - "js/developer/environment/inspector-watches.mjs": "f5765dedf2b8b351e7febf4412e2a78a1fb8fde9d3659094b5fa62c49fc0f775", + "js/developer/environment/inspector-watches.mjs": "3ea80254ba94500674ef4baecb47b24bca15859d96d326ee3fa9f499f163457a", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", diff --git a/js/developer/environment/inspector-watches.mjs b/js/developer/environment/inspector-watches.mjs index d74edd16..afe2eba2 100644 --- a/js/developer/environment/inspector-watches.mjs +++ b/js/developer/environment/inspector-watches.mjs @@ -265,8 +265,10 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () /** * Writes `text` into the node. Resolves with {code, message}: an empty code when the value was written, else why it * was not. A text longer than the bound is refused here, without a call. After a `stale` refusal the node is read again. + * `expected` is the value the user saw when the edition began; without it, the value the tree holds now. A pass may + * have refreshed the tree since: C++ must compare the object with what was displayed, not with what was read last. */ - write(path, text) { + write(path, text, expected = undefined) { const bound = writeBound(limits, maxMessageBytes); if (utf8Bytes(text) > bound) return Promise.resolve({code: codes.tooLarge, message: `The text is longer than ${bound} bytes`}); @@ -274,7 +276,7 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () const entry = nodes.get(path); if (!entry) return {code: codes.unknown, message: 'The node is no longer shown'}; let answer; - try { answer = await call(functions.write)(watch, revision, path, entry.node.value, text); } + try { answer = await call(functions.write)(watch, revision, path, expected ?? entry.node.value, text); } catch (error) { if (error?.code === codes.unknown) return fail(error); // Rejected before any effect: nothing changed, the revision included. A stale revision is cured by reading again. @@ -383,15 +385,15 @@ export function createTreeView({tree, list, view = globalThis}) { function edit(path) { const entry = tree.nodes.get(path); if (!entry || !(entry.node.flags & flags.writable)) return; - editing = {path, text: entry.node.value}; + editing = {path, text: entry.node.value, expected: entry.node.value}; // what the user sees now, whatever is read later notes.delete(path); render(); list.querySelector('input.edit')?.select(); } async function commit() { - const {path, text} = editing; + const {path, text, expected} = editing; editing = null; - const answer = await tree.write(path, text).catch(error => ({code: error?.code ?? 'webfront.error', message: error?.message ?? String(error)})); + const answer = await tree.write(path, text, expected).catch(error => ({code: error?.code ?? 'webfront.error', message: error?.message ?? String(error)})); if (answer.code) notes.set(path, writeFailure(answer)); render(); } diff --git a/test/developer/specs/inspector-watches-specs.mjs b/test/developer/specs/inspector-watches-specs.mjs index d7882537..86377501 100644 --- a/test/developer/specs/inspector-watches-specs.mjs +++ b/test/developer/specs/inspector-watches-specs.mjs @@ -402,6 +402,26 @@ describe('The view of a tree', () => { expect(rows(list)[2].querySelector('.value').textContent).toBe('B'); }); + it('writes against the value shown when the edition began, not the one a refresh read meanwhile', async () => { + const values = ['a', 'b']; + const {list, tree, view} = await shown(values); + view.edit('/#1'); + const input = list.querySelector('input.edit'); + input.value = 'mine'; + input.dispatchEvent(new Event('input')); + // The application changes the value while the user types, and a pass reads it: the tree now holds 'theirs'. + values[1] = 'theirs'; + await tree.refresh(); + expect(tree.nodes.get('/#1').node.value).toBe('theirs'); + list.querySelector('input.edit').dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter'})); + await tree.settled(); + await new Promise(resolve => setTimeout(resolve)); + // The user never saw 'theirs': the write is refused as stale, and the change of the application is kept. + expect(values[1]).toBe('theirs'); + expect(rows(list)[2].querySelector('.note').textContent).toContain('read again'); + expect(rows(list)[2].querySelector('.value').textContent).toBe('theirs'); + }); + it('says why a write was not applied, beside the node', async () => { const {list, tree, view} = await shown(['a']); view.edit('/#0'); From 4597a8fa464c293bc3ed667a7fd0566ef6d27c2d Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:17:45 +0100 Subject: [PATCH 08/14] Watches: refuse a text that is no number for a described numeric field (#682) The check of a whole number read only where from_chars stopped: an empty text, and a number too large for 64 bits, both stop at the end of the text with an error, and were taken for whole numbers. With a mutator the text then reached the application instead of being refused as webfront.inspector.parse. The error code is read too. --- include/webfront/WatchValues.hpp | 12 +++++++----- test/unit/WatchWriteTests.cpp | 18 +++++++++++++++++- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/include/webfront/WatchValues.hpp b/include/webfront/WatchValues.hpp index 6b975ea0..c2be9e81 100644 --- a/include/webfront/WatchValues.hpp +++ b/include/webfront/WatchValues.hpp @@ -704,11 +704,13 @@ struct FieldRender { case forms::Kind::integer: case forms::Kind::number: { const auto number = forms::detail::parseFloating(text); - // "0" underflows nothing; a text the double parser refuses may still be a whole number beyond 2^53. - long long whole = 0; - unsigned long long big = 0; - const bool exact = std::from_chars(text.data(), text.data() + text.size(), whole).ptr == text.data() + text.size() - || std::from_chars(text.data(), text.data() + text.size(), big).ptr == text.data() + text.size(); + // A text the double parser refuses may still be a whole number beyond 2^53: it is one when the whole + // text is read without an error (an empty text and a number too large both stop at its end, with one). + const auto wholeAs = [text](auto parsed) { + const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), parsed); + return error == std::errc{} && end == text.data() + text.size(); + }; + const bool exact = wholeAs(0LL) || wholeAs(0ULL); if (!number && !exact) throw ParseError("Not a number"); if (described->kind == forms::Kind::integer && !exact && std::trunc(*number) != *number) diff --git a/test/unit/WatchWriteTests.cpp b/test/unit/WatchWriteTests.cpp index 619ff4d3..eec5957f 100644 --- a/test/unit/WatchWriteTests.cpp +++ b/test/unit/WatchWriteTests.cpp @@ -236,7 +236,7 @@ const Scenario watchWritesDescribed{"The fields of a described type are written auto answer = bench.write(id, revisionOf(page), "/.0", "5", "9"); requireEqual(std::get<1>(answer), std::string{}); requireEqual(settings.speed, 9); - for (const std::string_view text : {"11", "0", "2.5", "fast"}) + for (const std::string_view text : {"11", "0", "2.5", "fast", "", "99999999999999999999999999", "-"}) checkEqual(codeOf([&] { return bench.write(id, std::get<0>(answer), "/.0", "9", text); }), @@ -306,6 +306,22 @@ const Scenario watchMutators{"The application's mutator applies a write its own std::string{code::stale}); // the revision moved with the pass: refused before anything require(seenText.empty()); }); + then("a text that is not a value of a described field is refused before the mutator is called", [&] { + Game game; + int calls = 0; + const auto id = bench.watch("game", visiting(game), [&](Game&, std::string_view, std::string_view) { + ++calls; + }); + const auto page = bench.open(id); + for (const std::string_view text : {"", "-", "1e", "101", "99999999999999999999999999"}) + checkEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "/.0", "0", text); + }), + std::string{code::parse}); + requireEqual(calls, 0); + requireEqual(std::get<1>(bench.write(id, revisionOf(page), "/.0", "0", "42")), std::string{}); + requireEqual(calls, 1); + }); then("a message of 1 MiB is cut to 256 bytes on a character, and the answer fits the smallest budget", [&] { // 254 bytes then characters of 3 bytes: the first of them straddles the bound. std::string message(254, 'm'); From 4a44cb101bf84dbe208739f7face3757d1cddc23 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:25:28 +0100 Subject: [PATCH 09/14] Watches: no edition of a value shown with control pictures; compile with MSVC (#682) A value that holds a control character is displayed with its visible picture. The inspector edits what it shows: writing it back replaced a line feed by its picture, even when the user changed another part of the text. Such a node is no longer writable, as a node whose value is cut. For MSVC: the executor and the mutator of makeWatch are unused for a watch that has none (C4100); in the tests, `far` is a macro of the Windows headers, the calls of a removed watch no longer sit in the initializer of a range-for, and the two calls queued on an executor are asked by two threads instead of when_all, whose constraints MSVC does not satisfy for two tasks. --- docs/WATCHES.md | 3 +- ...-inspecteurs-de-l-etat-de-l-application.md | 3 + include/webfront/WatchMemory.hpp | 13 ++-- include/webfront/Watches.hpp | 8 ++- test/unit/WatchTreeTests.cpp | 16 +++-- test/unit/WatchWriteTests.cpp | 69 ++++++++++++------- 6 files changed, 71 insertions(+), 41 deletions(-) diff --git a/docs/WATCHES.md b/docs/WATCHES.md index e65e9a75..5ae9bb09 100644 --- a/docs/WATCHES.md +++ b/docs/WATCHES.md @@ -142,7 +142,8 @@ to fold some. A watch is read-only unless its source writes: a `Visit` of a non-constant `T`, or a non-constant reference on an executor. A copy never writes. In a writable watch the panel edits in place (Enter writes, Escape cancels) the booleans, numbers, `std::string`, `std::bitset` (N binary digits) and the fields of a described type, within their bounds and -choices. A node whose label or value is cut, a constant member, and a keyed element shown by its position are not writable. +choices. A node whose label or value is cut, a text that holds a control character (shown as its picture, which an edition +would write back in its place), a constant member, and a keyed element shown by its position are not writable. A write carries what the panel displayed. Inside the same access as the assignment, WebFront checks that the target **and each of its ancestors** still show it (label, value, number of children); otherwise the write is refused as stale, the 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 68b3f368..791a61fa 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 @@ -650,6 +650,9 @@ les sections 3 à 6 laissaient ouvert : chemins qu'il avait dépliés et qui existent encore. Une passe le pose quand le nombre d'enfants d'un parent déplié a changé, ou quand le segment d'un enfant chargé n'est plus celui que la mémoire a enregistré (clé déplacée, alternative changée, `optional` vidé). Un nœud « retiré » n'est donc rapporté que par `children`, pour un chemin qui ne résout plus. +- **Caractères de contrôle.** Une valeur qui en contient est affichée avec leurs images (section 4) : le texte montré + n'est plus celui de l'objet, et l'éditer réécrirait les images à la place des caractères. Un tel nœud n'est pas + modifiable, comme un nœud dont la valeur est tronquée. - **Mémoire.** La limite de 10 000 nœuds se compte par connexion **et par observateur**. Une page de `children` s'arrête quand elle l'atteindrait et rend le `suivant` qui la reprend ; l'appel suivant est refusé (`webfront.inspector.limit`). - **Clés.** Les clés d'une `PagedSource` sont des chaînes (`key` rend un type convertible en `std::string`, `find` reçoit diff --git a/include/webfront/WatchMemory.hpp b/include/webfront/WatchMemory.hpp index ba07aeb9..2aa35823 100644 --- a/include/webfront/WatchMemory.hpp +++ b/include/webfront/WatchMemory.hpp @@ -83,19 +83,22 @@ struct Rendered { /** * Reads a node. Nothing here fails: an exception of a formatter or of a paged source becomes the node's value, with the * kind `opaque`. A node is writable when the watch is, its type has an editor, and what is shown of it is whole and - * tells it exactly: neither its label nor its value cut, and not a keyed element told by its position. + * tells it exactly: neither its label nor its value cut, its value shown as it is (a control character is shown as its + * picture, which an edition would write back in its place), and not a keyed element told by its position. */ [[nodiscard]] inline Rendered render(const ChildView& view, std::string path, bool positional, bool writable) { const auto& ops = *view.node.ops; std::string kind, value; - std::size_t count = 0; - bool cut = false; - bool failed = false; + std::size_t count = 0; + bool cut = false; + bool altered = false; + bool failed = false; try { kind = ops.kind(view.node); TextSink sink{maxTextBytes + 1}; // one byte more than what is shown tells that it is cut ops.value(view.node, sink); std::tie(value, cut) = visibleText(sink.text(), maxTextBytes, true); + altered = !cut && value != sink.text(); count = ops.container ? ops.size(view.node) : 0; } catch (const std::exception& error) { failed = true; @@ -111,7 +114,7 @@ struct Rendered { } unsigned flags = cut ? flag::truncated : 0u; Editor editor; - if (writable && !failed && !cut && !view.labelCut && !positional && ops.editor != nullptr) { + if (writable && !failed && !cut && !altered && !view.labelCut && !positional && ops.editor != nullptr) { try { editor = ops.editor(view.node); } catch (...) { diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index 87da127c..48d4aec2 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -725,8 +725,12 @@ template /// Builds a watch from its source, and optionally the state it owns, its executor and its mutator (BasicWF::watch). template -[[nodiscard]] std::shared_ptr -makeWatch(std::string name, std::string location, Source&& source, std::shared_ptr owner, Executor executor, Mutator mutator) { +[[nodiscard]] std::shared_ptr makeWatch(std::string name, + std::string location, + Source&& source, + std::shared_ptr owner, + [[maybe_unused]] Executor executor, + [[maybe_unused]] Mutator mutator) { using Stored = std::decay_t; // a function given by name is kept as a pointer using Object = typename Shape::Object; constexpr bool stateful = requires { requires Shape::stateful; }; diff --git a/test/unit/WatchTreeTests.cpp b/test/unit/WatchTreeTests.cpp index 5a093cf8..6e30ac43 100644 --- a/test/unit/WatchTreeTests.cpp +++ b/test/unit/WatchTreeTests.cpp @@ -222,10 +222,12 @@ const Scenario watchValueKinds{"Each kind of value is rendered as a node (ADR-02 expect("/#0", "bool", "true"); expect("/#1", "integer", "-3"); expect("/#2", "real", "0.5"); - expect("/#3", - "string", - "a\xE2\x90\x8A" - "b"); // the control character is made visible + // A control character is made visible; the text shown is then not the object's, and is not offered to edition. + checkEqual(valueOf(nodeAt(page, "/#3")), + std::string{"a\xE2\x90\x8A" + "b"}); + checkEqual(kindOf(nodeAt(page, "/#3")), std::string{"string"}); + checkEqual(flagsOf(nodeAt(page, "/#3")), 0u); expect("/#4", "bitset", "0101"); checkEqual(labelOf(nodeAt(page, "/#1")), std::string{"1"}); }); @@ -379,9 +381,9 @@ const Scenario watchSourcesRead{"A watch reads through the source the applicatio checkEqual(kindOf(nodesOf(page).front()), std::string{"sequence"}); checkEqual(flagsOf(nodesOf(page)[1]), 0u); // a copy is not the object requireEqual(nextOf(page), 3.0); - const auto far = bench.children(id, "", revisionOf(page), 999, 10); - requireEqual(valuesOf(far), std::vector{"", "998001"}); - requireEqual(nextOf(far), 0.0); + const auto last = bench.children(id, "", revisionOf(page), 999, 10); + requireEqual(valuesOf(last), std::vector{"", "998001"}); + requireEqual(nextOf(last), 0.0); }); }}; diff --git a/test/unit/WatchWriteTests.cpp b/test/unit/WatchWriteTests.cpp index eec5957f..eb1510e4 100644 --- a/test/unit/WatchWriteTests.cpp +++ b/test/unit/WatchWriteTests.cpp @@ -151,6 +151,12 @@ const Scenario watchWrites{"A value is written only where the application allows then("each writable kind parses its own text", [&] { checkEqual(std::get<1>(write("/#1", "name", "other\nname")), std::string{}); checkEqual(std::get<1>(board), std::string{"other\nname"}); + // The value now shows a control character as its picture: writing what is shown would replace it, so the node + // is no longer writable. + checkEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "/#1", "other\xE2\x90\x8Aname", "x"); + }), + std::string{code::readOnly}); checkEqual(std::get<1>(write("/#2", "false", "true")), std::string{}); check(std::get<2>(board)); checkEqual(std::get<1>(write("/#3", "0001", "1010")), std::string{}); @@ -393,29 +399,33 @@ const Scenario watchRegistrations{ bench.registry->remove(first); const auto second = bench.watch("value", visiting(value)); require(second != first); - for (const auto& call : std::vector>{[&] { - static_cast(bench.children(first, "", revisionOf(page))); - }, - [&] { - static_cast(bench.changes(first, revisionOf(page))); - }, - [&] { - static_cast(bench.fold(first, "", revisionOf(page))); - }, - [&] { - static_cast(bench.reset(first)); - }, - [&] { - static_cast(bench.value(first, "")); - }, - [&] { - static_cast(bench.write(first, revisionOf(page), "", "1", "2")); - }}) + // Each call of the inspectors, on the watch that is gone. + const auto refused = [&](auto&& call) { checkEqual(codeOf([&] { call(); return 0; }), std::string{code::unknown}); + }; + const auto old = revisionOf(page); + refused([&] { + static_cast(bench.children(first, "", old)); + }); + refused([&] { + static_cast(bench.changes(first, old)); + }); + refused([&] { + static_cast(bench.fold(first, "", old)); + }); + refused([&] { + static_cast(bench.reset(first)); + }); + refused([&] { + static_cast(bench.value(first, "")); + }); + refused([&] { + static_cast(bench.write(first, old, "", "1", "2")); + }); requireEqual(value, 1); requireEqual(nodesOf(bench.open(second)).size(), std::size_t{1}); }); @@ -642,16 +652,23 @@ const Scenario watchExecutors{"With an executor, a watch's operations run on the }); then("calls sent together are run one by one, in order: the second, with the same revision, is stale", [&] { const auto revision = bench.reset(id); // nothing runs yet: the loop has not started - auto both = std::async(std::launch::async, [&] { - return networking::ex::sync_wait(networking::ex::when_all(children(revision), children(revision))); - }); - std::this_thread::sleep_for(20ms); + // Two calls with the same revision, asked one after the other while the executor's loop has not started. + const auto ask = [&] { + return std::async(std::launch::async, [&] { + return await(children(revision)); + }); + }; + auto earlier = ask(); + std::this_thread::sleep_for(50ms); + auto later = ask(); + std::this_thread::sleep_for(50ms); requireEqual(reads.load(), 0); // queued on the executor, not run where they were asked owner.start(); - const auto [first, second] = *both.get(); - require(!resyncOf(first)); - requireEqual(nodesOf(first).size(), std::size_t{4}); - require(resyncOf(second)); + const auto answered = earlier.get(); + const auto stale = later.get(); + require(!resyncOf(answered)); + requireEqual(nodesOf(answered).size(), std::size_t{4}); + require(resyncOf(stale)); }); then("an operation queued when the watch is removed is refused without calling the source", [&] { const auto revision = bench.reset(id); From c90ef7f8f2f5ddeaf15aaa091523cce80c2d1491 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:47:08 +0100 Subject: [PATCH 10/14] Watches: read nothing again after a mutator, serve a page when a source fails (#682) - A mutator may replace or empty the container that held the node: the write rendered the node through the reference taken before the call. The target is resolved again from the root, or left to the next pass when it is gone. - A paged source that throws while it gives its elements left `children` without its page: the answer carried the revision 0. The page now serves the parent and the elements given, under its revision. - A pass walked a container without random access once per run of loaded positions, each time from its start: it is walked once, from the first loaded position to the last. - A wide character type (char8_t, char16_t, char32_t, wchar_t) is shown as its number and is not writable: std::from_chars has no overload for it, and a writable watch of one did not compile. --- include/webfront/WatchMemory.hpp | 34 +++-- include/webfront/WatchValues.hpp | 19 ++- test/unit/WatchPassTests.cpp | 47 +++++++ test/unit/WatchTreeTests.cpp | 216 +++++++++++++++++-------------- test/unit/WatchWriteTests.cpp | 157 ++++++++++++---------- 5 files changed, 291 insertions(+), 182 deletions(-) diff --git a/include/webfront/WatchMemory.hpp b/include/webfront/WatchMemory.hpp index 2aa35823..ce08029b 100644 --- a/include/webfront/WatchMemory.hpp +++ b/include/webfront/WatchMemory.hpp @@ -410,10 +410,20 @@ class Memory { code = inspect::code::refused; message = "The application refused the value"; } - if (applied) + // The assignment wrote the node in place. A mutator may have done anything to the object, the container that + // held the node included: nothing read before it is used again. + if (applied && !access.mutate) store(entry, render(view, std::string(at), positional, access.writable)); return true; }); + if (applied && access.mutate) + static_cast(descend(rootView(access, root), segments, 0, false, [&](std::size_t level, const ChildView& view, bool positional) { + if (level != segments.size()) + return true; + if (const auto found = nodes.find(path); found != nodes.end()) + store(found->second, render(view, std::string(path), positional, access.writable)); + return true; + })); if (!whole || !reached) code = inspect::code::stale; answer = {static_cast(++current), std::move(code), std::move(message)}; @@ -644,7 +654,7 @@ class Memory { }; std::vector pending; std::size_t fresh = 0; // the entries the page adds to the memory - ops.visit(view.node, start, count, [&](const ChildView& child) { + const auto each = [&](const ChildView& child) { ChildView shown = child; const auto key = usableKey(view.node, child.position); if (key) @@ -663,7 +673,14 @@ class Memory { fresh += added ? 1 : 0; pending.push_back({.position = child.position, .node = std::move(rendered), .key = key}); return pending.size() < count; - }); + }; + bool failed = false; + try { + ops.visit(view.node, start, count, each); + } catch (...) { + // A paged source that fails while it gives its elements: the page serves those it gave, and ends there. + failed = true; + } // Two elements of a page with the same key break the key's contract: both are told by their position, and neither // is writable (ADR-027, section 5). @@ -708,7 +725,7 @@ class Memory { entry.lastPosition = pending.back().position; } const auto after = start + pending.size(); - return after < total ? after : 0; + return after < total && !failed ? after : 0; } /// Removes a node and its descendants. @@ -750,17 +767,18 @@ class Memory { return; const auto& ops = *view.node.ops; bool structure = now.ops != entry.ops || childrenOf(now.node) != childrenOf(entry.node); - // Each run of loaded positions is walked once (rule 3): a container without random access is not walked per child. + // A container that reaches a position at once is read by runs of loaded positions. Any other is walked once, from + // its first loaded position to its last (rule 3): each visit starts again from its beginning. for (auto run = entry.positions.begin(); run != entry.positions.end() && !structure;) { auto last = run; - std::size_t length = 1; - for (auto following = std::next(run); following != entry.positions.end() && following->first == last->first + 1; ++following) { + std::size_t length = 1; // the loaded positions of the run + for (auto following = std::next(run); following != entry.positions.end() && (!ops.direct || following->first == last->first + 1); ++following) { last = following; ++length; } std::size_t visited = 0; try { - ops.visit(view.node, run->first, length, [&](const ChildView& child) { + ops.visit(view.node, run->first, last->first - run->first + 1, [&](const ChildView& child) { const auto loaded = entry.positions.find(child.position); if (loaded == entry.positions.end()) return true; diff --git a/include/webfront/WatchValues.hpp b/include/webfront/WatchValues.hpp index c2be9e81..678bd0ea 100644 --- a/include/webfront/WatchValues.hpp +++ b/include/webfront/WatchValues.hpp @@ -603,7 +603,8 @@ struct NodeOps { bool container = false; // may have children bool keyed = false; // its children have keys bool alternative = false; // its one child is told by the rank of an alternative, not by its position - char letter = '#'; // of its children's segments + bool direct = true; // reaches a child's position at once; false for a range that is walked from its start + char letter = '#'; // of its children's segments }; template @@ -743,6 +744,7 @@ struct FieldRender { .container = false, .keyed = false, .alternative = false, + .direct = true, .letter = '#'}; }; @@ -930,7 +932,7 @@ struct Render { return [value = input == "true"](const NodeRef& target) { objectOf(target) = value; }; - } else if constexpr (shape == Shape::integer || shape == Shape::real) { + } else if constexpr (parsedInteger || shape == Shape::real) { const auto parsed = forms::detail::parseNumber(input); if (!parsed) throw ParseError(std::is_floating_point_v ? "Not a finite number" : "Not a whole number of the value's type"); @@ -955,11 +957,13 @@ struct Render { }; } - static constexpr bool editable = !std::is_const_v - && (shape == Shape::boolean || shape == Shape::integer || shape == Shape::real || shape == Shape::bitset - || std::is_same_v); - static constexpr bool hasChildren = shape == Shape::optional || shape == Shape::variant || shape == Shape::tuple || shape == Shape::map - || shape == Shape::sequence || shape == Shape::paged || shape == Shape::described; + /// The integers a text is parsed into: a wide character type is shown as its number, and has no text of its own to write. + static constexpr bool parsedInteger = shape == Shape::integer && requires(const char* text, U& value) { std::from_chars(text, text, value); }; + static constexpr bool editable = !std::is_const_v + && (shape == Shape::boolean || parsedInteger || shape == Shape::real || shape == Shape::bitset + || std::is_same_v); + static constexpr bool hasChildren = shape == Shape::optional || shape == Shape::variant || shape == Shape::tuple || shape == Shape::map + || shape == Shape::sequence || shape == Shape::paged || shape == Shape::described; static constexpr NodeOps ops{.kind = &kind, .value = &value, @@ -971,6 +975,7 @@ struct Render { .container = hasChildren, .keyed = KeyedPagedSource, .alternative = shape == Shape::variant, + .direct = !((shape == Shape::map || shape == Shape::sequence) && !std::ranges::random_access_range), .letter = shape == Shape::described ? '.' : '#'}; }; diff --git a/test/unit/WatchPassTests.cpp b/test/unit/WatchPassTests.cpp index 5dba51a5..8efd2230 100644 --- a/test/unit/WatchPassTests.cpp +++ b/test/unit/WatchPassTests.cpp @@ -10,6 +10,7 @@ #include "WatchHarness.hpp" #include +#include #include #include @@ -49,6 +50,22 @@ struct Rows { } }; +/// A paged source that fails after its first element while `failing` is set. +struct Failing { + std::vector values{1, 2, 3}; + bool failing = false; + [[nodiscard]] std::size_t size() const { + return values.size(); + } + void visit(std::size_t first, std::size_t count, auto&& each) { + for (std::size_t index = first; index < values.size() && index - first < count; ++index) { + each(values[index]); + if (failing) + throw std::runtime_error("the source failed"); + } + } +}; + /// Reads the whole list of the root, 1 000 children a page; returns the last page. Page loadAll(Bench& bench, std::uint64_t id) { auto page = bench.open(id, 1000); @@ -141,6 +158,20 @@ const Scenario watchChanges{"A pass of differences tells what changed since the checkEqual(valueOf(nodesOf(pass)[1]), std::string{"alternative 1"}); requireEqual(bench.memory(other)->size(), std::size_t{3}); }); + then("a container without random access is read in one walk, whatever the windows loaded", [&] { + std::list chain(1000, 0); + const auto other = bench.watch("chain", visiting(chain)); + auto loaded = bench.children(other, "", bench.reset(other), 0, 10); + loaded = bench.children(other, "", revisionOf(loaded), 900, 10); + loaded = bench.children(other, "", revisionOf(loaded), 500, 10); + *std::next(chain.begin(), 5) = 1; + *std::next(chain.begin(), 505) = 2; + *std::next(chain.begin(), 909) = 3; + *std::next(chain.begin(), 700) = 4; // not loaded: not told + const auto pass = bench.changes(other, revisionOf(loaded)); + requireEqual(pathsOf(pass), std::vector({"/#5", "/#505", "/#909"})); + requireEqual(valuesOf(pass), std::vector({"1", "2", "3"})); + }); then("a pass of several pages is read in the set it kept, whatever the object becomes meanwhile", [&] { std::vector values(1000, 0); const auto other = bench.watch("values", visiting(values)); @@ -430,6 +461,22 @@ const Scenario watchPassAtomicity{ fragiles[5].failing = false; requireEqual(pathsOf(bench.changes(id, revisionOf(page))), std::vector{"/#5"}); }); + then("a paged source that fails while it gives its elements: the page serves what it gave, under its revision", [&] { + Failing source; + const auto id = bench.watch("failing", visiting(source)); + auto page = bench.open(id); + requireEqual(nodesOf(page).size(), std::size_t{4}); + source.failing = true; + page = bench.children(id, "", revisionOf(page)); + require(!resyncOf(page)); + requireEqual(pathsOf(page), std::vector({"", "/#0"})); + requireEqual(nextOf(page), 0.0); + requireEqual(revisionOf(page), static_cast(bench.memory(id)->revision())); + // A pass over a source that fails tells its children changed, and answers. + const auto pass = bench.changes(id, revisionOf(page)); + require(!resyncOf(pass)); + requireEqual(revisionOf(pass), static_cast(bench.memory(id)->revision())); + }); then("after an interruption, an exception of key() makes its elements elements without a key", [&] { Rows rows{ .rows = {{"a", 1}, {"b", 2}, {"c", 3}}, diff --git a/test/unit/WatchTreeTests.cpp b/test/unit/WatchTreeTests.cpp index 6e30ac43..7c5f6016 100644 --- a/test/unit/WatchTreeTests.cpp +++ b/test/unit/WatchTreeTests.cpp @@ -286,106 +286,122 @@ const Scenario watchValueKinds{"Each kind of value is rendered as a node (ADR-02 }); }}; -const Scenario watchSourcesRead{"A watch reads through the source the application gives (ADR-027, section 5)", {"inspector"}, [] { - Bench bench; - std::vector values{1, 2, 3}; - then("a Visit shows the same tree, read-only", [&] { - const auto id = bench.watch("values", [&](Visit> visit) { - visit(values); - }); - const auto page = bench.open(id); - requireEqual(valuesOf(page), std::vector{"", "1", "2", "3"}); - for (const auto& node : nodesOf(page)) - checkEqual(flagsOf(node), 0u); - checkEqual(std::get<4>(std::get<0>(bench.registry->page(0, 0, 10, 4096)).front()), false); - }); - then("the whole operation runs inside the visit, under the application's lock", [&] { - bool locked = false; - int reads = 0; - const auto id = bench.watch("locked", [&](Visit> visit) { - static const std::list wides{ - Wide{.size = 1, .failing = false}, - Wide{.size = 2, .failing = false} - }; - locked = true; - visit(wides); - locked = false; - ++reads; - }); - // The formatter of each element runs while the source holds its "lock". - const auto page = bench.open(id); - requireEqual(valuesOf(page), std::vector{"", "w", "ww"}); - requireEqual(reads, 1); - require(!locked); - }); - then("an accessor that returns a reference or a copy is read where the call runs, and never written", [&] { - const auto byReference = bench.watch("reference", [&]() -> std::vector& { - return values; - }); - const auto byCopy = bench.watch("copy", [&] { - return values; - }); - for (const auto id : {byReference, byCopy}) { - const auto page = bench.open(id); - requireEqual(valuesOf(page), std::vector{"", "1", "2", "3"}); - checkEqual(flagsOf(nodesOf(page)[1]), 0u); - requireEqual(codeOf([&] { - return bench.write(id, revisionOf(page), "/#0", "1", "9"); - }), - std::string{code::readOnly}); - } - requireEqual(values.front(), 1); - }); - then("a source that does not give its object, or fails before giving it, rejects the call and changes nothing", [&] { - bool give = true; - bool fail = false; - const auto id = bench.watch("shy", [&](Visit> visit) { - if (fail) - throw std::runtime_error("locked\nout"); - if (give) - visit(values); - }); - const auto page = bench.open(id); - const auto memory = bench.memory(id); - give = false; - requireEqual(codeOf([&] { - return bench.children(id, "", revisionOf(page)); - }), - std::string{code::unavailable}); - fail = true; - requireEqual(codeOf([&] { - return bench.changes(id, revisionOf(page)); - }), - std::string{"exception"}); - check(messageOf([&] { - return bench.changes(id, revisionOf(page)); - }).contains("locked\xE2\x90\x8Aout")); - requireEqual(static_cast(memory->revision()), revisionOf(page)); - requireEqual(memory->size(), std::size_t{4}); - }); - then("a source that fails after its visit is reported, and the answer is served", [&] { - const auto id = bench.watch("late", [&](Visit> visit) { - visit(values); - throw std::runtime_error("after the visit"); - }); - const auto page = bench.open(id); - requireEqual(nodesOf(page).size(), std::size_t{4}); - require(bench.lastDiagnostic().contains("'late'")); - require(bench.lastDiagnostic().contains("after the visit")); - }); - then("a paged source that gives its elements by value is read through copies", [&] { - Squares squares{.count = 1000}; - const auto id = bench.watch("squares", visiting(squares)); - const auto page = bench.children(id, "", bench.reset(id), 0, 3); - requireEqual(valuesOf(page), std::vector{"", "0", "1", "4"}); - checkEqual(kindOf(nodesOf(page).front()), std::string{"sequence"}); - checkEqual(flagsOf(nodesOf(page)[1]), 0u); // a copy is not the object - requireEqual(nextOf(page), 3.0); - const auto last = bench.children(id, "", revisionOf(page), 999, 10); - requireEqual(valuesOf(last), std::vector{"", "998001"}); - requireEqual(nextOf(last), 0.0); - }); - }}; +const Scenario watchSourcesRead{ + "A watch reads through the source the application gives (ADR-027, section 5)", + {"inspector"}, + [] { + Bench bench; + std::vector values{1, 2, 3}; + then("a Visit shows the same tree, read-only", [&] { + const auto id = bench.watch("values", [&](Visit> visit) { + visit(values); + }); + const auto page = bench.open(id); + requireEqual(valuesOf(page), std::vector{"", "1", "2", "3"}); + for (const auto& node : nodesOf(page)) + checkEqual(flagsOf(node), 0u); + checkEqual(std::get<4>(std::get<0>(bench.registry->page(0, 0, 10, 4096)).front()), false); + }); + then("the whole operation runs inside the visit, under the application's lock", [&] { + bool locked = false; + int reads = 0; + const auto id = bench.watch("locked", [&](Visit> visit) { + static const std::list wides{ + Wide{.size = 1, .failing = false}, + Wide{.size = 2, .failing = false} + }; + locked = true; + visit(wides); + locked = false; + ++reads; + }); + // The formatter of each element runs while the source holds its "lock". + const auto page = bench.open(id); + requireEqual(valuesOf(page), std::vector{"", "w", "ww"}); + requireEqual(reads, 1); + require(!locked); + }); + then("an accessor that returns a reference or a copy is read where the call runs, and never written", [&] { + const auto byReference = bench.watch("reference", [&]() -> std::vector& { + return values; + }); + const auto byCopy = bench.watch("copy", [&] { + return values; + }); + for (const auto id : {byReference, byCopy}) { + const auto page = bench.open(id); + requireEqual(valuesOf(page), std::vector{"", "1", "2", "3"}); + checkEqual(flagsOf(nodesOf(page)[1]), 0u); + requireEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "/#0", "1", "9"); + }), + std::string{code::readOnly}); + } + requireEqual(values.front(), 1); + }); + then("a source that does not give its object, or fails before giving it, rejects the call and changes nothing", [&] { + bool give = true; + bool fail = false; + const auto id = bench.watch("shy", [&](Visit> visit) { + if (fail) + throw std::runtime_error("locked\nout"); + if (give) + visit(values); + }); + const auto page = bench.open(id); + const auto memory = bench.memory(id); + give = false; + requireEqual(codeOf([&] { + return bench.children(id, "", revisionOf(page)); + }), + std::string{code::unavailable}); + fail = true; + requireEqual(codeOf([&] { + return bench.changes(id, revisionOf(page)); + }), + std::string{"exception"}); + check(messageOf([&] { + return bench.changes(id, revisionOf(page)); + }).contains("locked\xE2\x90\x8Aout")); + requireEqual(static_cast(memory->revision()), revisionOf(page)); + requireEqual(memory->size(), std::size_t{4}); + }); + then("a source that fails after its visit is reported, and the answer is served", [&] { + const auto id = bench.watch("late", [&](Visit> visit) { + visit(values); + throw std::runtime_error("after the visit"); + }); + const auto page = bench.open(id); + requireEqual(nodesOf(page).size(), std::size_t{4}); + require(bench.lastDiagnostic().contains("'late'")); + require(bench.lastDiagnostic().contains("after the visit")); + }); + then("a wide character is shown as its number, and has no text to be written", [&] { + std::tuple characters{u'a', L'b', U'c', u8'd', 'e', 102}; + const auto id = bench.watch("characters", visiting(characters)); + const auto page = bench.open(id); + requireEqual(valuesOf(page), std::vector({"", "97", "98", "99", "100", "101", "102"})); + for (std::size_t index = 1; index <= 4; ++index) { + checkEqual(kindOf(nodesOf(page)[index]), std::string{"integer"}); + checkEqual(flagsOf(nodesOf(page)[index]), 0u); + } + checkEqual(flagsOf(nodesOf(page)[5]), flag::writable); + requireEqual(std::get<1>(bench.write(id, revisionOf(page), "/#5", "102", "65535")), std::string{}); + requireEqual(std::get<5>(characters), 65535); + }); + then("a paged source that gives its elements by value is read through copies", [&] { + Squares squares{.count = 1000}; + const auto id = bench.watch("squares", visiting(squares)); + const auto page = bench.children(id, "", bench.reset(id), 0, 3); + requireEqual(valuesOf(page), std::vector{"", "0", "1", "4"}); + checkEqual(kindOf(nodesOf(page).front()), std::string{"sequence"}); + checkEqual(flagsOf(nodesOf(page)[1]), 0u); // a copy is not the object + requireEqual(nextOf(page), 3.0); + const auto last = bench.children(id, "", revisionOf(page), 999, 10); + requireEqual(valuesOf(last), std::vector{"", "998001"}); + requireEqual(nextOf(last), 0.0); + }); + }}; const Scenario watchPaths{"Paths are ASCII, reversible and bounded (ADR-027, section 3)", {"inspector"}, [] { then("a key is percent-encoded, and decoded back", [&] { diff --git a/test/unit/WatchWriteTests.cpp b/test/unit/WatchWriteTests.cpp index eb1510e4..5c67195c 100644 --- a/test/unit/WatchWriteTests.cpp +++ b/test/unit/WatchWriteTests.cpp @@ -284,73 +284,96 @@ const Scenario watchWritesDescribed{"The fields of a described type are written }); }}; -const Scenario watchMutators{"The application's mutator applies a write its own way, or refuses it (ADR-027, section 6)", {"inspector"}, [] { - Bench bench; - std::vector values{1, 2, 3}; - then("it receives the object, the path and the text, in place of the assignment", [&] { - std::string seenPath, seenText; - const auto id = bench.watch("values", - visiting(values), - [&](std::vector& object, std::string_view path, std::string_view text) { - seenPath = path; - seenText = text; - object.assign(3, 7); // its own way: keeps an invariant of the application - }); - const auto page = bench.open(id); - const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "5"); - requireEqual(std::get<1>(answer), std::string{}); - requireEqual(seenPath, std::string{"/#1"}); - requireEqual(seenText, std::string{"5"}); - requireEqual(values, std::vector({7, 7, 7})); - // The memory holds what the target shows now; the other nodes are found by the next pass. - requireEqual(pathsOf(bench.changes(id, std::get<0>(answer))), std::vector({"/#0", "/#2"})); - // The text was parsed for the node first: the mutator is not called for a text that is not a number. - seenText.clear(); - checkEqual(codeOf([&] { - return bench.write(id, std::get<0>(answer), "/#1", "7", "seven"); - }), - std::string{code::stale}); // the revision moved with the pass: refused before anything - require(seenText.empty()); - }); - then("a text that is not a value of a described field is refused before the mutator is called", [&] { - Game game; - int calls = 0; - const auto id = bench.watch("game", visiting(game), [&](Game&, std::string_view, std::string_view) { - ++calls; - }); - const auto page = bench.open(id); - for (const std::string_view text : {"", "-", "1e", "101", "99999999999999999999999999"}) - checkEqual(codeOf([&] { - return bench.write(id, revisionOf(page), "/.0", "0", text); - }), - std::string{code::parse}); - requireEqual(calls, 0); - requireEqual(std::get<1>(bench.write(id, revisionOf(page), "/.0", "0", "42")), std::string{}); - requireEqual(calls, 1); - }); - then("a message of 1 MiB is cut to 256 bytes on a character, and the answer fits the smallest budget", [&] { - // 254 bytes then characters of 3 bytes: the first of them straddles the bound. - std::string message(254, 'm'); - while (message.size() < 1024 * 1024) - message += "\xE2\x82\xAC"; - const auto id = bench.watch("values", visiting(values), [&](std::vector&, std::string_view, std::string_view) { - throw std::runtime_error(message); - }); - const auto page = bench.open(id); - const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "5"); - requireEqual(std::get<1>(answer), std::string{code::refused}); - const auto& text = std::get<2>(answer); - require(text.size() <= inspect::maxTextBytes); - requireEqual(text, std::string(253, 'm') + "\xE2\x80\xA6"); // back to a whole character, then the ellipsis - require(std::get<0>(answer) != revisionOf(page)); - requireEqual(values[1], 2); - const auto bytes = 8 + 2 + 9 + inspect::detail::stringBytes(std::get<1>(answer).size()) - + inspect::detail::stringBytes(text.size()); - require(bytes <= inspect::minPageBytes); - // The revision was received: the next call is not a resynchronization. - require(!resyncOf(bench.changes(id, std::get<0>(answer)))); - }); - }}; +const Scenario watchMutators{ + "The application's mutator applies a write its own way, or refuses it (ADR-027, section 6)", + {"inspector"}, + [] { + Bench bench; + std::vector values{1, 2, 3}; + then("it receives the object, the path and the text, in place of the assignment", [&] { + std::string seenPath, seenText; + const auto id = bench.watch("values", visiting(values), [&](std::vector& object, std::string_view path, std::string_view text) { + seenPath = path; + seenText = text; + object.assign(3, 7); // its own way: keeps an invariant of the application + }); + const auto page = bench.open(id); + const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "5"); + requireEqual(std::get<1>(answer), std::string{}); + requireEqual(seenPath, std::string{"/#1"}); + requireEqual(seenText, std::string{"5"}); + requireEqual(values, std::vector({7, 7, 7})); + // The memory holds what the target shows now; the other nodes are found by the next pass. + requireEqual(pathsOf(bench.changes(id, std::get<0>(answer))), std::vector({"/#0", "/#2"})); + // The text was parsed for the node first: the mutator is not called for a text that is not a number. + seenText.clear(); + checkEqual(codeOf([&] { + return bench.write(id, std::get<0>(answer), "/#1", "7", "seven"); + }), + std::string{code::stale}); // the revision moved with the pass: refused before anything + require(seenText.empty()); + }); + then("a mutator may replace the container that held the node: nothing read before it is used again", [&] { + const auto id = bench.watch("values", visiting(values), [](std::vector& object, std::string_view, std::string_view text) { + object = std::vector(1000, std::stoi(std::string(text))); // the former elements are freed + }); + const auto page = bench.open(id); + const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "5"); + requireEqual(std::get<1>(answer), std::string{}); + requireEqual(values.size(), std::size_t{1000}); + // The target was read again in the new container; the pass tells what else changed. + const auto pass = bench.changes(id, std::get<0>(answer)); + requireEqual(pathsOf(pass), std::vector{""}); + requireEqual(flagsOf(nodesOf(pass).front()), flag::childrenChanged); + }); + then("a mutator may remove the node it was asked to write", [&] { + const auto id = bench.watch("values", visiting(values), [](std::vector& object, std::string_view, std::string_view) { + object.clear(); + }); + const auto page = bench.open(id); + const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "5"); + requireEqual(std::get<1>(answer), std::string{}); + require(values.empty()); + require(!resyncOf(bench.changes(id, std::get<0>(answer)))); + }); + then("a text that is not a value of a described field is refused before the mutator is called", [&] { + Game game; + int calls = 0; + const auto id = bench.watch("game", visiting(game), [&](Game&, std::string_view, std::string_view) { + ++calls; + }); + const auto page = bench.open(id); + for (const std::string_view text : {"", "-", "1e", "101", "99999999999999999999999999"}) + checkEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "/.0", "0", text); + }), + std::string{code::parse}); + requireEqual(calls, 0); + requireEqual(std::get<1>(bench.write(id, revisionOf(page), "/.0", "0", "42")), std::string{}); + requireEqual(calls, 1); + }); + then("a message of 1 MiB is cut to 256 bytes on a character, and the answer fits the smallest budget", [&] { + // 254 bytes then characters of 3 bytes: the first of them straddles the bound. + std::string message(254, 'm'); + while (message.size() < 1024 * 1024) + message += "\xE2\x82\xAC"; + const auto id = bench.watch("values", visiting(values), [&](std::vector&, std::string_view, std::string_view) { + throw std::runtime_error(message); + }); + const auto page = bench.open(id); + const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "5"); + requireEqual(std::get<1>(answer), std::string{code::refused}); + const auto& text = std::get<2>(answer); + require(text.size() <= inspect::maxTextBytes); + requireEqual(text, std::string(253, 'm') + "\xE2\x80\xA6"); // back to a whole character, then the ellipsis + require(std::get<0>(answer) != revisionOf(page)); + requireEqual(values[1], 2); + const auto bytes = 8 + 2 + 9 + inspect::detail::stringBytes(std::get<1>(answer).size()) + inspect::detail::stringBytes(text.size()); + require(bytes <= inspect::minPageBytes); + // The revision was received: the next call is not a resynchronization. + require(!resyncOf(bench.changes(id, std::get<0>(answer)))); + }); + }}; const Scenario watchWriteRequestBudget{ "A write request fits the message size, its text bounded on both sides (ADR-027, section 3, \"Budget d'une requête\")", From 034a18d0f6ef7c30cd1c7c8b07257ab01de6d76e Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:47:08 +0100 Subject: [PATCH 11/14] Inspector: give up an edition that a refresh made stale, keep what is typed (#682) - An edition keeps what told its node and its ancestors when it began. A refresh that changed any of it (another key under the same rank with the same value, a list that grew) gives the edition up instead of writing to what took the place. - A page that returns two keyed elements in swapped places removed the first one it had just placed: the page is applied whole, then what no position names any more is removed. - The position typed in a large container, and its focus, survive the rendering that each period causes. - The calls waiting when a tree is stopped, or its watch gone, are rejected instead of being left pending. --- js/developer/environment/bundles.json | 2 +- .../environment/inspector-watches.mjs | 56 ++++++++++++-- .../specs/inspector-watches-specs.mjs | 77 +++++++++++++++++++ 3 files changed, 126 insertions(+), 9 deletions(-) diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index f957556b..07e9d487 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -28,7 +28,7 @@ "js/developer/environment/inspector.mjs": "3fb29ac2f6f268bfa125d66dbbaddd68115e2f497b3f4f15de36b45e1d5aba7e", "js/developer/environment/inspector-packages.mjs": "1c3f6350780b841784f83bc20ead2945157c48a1f136c47e3a7a90d89bea8522", "js/developer/environment/inspector-registry.mjs": "bdddca4f710567b9c5030a741ed96ca6b79ebbd080da6e0bb3336e91bb1f7b39", - "js/developer/environment/inspector-watches.mjs": "3ea80254ba94500674ef4baecb47b24bca15859d96d326ee3fa9f499f163457a", + "js/developer/environment/inspector-watches.mjs": "a14d66c7adeba40f3ecee6b096dcac815fee9ef4a2320f757147a125603302be", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", diff --git a/js/developer/environment/inspector-watches.mjs b/js/developer/environment/inspector-watches.mjs index afe2eba2..5878c517 100644 --- a/js/developer/environment/inspector-watches.mjs +++ b/js/developer/environment/inspector-watches.mjs @@ -86,10 +86,14 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () const waiting = []; let running = null; + /** Rejects what was waiting: its callers are told, none is left pending. */ + const abandon = () => { + for (const {reject} of waiting.splice(0)) reject(Object.assign(new Error('The watch is gone'), {code: codes.unknown})); + }; const fail = error => { if (error?.code === codes.unknown && !gone) { gone = true; - waiting.length = 0; + abandon(); onGone(); } throw error; @@ -165,13 +169,18 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () return list(path, 0); } if (start === 0) for (const position of [...entry.positions.keys()]) if (position >= parent.children) remove(entry.positions.get(position)); + // The whole page first, then what it replaced and no position names any more: two keyed elements that swapped + // their places are both kept. + const replaced = []; children.forEach((child, index) => { const position = start + index; const previous = entry.positions.get(position); - if (previous !== undefined && previous !== child.path && ![...entry.positions.values()].includes(child.path)) remove(previous); + if (previous !== undefined && previous !== child.path) replaced.push(previous); entry.positions.set(position, child.path); keep(child); }); + const named = new Set(entry.positions.values()); + for (const previous of replaced) if (!named.has(previous)) remove(previous); entry.next = page.next; onUpdate(); for (const child of children) @@ -221,6 +230,19 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () /** Resolves once every call asked so far is answered. */ async settled() { while (running || waiting.length) await (running ?? Promise.resolve()).catch(() => {}); }, + /** + * What is shown of a node and of each of its ancestors (kind, label, value, number of children), as one text; null + * when one of them is no longer shown. An edition keeps it, and is given up when it changed meanwhile. + */ + shown(path) { + const parts = []; + for (let at = path; ; at = parentOf(at)) { + const entry = nodes.get(at); + if (!entry) return null; + parts.push([entry.node.kind, entry.node.label, entry.node.value, entry.node.children].join('\u0000')); + if (at === '') return parts.join('\u0001'); + } + }, /** Opens the watch: C++'s memory of it is emptied, then the root and its first children are read. */ open() { return enqueue(async () => { @@ -314,7 +336,7 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () /** Stops the tree: nothing more is sent. C++ frees its memory when the connection closes, or at the next open. */ stop() { stopped = true; - waiting.length = 0; + abandon(); }, }; return tree; @@ -364,6 +386,7 @@ export function createTreeView({tree, list, view = globalThis}) { const notes = new Map(); // path, why the last write was not applied const full = new Map(); // path, the full value read let editing = null; // {path, text}: kept across the renderings that a refresh causes + const positions = new Map(); // path, the position being typed in its "go to" field list.className = 'tree'; list.setAttribute('role', 'tree'); @@ -385,14 +408,22 @@ export function createTreeView({tree, list, view = globalThis}) { function edit(path) { const entry = tree.nodes.get(path); if (!entry || !(entry.node.flags & flags.writable)) return; - editing = {path, text: entry.node.value, expected: entry.node.value}; // what the user sees now, whatever is read later + // What the user sees now, whatever is read later: the value, and what tells the node and its ancestors. + editing = {path, text: entry.node.value, expected: entry.node.value, shown: tree.shown(path)}; notes.delete(path); render(); list.querySelector('input.edit')?.select(); } async function commit() { - const {path, text, expected} = editing; + const {path, text, expected, shown} = editing; editing = null; + // A refresh changed what the edition was started on (another key under the same rank, a list that grew): the text + // was typed for what is no longer there. + if (tree.shown(path) !== shown) { + notes.set(path, writeFailure({code: codes.stale, message: ''})); + render(); + return; + } const answer = await tree.write(path, text, expected).catch(error => ({code: error?.code ?? 'webfront.error', message: error?.message ?? String(error)})); if (answer.code) notes.set(path, writeFailure(answer)); render(); @@ -478,11 +509,16 @@ export function createTreeView({tree, list, view = globalThis}) { input.max = String(node.children - 1); input.placeholder = 'position'; input.setAttribute('aria-label', `Go to a position in ${node.label}`); + input.value = positions.get(path) ?? ''; + input.addEventListener('input', () => positions.set(path, input.value)); input.addEventListener('keydown', event => { const position = Number(input.value); - if (event.key === 'Enter' && Number.isSafeInteger(position) && position >= 0 && position < node.children) + if (event.key === 'Enter' && input.value !== '' && Number.isSafeInteger(position) && position >= 0 && position < node.children) { + positions.delete(path); report(tree.load(path, position)); + } }); + jump.dataset.jump = path; jump.append(input); group.append(jump); } @@ -495,13 +531,17 @@ export function createTreeView({tree, list, view = globalThis}) { function render() { const focused = page.activeElement; const within = focused && list.contains(focused); - const where = within ? {path: focused.closest('li')?.dataset.path, name: focused.className.split(' ')[0]} : null; + const where = within + ? {path: focused.closest('li')?.dataset.path, jump: focused.closest('li')?.dataset.jump, name: focused.className.split(' ')[0]} : null; + for (const path of [...positions.keys()]) if (!tree.nodes.has(path)) positions.delete(path); for (const path of [...notes.keys()]) if (!tree.nodes.has(path)) notes.delete(path); for (const path of [...full.keys()]) if (!tree.nodes.has(path)) full.delete(path); if (editing && !tree.nodes.has(editing.path)) editing = null; list.replaceChildren(...(tree.nodes.has('') ? [row('', 0)] : [])); if (tree.problem) list.append(element('li', 'note', tree.problem)); - if (where?.path !== undefined) { + if (where?.jump !== undefined) + [...list.querySelectorAll('li')].find(candidate => candidate.dataset.jump === where.jump)?.querySelector('input')?.focus(); + else if (where?.path !== undefined) { const item = [...list.querySelectorAll('li')].find(candidate => candidate.dataset.path === where.path); const again = item?.querySelector(`:scope > .row .${where.name || 'toggle'}`); again?.focus(); diff --git a/test/developer/specs/inspector-watches-specs.mjs b/test/developer/specs/inspector-watches-specs.mjs index 86377501..827a3f46 100644 --- a/test/developer/specs/inspector-watches-specs.mjs +++ b/test/developer/specs/inspector-watches-specs.mjs @@ -326,6 +326,41 @@ describe('The tree of a watch', () => { await expectAsync(tree.fullValue('/#0')).toBeRejectedWithError(codes.stale); }); + it('keeps two keyed elements that swapped their places when their page is read again', async () => { + const keyed = order => [[node('', 'sequence', 'rows', '', 2), ...order.map(key => node(`/k${key}`, 'integer', key, key === 'a' ? '1' : '2'))], + 0, 0, false]; + let order = ['a', 'b'], revision = 1; + const answers = { + [functions.limits]: () => limits, + [functions.reset]: () => ++revision, + [functions.children]: () => { const page = keyed(order); page[2] = ++revision; return page; }, + }; + const bridge = {cppFunction: name => async (...args) => answers[name](...args)}; + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + order = ['b', 'a']; + await tree.load('', 0); + expect([...tree.nodes.keys()].sort()).toEqual(['', '/ka', '/kb']); + expect([...tree.nodes.get('').positions.values()]).toEqual(['/kb', '/ka']); + // An element that left the page leaves the tree. + order = ['b', 'c']; + await tree.load('', 0); + expect([...tree.nodes.keys()].sort()).toEqual(['', '/kb', '/kc']); + }); + + it('settles what was waiting when it is stopped: no caller is left pending', async () => { + const bridge = fakeWatch(['a', 'b']); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + const release = bridge.hold(functions.fold); + const folding = tree.collapse(''); + const unfolding = tree.expand(''); // waits behind the folding + tree.stop(); + await expectAsync(unfolding).toBeRejectedWithError('The watch is gone'); + release(); + await folding; + }); + it('tells once that its watch is gone, and sends nothing more', async () => { const bridge = fakeWatch(['a']); let gone = 0; @@ -422,6 +457,48 @@ describe('The view of a tree', () => { expect(rows(list)[2].querySelector('.value').textContent).toBe('theirs'); }); + it('gives up an edition when a refresh changed what tells the node: its label, or an ancestor', async () => { + const values = ['a', 'b']; + const {bridge, list, tree, view} = await shown(values); + view.edit('/#1'); + const input = list.querySelector('input.edit'); + input.value = 'mine'; + input.dispatchEvent(new Event('input')); + // Another element takes the place, with the same value: only its label tells it (a map whose key was replaced). + const changes = bridge.answers[functions.changes]; + bridge.answers[functions.changes] = (...args) => { + bridge.answers[functions.changes] = changes; + const page = changes(...args); + return [[node('/#1', 'string', 'other key', 'b', 0, flags.writable)], 0, page[2], false]; + }; + await tree.refresh(); + const before = bridge.calls.length; + list.querySelector('input.edit').dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter'})); + await tree.settled(); + await new Promise(resolve => setTimeout(resolve)); + expect(bridge.calls.length).withContext('no write is sent').toBe(before); + expect(values[1]).toBe('b'); + expect(rows(list)[2].querySelector('.note').textContent).toContain('read again'); + }); + + it('keeps the position being typed, and its focus, across a refresh', async () => { + const {list, tree} = await shown(Array.from({length: 300}, (unused, index) => `v${index}`), {pageSize: 3}); + let input = list.querySelector('input.position'); + input.focus(); + input.value = '25'; + input.dispatchEvent(new Event('input')); + await tree.refresh(); + input = list.querySelector('input.position'); + expect(input.value).toBe('25'); + expect(document.activeElement).toBe(input); + input.value = '250'; + input.dispatchEvent(new Event('input')); + input.dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter'})); + await tree.settled(); + expect(tree.nodes.has('/#250')).toBeTrue(); + expect(list.querySelector('input.position').value).toBe(''); + }); + it('says why a write was not applied, beside the node', async () => { const {list, tree, view} = await shown(['a']); view.edit('/#0'); From 25e0f1c71c9b477b6edd4e25874d3dc857b226bc Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:11:56 +0100 Subject: [PATCH 12/14] Watches: name the wide character types that are not writable (#682) Whether std::from_chars takes a wide character type depends on the standard library: libc++ accepted one, which a test refused as writable. The types are named instead. The test also builds its tuple without a narrowing conversion, which MSVC treats as an error. --- include/webfront/WatchValues.hpp | 4 +- test/unit/WatchTreeTests.cpp | 230 +++++++++++++++---------------- 2 files changed, 117 insertions(+), 117 deletions(-) diff --git a/include/webfront/WatchValues.hpp b/include/webfront/WatchValues.hpp index 678bd0ea..b7f92f23 100644 --- a/include/webfront/WatchValues.hpp +++ b/include/webfront/WatchValues.hpp @@ -958,7 +958,9 @@ struct Render { } /// The integers a text is parsed into: a wide character type is shown as its number, and has no text of its own to write. - static constexpr bool parsedInteger = shape == Shape::integer && requires(const char* text, U& value) { std::from_chars(text, text, value); }; + /// The types are named: whether std::from_chars takes one of them depends on the standard library. + static constexpr bool parsedInteger = shape == Shape::integer && !std::is_same_v && !std::is_same_v && !std::is_same_v + && !std::is_same_v; static constexpr bool editable = !std::is_const_v && (shape == Shape::boolean || parsedInteger || shape == Shape::real || shape == Shape::bitset || std::is_same_v); diff --git a/test/unit/WatchTreeTests.cpp b/test/unit/WatchTreeTests.cpp index 7c5f6016..42a6934c 100644 --- a/test/unit/WatchTreeTests.cpp +++ b/test/unit/WatchTreeTests.cpp @@ -286,122 +286,120 @@ const Scenario watchValueKinds{"Each kind of value is rendered as a node (ADR-02 }); }}; -const Scenario watchSourcesRead{ - "A watch reads through the source the application gives (ADR-027, section 5)", - {"inspector"}, - [] { - Bench bench; - std::vector values{1, 2, 3}; - then("a Visit shows the same tree, read-only", [&] { - const auto id = bench.watch("values", [&](Visit> visit) { - visit(values); - }); - const auto page = bench.open(id); - requireEqual(valuesOf(page), std::vector{"", "1", "2", "3"}); - for (const auto& node : nodesOf(page)) - checkEqual(flagsOf(node), 0u); - checkEqual(std::get<4>(std::get<0>(bench.registry->page(0, 0, 10, 4096)).front()), false); - }); - then("the whole operation runs inside the visit, under the application's lock", [&] { - bool locked = false; - int reads = 0; - const auto id = bench.watch("locked", [&](Visit> visit) { - static const std::list wides{ - Wide{.size = 1, .failing = false}, - Wide{.size = 2, .failing = false} - }; - locked = true; - visit(wides); - locked = false; - ++reads; - }); - // The formatter of each element runs while the source holds its "lock". - const auto page = bench.open(id); - requireEqual(valuesOf(page), std::vector{"", "w", "ww"}); - requireEqual(reads, 1); - require(!locked); - }); - then("an accessor that returns a reference or a copy is read where the call runs, and never written", [&] { - const auto byReference = bench.watch("reference", [&]() -> std::vector& { - return values; - }); - const auto byCopy = bench.watch("copy", [&] { - return values; - }); - for (const auto id : {byReference, byCopy}) { - const auto page = bench.open(id); - requireEqual(valuesOf(page), std::vector{"", "1", "2", "3"}); - checkEqual(flagsOf(nodesOf(page)[1]), 0u); - requireEqual(codeOf([&] { - return bench.write(id, revisionOf(page), "/#0", "1", "9"); - }), - std::string{code::readOnly}); - } - requireEqual(values.front(), 1); - }); - then("a source that does not give its object, or fails before giving it, rejects the call and changes nothing", [&] { - bool give = true; - bool fail = false; - const auto id = bench.watch("shy", [&](Visit> visit) { - if (fail) - throw std::runtime_error("locked\nout"); - if (give) - visit(values); - }); - const auto page = bench.open(id); - const auto memory = bench.memory(id); - give = false; - requireEqual(codeOf([&] { - return bench.children(id, "", revisionOf(page)); - }), - std::string{code::unavailable}); - fail = true; - requireEqual(codeOf([&] { - return bench.changes(id, revisionOf(page)); - }), - std::string{"exception"}); - check(messageOf([&] { - return bench.changes(id, revisionOf(page)); - }).contains("locked\xE2\x90\x8Aout")); - requireEqual(static_cast(memory->revision()), revisionOf(page)); - requireEqual(memory->size(), std::size_t{4}); - }); - then("a source that fails after its visit is reported, and the answer is served", [&] { - const auto id = bench.watch("late", [&](Visit> visit) { - visit(values); - throw std::runtime_error("after the visit"); - }); - const auto page = bench.open(id); - requireEqual(nodesOf(page).size(), std::size_t{4}); - require(bench.lastDiagnostic().contains("'late'")); - require(bench.lastDiagnostic().contains("after the visit")); - }); - then("a wide character is shown as its number, and has no text to be written", [&] { - std::tuple characters{u'a', L'b', U'c', u8'd', 'e', 102}; - const auto id = bench.watch("characters", visiting(characters)); - const auto page = bench.open(id); - requireEqual(valuesOf(page), std::vector({"", "97", "98", "99", "100", "101", "102"})); - for (std::size_t index = 1; index <= 4; ++index) { - checkEqual(kindOf(nodesOf(page)[index]), std::string{"integer"}); - checkEqual(flagsOf(nodesOf(page)[index]), 0u); - } - checkEqual(flagsOf(nodesOf(page)[5]), flag::writable); - requireEqual(std::get<1>(bench.write(id, revisionOf(page), "/#5", "102", "65535")), std::string{}); - requireEqual(std::get<5>(characters), 65535); - }); - then("a paged source that gives its elements by value is read through copies", [&] { - Squares squares{.count = 1000}; - const auto id = bench.watch("squares", visiting(squares)); - const auto page = bench.children(id, "", bench.reset(id), 0, 3); - requireEqual(valuesOf(page), std::vector{"", "0", "1", "4"}); - checkEqual(kindOf(nodesOf(page).front()), std::string{"sequence"}); - checkEqual(flagsOf(nodesOf(page)[1]), 0u); // a copy is not the object - requireEqual(nextOf(page), 3.0); - const auto last = bench.children(id, "", revisionOf(page), 999, 10); - requireEqual(valuesOf(last), std::vector{"", "998001"}); - requireEqual(nextOf(last), 0.0); - }); - }}; +const Scenario watchSourcesRead{"A watch reads through the source the application gives (ADR-027, section 5)", {"inspector"}, [] { + Bench bench; + std::vector values{1, 2, 3}; + then("a Visit shows the same tree, read-only", [&] { + const auto id = bench.watch("values", [&](Visit> visit) { + visit(values); + }); + const auto page = bench.open(id); + requireEqual(valuesOf(page), std::vector{"", "1", "2", "3"}); + for (const auto& node : nodesOf(page)) + checkEqual(flagsOf(node), 0u); + checkEqual(std::get<4>(std::get<0>(bench.registry->page(0, 0, 10, 4096)).front()), false); + }); + then("the whole operation runs inside the visit, under the application's lock", [&] { + bool locked = false; + int reads = 0; + const auto id = bench.watch("locked", [&](Visit> visit) { + static const std::list wides{ + Wide{.size = 1, .failing = false}, + Wide{.size = 2, .failing = false} + }; + locked = true; + visit(wides); + locked = false; + ++reads; + }); + // The formatter of each element runs while the source holds its "lock". + const auto page = bench.open(id); + requireEqual(valuesOf(page), std::vector{"", "w", "ww"}); + requireEqual(reads, 1); + require(!locked); + }); + then("an accessor that returns a reference or a copy is read where the call runs, and never written", [&] { + const auto byReference = bench.watch("reference", [&]() -> std::vector& { + return values; + }); + const auto byCopy = bench.watch("copy", [&] { + return values; + }); + for (const auto id : {byReference, byCopy}) { + const auto page = bench.open(id); + requireEqual(valuesOf(page), std::vector{"", "1", "2", "3"}); + checkEqual(flagsOf(nodesOf(page)[1]), 0u); + requireEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "/#0", "1", "9"); + }), + std::string{code::readOnly}); + } + requireEqual(values.front(), 1); + }); + then("a source that does not give its object, or fails before giving it, rejects the call and changes nothing", [&] { + bool give = true; + bool fail = false; + const auto id = bench.watch("shy", [&](Visit> visit) { + if (fail) + throw std::runtime_error("locked\nout"); + if (give) + visit(values); + }); + const auto page = bench.open(id); + const auto memory = bench.memory(id); + give = false; + requireEqual(codeOf([&] { + return bench.children(id, "", revisionOf(page)); + }), + std::string{code::unavailable}); + fail = true; + requireEqual(codeOf([&] { + return bench.changes(id, revisionOf(page)); + }), + std::string{"exception"}); + check(messageOf([&] { + return bench.changes(id, revisionOf(page)); + }).contains("locked\xE2\x90\x8Aout")); + requireEqual(static_cast(memory->revision()), revisionOf(page)); + requireEqual(memory->size(), std::size_t{4}); + }); + then("a source that fails after its visit is reported, and the answer is served", [&] { + const auto id = bench.watch("late", [&](Visit> visit) { + visit(values); + throw std::runtime_error("after the visit"); + }); + const auto page = bench.open(id); + requireEqual(nodesOf(page).size(), std::size_t{4}); + require(bench.lastDiagnostic().contains("'late'")); + require(bench.lastDiagnostic().contains("after the visit")); + }); + then("a wide character is shown as its number, and has no text to be written", [&] { + std::tuple + characters{u'a', L'b', U'c', u8'd', static_cast('e'), static_cast(102)}; + const auto id = bench.watch("characters", visiting(characters)); + const auto page = bench.open(id); + requireEqual(valuesOf(page), std::vector({"", "97", "98", "99", "100", "101", "102"})); + for (std::size_t index = 1; index <= 4; ++index) { + checkEqual(kindOf(nodesOf(page)[index]), std::string{"integer"}); + checkEqual(flagsOf(nodesOf(page)[index]), 0u); + } + checkEqual(flagsOf(nodesOf(page)[5]), flag::writable); + requireEqual(std::get<1>(bench.write(id, revisionOf(page), "/#5", "102", "65535")), std::string{}); + requireEqual(std::get<5>(characters), 65535); + }); + then("a paged source that gives its elements by value is read through copies", [&] { + Squares squares{.count = 1000}; + const auto id = bench.watch("squares", visiting(squares)); + const auto page = bench.children(id, "", bench.reset(id), 0, 3); + requireEqual(valuesOf(page), std::vector{"", "0", "1", "4"}); + checkEqual(kindOf(nodesOf(page).front()), std::string{"sequence"}); + checkEqual(flagsOf(nodesOf(page)[1]), 0u); // a copy is not the object + requireEqual(nextOf(page), 3.0); + const auto last = bench.children(id, "", revisionOf(page), 999, 10); + requireEqual(valuesOf(last), std::vector{"", "998001"}); + requireEqual(nextOf(last), 0.0); + }); + }}; const Scenario watchPaths{"Paths are ASCII, reversible and bounded (ADR-027, section 3)", {"inspector"}, [] { then("a key is percent-encoded, and decoded back", [&] { From bfc9b734495080bd2fffb1d9cf2b079f98597ad4 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:46:44 +0100 Subject: [PATCH 13/14] Watches: answer the review of #700 (#682) - A read of a watch being removed publishes no snapshot: it would replace another watch's, and nothing would free it. An operation that ends on a removed watch frees what it kept in the session. - Under an element told by its position, every descendant is read-only, keyed or not; a branch whose whole path is keyed stays writable. - The mutator is called once the walk is over, in the same access: it may change the container a paged source is walking. An assignment applied is not reported stale when the source throws afterwards. - A later page that brings back a key already served at another position starts the list again. - A whole number is compared exactly with the bounds of a described field. - The inspector checks what an edition was started on again just before it sends the write. - The sessions of the connections released by shutdown are freed. - MSVC: C4702 is suppressed around makeWatch, whose closure has unreachable returns for a source that always throws, as around openWindow. - Tests release their gate even when an assertion fails. --- include/webfront/WatchMemory.hpp | 59 ++++++-- include/webfront/WatchValues.hpp | 24 ++- include/webfront/Watches.hpp | 137 +++++++++++++----- include/webfront/WebFront.hpp | 9 +- js/developer/environment/bundles.json | 2 +- .../environment/inspector-watches.mjs | 7 +- .../specs/inspector-watches-specs.mjs | 15 ++ test/unit/WatchTreeTests.cpp | 58 ++++++++ test/unit/WatchWriteTests.cpp | 119 ++++++++++++++- 9 files changed, 366 insertions(+), 64 deletions(-) diff --git a/include/webfront/WatchMemory.hpp b/include/webfront/WatchMemory.hpp index ce08029b..dd589b4e 100644 --- a/include/webfront/WatchMemory.hpp +++ b/include/webfront/WatchMemory.hpp @@ -176,7 +176,7 @@ inline bool descend(const ChildView& here, std::span segments, st ops.visit(here.node, *position, 1, [&](const ChildView& child) { ChildView named = child; std::tie(named.label, named.labelCut) = visibleText(segment.key, maxTextBytes, true); - found = descend(named, segments.subspan(1), level + 1, false, at); + found = descend(named, segments.subspan(1), level + 1, positional, at); return false; }); } else { @@ -187,7 +187,7 @@ inline bool descend(const ChildView& here, std::span segments, st return false; ops.visit(here.node, position, 1, [&](const ChildView& child) { if (child.rank == segment.number) - found = descend(child, segments.subspan(1), level + 1, ops.keyed, at); + found = descend(child, segments.subspan(1), level + 1, positional || ops.keyed, at); return false; }); } @@ -397,11 +397,12 @@ class Memory { if (std::get<3>(now.node) != expected || now.ops != entry.ops || now.aux != entry.aux || (flagsOf(now.node) & flag::writable) == 0) return false; reached = true; + // A mutator may change the container being walked: it is called once the walk is over. An assignment writes + // the node where it is. + if (access.mutate) + return true; try { - if (access.mutate) - access.mutate(root.object, path, text); - else - apply(view.node); + apply(view.node); applied = true; } catch (const std::exception& error) { code = inspect::code::refused; @@ -410,12 +411,23 @@ class Memory { code = inspect::code::refused; message = "The application refused the value"; } - // The assignment wrote the node in place. A mutator may have done anything to the object, the container that - // held the node included: nothing read before it is used again. - if (applied && !access.mutate) + if (applied) store(entry, render(view, std::string(at), positional, access.writable)); return true; }); + if (whole && reached && access.mutate) { + try { + access.mutate(root.object, path, text); + applied = true; + } catch (const std::exception& error) { + code = inspect::code::refused; + message = boundedText(error.what()); + } catch (...) { + code = inspect::code::refused; + message = "The application refused the value"; + } + } + // A mutator may have done anything to the object: nothing read before it is used again. if (applied && access.mutate) static_cast(descend(rootView(access, root), segments, 0, false, [&](std::size_t level, const ChildView& view, bool positional) { if (level != segments.size()) @@ -424,7 +436,9 @@ class Memory { store(found->second, render(view, std::string(path), positional, access.writable)); return true; })); - if (!whole || !reached) + // A source that fails after the value was assigned (a paged source that throws once it gave the element) does + // not make the write stale: it was applied. + if ((!whole || !reached) && !applied) code = inspect::code::stale; answer = {static_cast(++current), std::move(code), std::move(message)}; }); @@ -653,7 +667,8 @@ class Memory { std::optional key; }; std::vector pending; - std::size_t fresh = 0; // the entries the page adds to the memory + std::size_t fresh = 0; // the entries the page adds to the memory + bool moved = false; // a key of this page was served at another position const auto each = [&](const ChildView& child) { ChildView shown = child; const auto key = usableKey(view.node, child.position); @@ -661,12 +676,20 @@ class Memory { std::tie(shown.label, shown.labelCut) = visibleText(*key, maxTextBytes, true); const auto told = numberSegment(ops.letter, child.rank); const auto childAt = childPath(path, key ? 'k' + encodeKey(*key) : told); - auto rendered = render(shown, childAt, ops.keyed && !key, access.writable); + auto rendered = render(shown, childAt, positional || (ops.keyed && !key), access.writable); // A keyed child may yet be told by its position (a key that another child of the page has too): the page keeps // room for the longer of its two paths. const auto longer = (std::max)(childAt.size(), path.size() + 1 + told.size()); const auto bytes = nodeBytes(rendered.node) + stringBytes(longer) - stringBytes(childAt.size()); const bool added = !nodes.contains(childAt); + if (start > 0 && key) { + // A key served at another position of this list: the source moved its elements between two pages. + for (const auto& [position, loaded] : entry.positions) + if (loaded == childAt && position != child.position) { + moved = true; + return false; + } + } if (used + bytes > budget || (added && nodes.size() + fresh >= limits.maxNodes)) return false; used += bytes; @@ -681,6 +704,14 @@ class Memory { // A paged source that fails while it gives its elements: the page serves those it gave, and ends there. failed = true; } + if (moved) { + // As when the number of children changed (rule 2): the list starts again from its first position. + dropDescendants(path, nullptr); + entry.positions.clear(); + entry.lastKey.reset(); + std::get<5>(served.front()) = static_cast(flagsOf(served.front()) | flag::childrenChanged); + return 0; + } // Two elements of a page with the same key break the key's contract: both are told by their position, and neither // is writable (ADR-027, section 5). @@ -785,7 +816,7 @@ class Memory { ++visited; const std::string_view recorded = std::string_view{loaded->second}.substr(path.size() + 1); ChildView shown = child; - bool byPlace = false; + bool byPlace = positional; // under a parent told by its position, so is every child // A keyed child is labelled by its key, also when it is told by its position (a key that repeats). const auto key = usableKey(view.node, child.position); if (key) @@ -796,7 +827,7 @@ class Memory { return false; } } else { - byPlace = ops.keyed; + byPlace = positional || ops.keyed; if (numberSegment(ops.letter, ops.keyed ? child.position : child.rank) != recorded) { structure = true; return false; diff --git a/include/webfront/WatchValues.hpp b/include/webfront/WatchValues.hpp index b7f92f23..34feba66 100644 --- a/include/webfront/WatchValues.hpp +++ b/include/webfront/WatchValues.hpp @@ -707,18 +707,30 @@ struct FieldRender { const auto number = forms::detail::parseFloating(text); // A text the double parser refuses may still be a whole number beyond 2^53: it is one when the whole // text is read without an error (an empty text and a number too large both stop at its end, with one). - const auto wholeAs = [text](auto parsed) { + const auto wholeAs = [text](auto parsed) -> std::optional { const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), parsed); - return error == std::errc{} && end == text.data() + text.size(); + if (error == std::errc{} && end == text.data() + text.size()) + return parsed; + return std::nullopt; }; - const bool exact = wholeAs(0LL) || wholeAs(0ULL); + const auto signedWhole = wholeAs(0LL); + const auto bigWhole = signedWhole ? std::nullopt : wholeAs(0ULL); + const bool exact = signedWhole || bigWhole; if (!number && !exact) throw ParseError("Not a number"); if (described->kind == forms::Kind::integer && !exact && std::trunc(*number) != *number) throw ParseError("Not a whole number"); - if (number && described->range && (*number < described->range->min || *number > described->range->max)) - throw ParseError("Out of the bounds " + forms::detail::formatNumber(described->range->min) + " to " - + forms::detail::formatNumber(described->range->max)); + if (described->range) { + // A whole number is compared exactly: as a double, 2^53 + 1 would round onto a bound of 2^53. + const bool inside = signedWhole ? forms::detail::atLeast(*signedWhole, described->range->min) + && forms::detail::atMost(*signedWhole, described->range->max) + : bigWhole ? forms::detail::atLeast(*bigWhole, described->range->min) + && forms::detail::atMost(*bigWhole, described->range->max) + : *number >= described->range->min && *number <= described->range->max; + if (!inside) + throw ParseError("Out of the bounds " + forms::detail::formatNumber(described->range->min) + " to " + + forms::detail::formatNumber(described->range->max)); + } break; } case forms::Kind::text: diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index 48d4aec2..03ed3d79 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -246,6 +246,18 @@ class WatchSession { std::scoped_lock lock{mutex}; return snapshot.has_value(); } + /// Frees what this connection keeps of a watch: its memory and, when it is the watch's, the snapshot. + void drop(std::uint64_t watch) noexcept { + std::shared_ptr released; + std::optional snapshotReleased; + std::scoped_lock lock{mutex}; + if (const auto found = memories.find(watch); found != memories.end()) { + released = std::move(found->second); + memories.erase(found); + } + if (snapshot && snapshot->watch == watch) + snapshotReleased.swap(snapshot); + } private: friend class WatchRegistry; @@ -421,7 +433,7 @@ class WatchRegistry { * it was removed is replaced by the terminal refusal: its revision would be that of a memory that no longer exists. */ template - static auto perform(Core& core, Operation&& operation, const bool* written = nullptr) { + static auto perform(Core& core, Operation&& operation, const bool* written = nullptr, WatchSession* session = nullptr) { { std::scoped_lock lock{core.lifecycle}; if (core.removed) @@ -436,9 +448,17 @@ class WatchRegistry { core.idle.notify_all(); } }; + // A watch removed while the operation ran: what the operation kept for the connection (a memory it created again) + // is freed, since the removal may have cleaned the session before. const auto removed = [&] { - std::scoped_lock lock{core.lifecycle}; - return core.removed; + { + std::scoped_lock lock{core.lifecycle}; + if (!core.removed) + return false; + } + if (session != nullptr) + session->drop(core.id); + return true; }; Done done{core}; try { @@ -453,6 +473,13 @@ class WatchRegistry { } } + /// Whether the watch is being removed. Read under a session's lock, it orders a publication in that session with the + /// removal, which takes the session's lock after it marks the watch. + [[nodiscard]] static bool removing(Core& core) { + std::scoped_lock lock{core.lifecycle}; + return core.removed; + } + public: // --- Operations (ADR-027, sections 3 and 6) ---------------------------------------------------------------- @@ -503,30 +530,46 @@ class WatchRegistry { double count, const Limits& limits) { const auto core = find(watch); - return perform(*core, [&] { - return from->memory(core->id)->children(core->access, path, revision, start, count, limits); - }); + return perform( + *core, + [&] { + return from->memory(core->id)->children(core->access, path, revision, start, count, limits); + }, + nullptr, + from.get()); } Page changes(const std::shared_ptr& from, double watch, double revision, double cursor, double count, const Limits& limits) { const auto core = find(watch); - return perform(*core, [&] { - return from->memory(core->id)->changes(core->access, revision, cursor, count, limits); - }); + return perform( + *core, + [&] { + return from->memory(core->id)->changes(core->access, revision, cursor, count, limits); + }, + nullptr, + from.get()); } Page fold(const std::shared_ptr& from, double watch, std::string_view path, double revision) { const auto core = find(watch); - return perform(*core, [&] { - return from->memory(core->id)->fold(path, revision); - }); + return perform( + *core, + [&] { + return from->memory(core->id)->fold(path, revision); + }, + nullptr, + from.get()); } double reset(const std::shared_ptr& from, double watch) { const auto core = find(watch); - return perform(*core, [&] { - return from->memory(core->id)->reset(); - }); + return perform( + *core, + [&] { + return from->memory(core->id)->reset(); + }, + nullptr, + from.get()); } WriteAnswer write(const std::shared_ptr& from, @@ -543,7 +586,8 @@ class WatchRegistry { [&] { return from->memory(core->id)->write(core->access, revision, path, expected, text, limits, applied); }, - &applied); + &applied, + from.get()); } /** @@ -555,30 +599,38 @@ class WatchRegistry { ValueAnswer value(const std::shared_ptr& from, double watch, std::string_view path, double snapshotAsked, double offsetAsked, const Limits& limits) { const auto core = find(watch); - return perform(*core, [&]() -> ValueAnswer { - const auto snapshot = wholeNumber(snapshotAsked, "snapshot"), offset = wholeNumber(offsetAsked, "offset"); - const auto room = limits.responseBudget - responseHeaderBytes; - if (snapshot == 0) { - if (offset != 0) - throw detail::refusal(code::stale, "A new reading starts at the offset 0"); - auto [text, capped] = from->memory(core->id)->value(core->access, path, limits.maxSnapshotBytes); + return perform( + *core, + [&]() -> ValueAnswer { + const auto snapshot = wholeNumber(snapshotAsked, "snapshot"), offset = wholeNumber(offsetAsked, "offset"); + const auto room = limits.responseBudget - responseHeaderBytes; + if (snapshot == 0) { + if (offset != 0) + throw detail::refusal(code::stale, "A new reading starts at the offset 0"); + auto [text, capped] = from->memory(core->id)->value(core->access, path, limits.maxSnapshotBytes); + std::scoped_lock lock{from->mutex}; + if (from->closed) + throw webfront::detail::makeBridgeError(bridge_code::disconnected, "The connection is closed"); + // A watch removed meanwhile publishes nothing: its snapshot would replace another watch's, and nothing would + // free it. A removal that comes after the publication frees it (it takes this lock once the watch is marked). + if (removing(*core)) + throw gone(false); + from->snapshot = detail::Snapshot{.id = ++from->snapshots, + .watch = core->id, + .path = std::string(path), + .text = std::move(text), + .next = 0, + .capped = capped}; + return fragment(*from, room); + } std::scoped_lock lock{from->mutex}; - if (from->closed) - throw webfront::detail::makeBridgeError(bridge_code::disconnected, "The connection is closed"); - from->snapshot = detail::Snapshot{.id = ++from->snapshots, - .watch = core->id, - .path = std::string(path), - .text = std::move(text), - .next = 0, - .capped = capped}; + const auto& kept = from->snapshot; + if (!kept || kept->id != snapshot || kept->watch != core->id || kept->path != path || kept->next != offset || offset == 0) + throw detail::refusal(code::stale, "The snapshot is no longer the connection's: read the value again"); return fragment(*from, room); - } - std::scoped_lock lock{from->mutex}; - const auto& kept = from->snapshot; - if (!kept || kept->id != snapshot || kept->watch != core->id || kept->path != path || kept->next != offset || offset == 0) - throw detail::refusal(code::stale, "The snapshot is no longer the connection's: read the value again"); - return fragment(*from, room); - }); + }, + nullptr, + from.get()); } /// The bounds of the operations, as webfront.inspector.limits answers them. @@ -723,6 +775,12 @@ template } } // namespace detail +#ifdef _MSC_VER + // A source that always throws (a test of a failing source, an application's placeholder) makes the returns of the + // closure below provably unreachable for that instantiation; MSVC flags it under /WX. It is expected, not a bug. + #pragma warning(push) + #pragma warning(disable : 4702) +#endif /// Builds a watch from its source, and optionally the state it owns, its executor and its mutator (BasicWF::watch). template [[nodiscard]] std::shared_ptr makeWatch(std::string name, @@ -784,6 +842,9 @@ template close(); domDocuments.clear(); std::map released; - std::scoped_lock lock{linksMutex}; - released.swap(webLinks); + { + std::scoped_lock lock{linksMutex}; + released.swap(webLinks); + } + // Their closure is not reported during shutdown: what the inspectors kept for them is freed here. + for (const auto& [id, connection] : released) + forgetInspectorSession(connection.generation); } /// The type-erased handler of a C++ function, as cppFunction registers it. diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 07e9d487..d0acfb33 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -28,7 +28,7 @@ "js/developer/environment/inspector.mjs": "3fb29ac2f6f268bfa125d66dbbaddd68115e2f497b3f4f15de36b45e1d5aba7e", "js/developer/environment/inspector-packages.mjs": "1c3f6350780b841784f83bc20ead2945157c48a1f136c47e3a7a90d89bea8522", "js/developer/environment/inspector-registry.mjs": "bdddca4f710567b9c5030a741ed96ca6b79ebbd080da6e0bb3336e91bb1f7b39", - "js/developer/environment/inspector-watches.mjs": "a14d66c7adeba40f3ecee6b096dcac815fee9ef4a2320f757147a125603302be", + "js/developer/environment/inspector-watches.mjs": "530ba2c9bb92deb863fbb201e59578c530908be5a108d168840dbe05d286bffd", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", diff --git a/js/developer/environment/inspector-watches.mjs b/js/developer/environment/inspector-watches.mjs index 5878c517..84853de0 100644 --- a/js/developer/environment/inspector-watches.mjs +++ b/js/developer/environment/inspector-watches.mjs @@ -289,14 +289,17 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () * was not. A text longer than the bound is refused here, without a call. After a `stale` refusal the node is read again. * `expected` is the value the user saw when the edition began; without it, the value the tree holds now. A pass may * have refreshed the tree since: C++ must compare the object with what was displayed, not with what was read last. + * `shown` (tree.shown(path) when the edition began) is checked again just before the write is sent. */ - write(path, text, expected = undefined) { + write(path, text, expected = undefined, shown = undefined) { const bound = writeBound(limits, maxMessageBytes); if (utf8Bytes(text) > bound) return Promise.resolve({code: codes.tooLarge, message: `The text is longer than ${bound} bytes`}); return enqueue(async () => { const entry = nodes.get(path); if (!entry) return {code: codes.unknown, message: 'The node is no longer shown'}; + // A pass answered while the write waited may have changed what the edition was started on. + if (shown !== undefined && tree.shown(path) !== shown) return {code: codes.stale, message: ''}; let answer; try { answer = await call(functions.write)(watch, revision, path, expected ?? entry.node.value, text); } catch (error) { @@ -424,7 +427,7 @@ export function createTreeView({tree, list, view = globalThis}) { render(); return; } - const answer = await tree.write(path, text, expected).catch(error => ({code: error?.code ?? 'webfront.error', message: error?.message ?? String(error)})); + const answer = await tree.write(path, text, expected, shown).catch(error => ({code: error?.code ?? 'webfront.error', message: error?.message ?? String(error)})); if (answer.code) notes.set(path, writeFailure(answer)); render(); } diff --git a/test/developer/specs/inspector-watches-specs.mjs b/test/developer/specs/inspector-watches-specs.mjs index 827a3f46..514695fc 100644 --- a/test/developer/specs/inspector-watches-specs.mjs +++ b/test/developer/specs/inspector-watches-specs.mjs @@ -293,6 +293,21 @@ describe('The tree of a watch', () => { expect((await tree.write('/#1', 'B')).code).toBe(''); }); + it('checks what the edition was started on just before it sends the write', async () => { + const bridge = fakeWatch(['a', 'b']); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + const shown = tree.shown('/#1'); + const release = bridge.hold(functions.fold); + const folding = tree.collapse('/#0'); // the write waits behind it + const writing = tree.write('/#1', 'B', 'b', shown); + tree.nodes.get('/#1').node.label = 'another'; // what a pass answered meanwhile would change + release(); + await folding; + expect((await writing).code).toBe(codes.stale); + expect(bridge.calls.some(([name]) => name === functions.write)).toBeFalse(); + }); + it('refuses in the page, without a call, a text longer than the bound', async () => { const bridge = fakeWatch(['a']); const tree = createWatchTree({bridge, watch: 1}); diff --git a/test/unit/WatchTreeTests.cpp b/test/unit/WatchTreeTests.cpp index 42a6934c..66c5f335 100644 --- a/test/unit/WatchTreeTests.cpp +++ b/test/unit/WatchTreeTests.cpp @@ -27,6 +27,31 @@ using namespace webfront; namespace watch_tree { using namespace watch_fixture; +/// An element of a keyed source, with values of its own. +struct KeyedItem { + std::string key; + std::vector values; +}; +struct KeyedItems { + std::vector items; + [[nodiscard]] std::size_t size() const { + return items.size(); + } + void visit(std::size_t first, std::size_t count, auto&& each) { + for (std::size_t index = first; index < items.size() && index - first < count; ++index) + each(items[index].values); + } + [[nodiscard]] std::string key(std::size_t position) const { + return items.at(position).key; + } + [[nodiscard]] std::optional find(std::string_view wanted) const { + for (std::size_t index = 0; index < items.size(); ++index) + if (items[index].key == wanted) + return index; + return std::nullopt; + } +}; + struct Point { int x = 0; int y = 0; @@ -743,6 +768,20 @@ const Scenario watchListsStayCoherent{"A list of children is read on one state, } while (start != 0); requireEqual(read, std::vector{"x", "a", "b", "c", "d"}); }); + then("with keys, a later page that brings back a key already served at another position starts the list again", [&] { + Keyed root; + for (const auto* name : {"a", "b", "c", "d"}) + root.items.push_back(Keyed{.name = name, .text = name, .items = {}, .keyFails = false, .visits = 0}); + const auto id = bench.watch("swapped", visiting(root)); + auto page = bench.open(id, 2); + requireEqual(pathsOf(page), std::vector{"", "/ka", "/kb"}); + std::swap(root.items[0], root.items[2]); // c, b, a, d: the size and the place of b are kept + page = bench.children(id, "", revisionOf(page), 2, 2); + requireEqual(nodesOf(page).size(), std::size_t{1}); + requireEqual(flagsOf(nodesOf(page).front()), flag::childrenChanged); + page = bench.children(id, "", revisionOf(page), 0, 10); + requireEqual(pathsOf(page), std::vector{"", "/kc", "/kb", "/ka", "/kd"}); + }); then("with keys, an insertion that keeps the number of children is seen by the key of the last child served", [&] { Keyed root; for (const auto* name : {"a", "b", "c", "d"}) @@ -821,6 +860,25 @@ const Scenario watchKeys{ requireEqual(rows.rows[1].value, 2); requireEqual(rows.rows[4].value, 5); }); + then("under an element told by its position, every descendant is read-only, keyed or not", [&] { + KeyedItems items{ + .items = {{std::string(inspect::maxKeyBytes + 1, 'k'), {1, 2}}, {"short", {3}}} + }; + const auto id = bench.watch("items", visiting(items)); + auto page = bench.open(id); + requireEqual(pathsOf(page), std::vector({"", "/#0", "/kshort"})); + page = bench.children(id, "/#0", revisionOf(page)); + requireEqual(pathsOf(page), std::vector({"/#0", "/#0/#0", "/#0/#1"})); + checkEqual(flagsOf(nodesOf(page)[1]), 0u); + checkEqual(flagsOf(nodesOf(page)[2]), 0u); + requireEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "/#0/#1", "2", "9"); + }), + std::string{code::readOnly}); + // A branch whose whole path is keyed stays writable. + page = bench.children(id, "/kshort", revisionOf(page)); + checkEqual(flagsOf(nodesOf(page)[1]), flag::writable); + }); then("a key that find() resolves to an element with another key is a node removed", [&] { struct Lying : Keyed { [[nodiscard]] std::optional find(std::string_view) const { diff --git a/test/unit/WatchWriteTests.cpp b/test/unit/WatchWriteTests.cpp index 5c67195c..44ce21ad 100644 --- a/test/unit/WatchWriteTests.cpp +++ b/test/unit/WatchWriteTests.cpp @@ -27,6 +27,36 @@ using namespace std::chrono_literals; namespace watch_write { using namespace watch_fixture; +/// A paged source that tells whether it is walking its elements. +struct WalkedRows { + std::vector values{1, 2, 3}; + bool visiting = false; + [[nodiscard]] std::size_t size() const { + return values.size(); + } + void visit(std::size_t first, std::size_t count, auto&& each) { + visiting = true; + for (std::size_t index = first; index < values.size() && index - first < count; ++index) + each(values[index]); + visiting = false; + } +}; + +/// A paged source that fails once it gave the elements asked. +struct FailingRows { + std::vector values{1, 2, 3}; + bool failAfter = false; + [[nodiscard]] std::size_t size() const { + return values.size(); + } + void visit(std::size_t first, std::size_t count, auto&& each) { + for (std::size_t index = first; index < values.size() && index - first < count; ++index) + each(values[index]); + if (failAfter) + throw std::runtime_error("after the element"); + } +}; + struct Player { std::string name; int score = 0; @@ -35,6 +65,10 @@ struct Game { forms_fixture::Settings settings; int turn = 0; }; +/// A field whose upper bound is 2^53, where a double no longer tells two neighbouring integers apart. +struct Big { + long long value = 0; +}; /// A keyed paged source of scores. struct Scores { @@ -85,6 +119,15 @@ struct Gate { } }; +/// Opens a gate when it goes: declared after the futures that wait for the gate, it is destroyed before them, so that a +/// failed assertion does not leave their destructors waiting for an operation held behind it. +struct Opening { + Gate& gate; + ~Opening() { + gate.release(); + } +}; + using Small = http::CustomBuffersPolicy<8192, 8192, 32768, 8192>; /// A thread that runs a loop, as the thread that owns an object does: the executor of a watch. @@ -110,6 +153,12 @@ Result await(ResultTask task) { } } // namespace watch_write +template <> +struct webfront::inspect::Described { + static webfront::forms::Description description() { + return {.name = "Big", .fields = {webfront::forms::field("value", &watch_write::Big::value, "Value", webfront::forms::Bounds{0, 9007199254740992.0})}}; + } +}; template <> struct webfront::inspect::Described { static webfront::forms::Description description() { @@ -336,6 +385,28 @@ const Scenario watchMutators{ require(values.empty()); require(!resyncOf(bench.changes(id, std::get<0>(answer)))); }); + then("the mutator is called once the walk is over, outside the visit of a paged source", [&] { + WalkedRows rows; + bool inVisit = true; + const auto id = bench.watch("rows", visiting(rows), [&](WalkedRows& object, std::string_view, std::string_view) { + inVisit = object.visiting; + object.values.clear(); // would invalidate the walk if it were still running + }); + const auto page = bench.open(id); + const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "5"); + requireEqual(std::get<1>(answer), std::string{}); + require(!inVisit); + require(rows.values.empty()); + }); + then("a paged source that fails after it gave the element written does not make the write stale", [&] { + FailingRows rows; + const auto id = bench.watch("rows", visiting(rows)); + const auto page = bench.open(id); + rows.failAfter = true; + const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "20"); + requireEqual(std::get<1>(answer), std::string{}); + requireEqual(rows.values[1], 20); + }); then("a text that is not a value of a described field is refused before the mutator is called", [&] { Game game; int calls = 0; @@ -352,6 +423,22 @@ const Scenario watchMutators{ requireEqual(std::get<1>(bench.write(id, revisionOf(page), "/.0", "0", "42")), std::string{}); requireEqual(calls, 1); }); + then("a whole number is compared exactly with the bounds of its field", [&] { + Big big; + int calls = 0; + const auto id = bench.watch("big", visiting(big), [&](Big&, std::string_view, std::string_view) { + ++calls; + }); + const auto page = bench.open(id); + // 2^53 + 1 rounds onto 2^53 as a double: it must still be refused. + requireEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "/.0", "0", "9007199254740993"); + }), + std::string{code::parse}); + requireEqual(calls, 0); + requireEqual(std::get<1>(bench.write(id, revisionOf(page), "/.0", "0", "9007199254740992")), std::string{}); + requireEqual(calls, 1); + }); then("a message of 1 MiB is cut to 256 bytes on a character, and the answer fits the smallest budget", [&] { // 254 bytes then characters of 3 bytes: the first of them straddles the bound. std::string message(254, 'm'); @@ -452,6 +539,34 @@ const Scenario watchRegistrations{ requireEqual(value, 1); requireEqual(nodesOf(bench.open(second)).size(), std::size_t{1}); }); + then("a watch removed during the reading of a value publishes no snapshot, and keeps no memory", [&] { + struct State { + std::string text = std::string(20'000, 't'); + inspect::Watch handle; + bool drop = false; + }; + auto state = std::make_shared(); + const auto id = bench.owning("text", state, [](State& owned, Visit visit) { + visit(owned.text); + if (owned.drop) + owned.handle.reset(); // removed once the value is formatted, before it is published + }); + state->handle = inspect::Watch{bench.registry, id}; + static_cast(bench.open(id)); + // Another watch's snapshot, which the removed one must not replace. + std::string other(100'000, 'o'); // several fragments: the reading goes on after the removal + const auto second = bench.watch("other", visiting(other)); + static_cast(bench.open(second)); + const auto kept = bench.value(second, ""); + state->drop = true; + requireEqual(codeOf([&] { + return bench.value(id, ""); + }), + std::string{code::unknown}); + require(bench.session->find(id) == nullptr); + require(std::get<2>(kept) > 0.0); // the reading of the other watch has fragments left + requireEqual(std::get<0>(bench.value(second, "", std::get<4>(kept), std::get<2>(kept))).front(), 'o'); + }); then("removing a watch frees its memories and its snapshot, for every connection", [&] { std::string text(20'000, 't'); bench.limits.responseBudget = inspect::minPageBytes; @@ -503,6 +618,7 @@ const Scenario watchDestruction{"Destroying a watch's handle waits for an operat bench.registry->remove(id); // outside the lock of the source removed = true; }); + const Opening opening{gate}; std::this_thread::sleep_for(50ms); require(!removed); // the operation still reads the application's objects gate.release(); @@ -526,9 +642,10 @@ const Scenario watchDestruction{"Destroying a watch's handle waits for an operat }); }); gate.waitInside(); - auto removing = std::async(std::launch::async, [&] { + auto removing = std::async(std::launch::async, [&] { bench.registry->remove(id); }); + const Opening opening{gate}; requireEventually([&] { return bench.diagnosticCount() == 1; }); From 0551f647809b5bf20a1d12beae2424f68f5d16be Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:37:08 +0100 Subject: [PATCH 14/14] Watches: answer the review of #704 on the watches (#682) - The removal of a watch closes its admission in the section that erases it from the registry: no operation starts once the registry tells it is gone. - A source is read as the object it gives: a PagedSource with a non-constant visit, returned by an accessor without executor, shows its elements; writes stay governed by access.writable. - A diagnostic that fails does not replace the answer of an applied write. - A write leaves the memory as the inspector was sent it: the next pass, or a reading of the node, tells the value the object holds, also when a mutator stores another one than the text. - An integer field takes exactly a whole number: the text is read digit by digit, never rounded through a double ("1.00000000000000001" is refused). - The inspector reads nothing once a tree is stopped, keeps a write that C++ confirmed when only its reading again fails, and does not load again by itself a window that failed. - Tests: each refusal of an unadmitted page is checked on its own answer; the removal is awaited through the registry instead of a delay; the two calls queued on an executor no longer depend on the order of their threads. --- docs/WATCHES.md | 3 + ...-inspecteurs-de-l-etat-de-l-application.md | 5 ++ include/webfront/WatchMemory.hpp | 22 +++-- include/webfront/WatchValues.hpp | 71 +++++++++++++--- include/webfront/Watches.hpp | 8 +- js/developer/environment/bundles.json | 2 +- .../environment/inspector-watches.mjs | 34 ++++++-- .../specs/inspector-watches-specs.mjs | 65 +++++++++++++++ test/unit/ViewAssociationTests.cpp | 38 ++++++--- test/unit/WatchPassTests.cpp | 2 +- test/unit/WatchTreeTests.cpp | 11 +++ test/unit/WatchWriteTests.cpp | 81 +++++++++++++++---- test/web/suite/specs/inspector-specs.mjs | 6 +- 13 files changed, 290 insertions(+), 58 deletions(-) diff --git a/docs/WATCHES.md b/docs/WATCHES.md index 5ae9bb09..1a8e8f54 100644 --- a/docs/WATCHES.md +++ b/docs/WATCHES.md @@ -150,6 +150,9 @@ each of its ancestors** still show it (label, value, number of children); otherw object is left as it is, and the panel reads the node again. It is a compare-and-swap on what you saw. It cannot tell two elements without keys that look the same in every visible way: give such a container keys when the identity matters. +The answer of a write carries no value, and the inspector's memory keeps what it was sent: the next pass, or a reading of +the node, tells the value the object holds, also when a mutator stored another value than the text. + To keep an invariant, pass a mutator, which replaces the assignment and throws to refuse: ```cpp 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 791a61fa..d7840ffd 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 @@ -662,6 +662,11 @@ les sections 3 à 6 laissaient ouvert : des formes ordinaires est acceptée aussi, quand elle ne capture rien que l'état ne garde vivant. - **Mutateur.** `mutate(T& objet, std::string_view chemin, std::string_view texte)` : le texte a déjà été analysé pour le genre du nœud, et le mutateur lève une exception pour refuser. Le chemin se décode par `inspect::parsePath`. +- **Mémoire après une écriture.** Une écriture appliquée ne change pas la mémoire : la réponse ne porte pas de valeur, et + l'objet peut tenir une autre valeur que le texte (un mutateur qui l'ajuste). La passe suivante, ou une relecture du + nœud, transmet la valeur que l'objet tient ; l'inspecteur relit le nœud après chaque écriture. +- **Entiers décrits.** Un champ entier n'accepte qu'un texte qui écrit exactement un entier (`1.0`, `1e1`, `2.50e1`) : + il est analysé chiffre à chiffre, jamais arrondi par un `double`, puis comparé exactement aux bornes. - **Champs décrits.** Le texte d'un champ est validé sans l'objet autant que la description le dit (genre, bornes, choix) ; le type du membre, que seul son accesseur connaît, est vérifié à l'écriture, dont le refus résout la Promise avec `webfront.inspector.refused`. La lecture d'un champ passe par son accesseur, qui copie un membre texte en entier : la diff --git a/include/webfront/WatchMemory.hpp b/include/webfront/WatchMemory.hpp index dd589b4e..8b223861 100644 --- a/include/webfront/WatchMemory.hpp +++ b/include/webfront/WatchMemory.hpp @@ -221,8 +221,12 @@ void enter(Access& access, Use&& use) { const auto failure = [&](std::string_view what) { if (!entered) throw std::runtime_error("The watch's source failed: " + boundedText(what, maxTextBytes - 32)); - if (access.diagnose) - access.diagnose("The source of the watch '" + access.label + "' threw after its visit: " + boundedText(what)); + // The operation is done, a write may be applied: a diagnostic that fails does not replace its answer. + try { + if (access.diagnose) + access.diagnose("The source of the watch '" + access.label + "' threw after its visit: " + boundedText(what)); + } catch (...) { // NOLINT(bugprone-empty-catch): a diagnostic is not worth losing the answer + } }; try { if (!access.open) @@ -411,8 +415,6 @@ class Memory { code = inspect::code::refused; message = "The application refused the value"; } - if (applied) - store(entry, render(view, std::string(at), positional, access.writable)); return true; }); if (whole && reached && access.mutate) { @@ -427,15 +429,9 @@ class Memory { message = "The application refused the value"; } } - // A mutator may have done anything to the object: nothing read before it is used again. - if (applied && access.mutate) - static_cast(descend(rootView(access, root), segments, 0, false, [&](std::size_t level, const ChildView& view, bool positional) { - if (level != segments.size()) - return true; - if (const auto found = nodes.find(path); found != nodes.end()) - store(found->second, render(view, std::string(path), positional, access.writable)); - return true; - })); + // The memory keeps what the inspector was sent: the answer carries no value, and the object may hold another one + // than the text (a mutator that adjusts it, a member that normalizes it). The next pass, or a reading of the + // node, tells the value it holds now. // A source that fails after the value was assigned (a paged source that throws once it gave the element) does // not make the write stale: it was applied. if ((!whole || !reached) && !applied) diff --git a/include/webfront/WatchValues.hpp b/include/webfront/WatchValues.hpp index 34feba66..578a786d 100644 --- a/include/webfront/WatchValues.hpp +++ b/include/webfront/WatchValues.hpp @@ -653,6 +653,51 @@ template } /// The description of T, built once. +/** + * The integer a decimal text writes exactly, in its plain form ("-12" for "-1.2e1", "1" for "1.0"), or nothing when the text + * is no number or not a whole one: the digits are moved by the exponent, never rounded through a double. + */ +[[nodiscard]] inline std::optional exactInteger(std::string_view text) { + std::size_t at = 0; + const bool negative = at < text.size() && (text[at] == '-' || text[at] == '+') ? text[at++] == '-' : false; + std::string digits; + long long point = -1; + for (; at < text.size() && ((text[at] >= '0' && text[at] <= '9') || text[at] == '.'); ++at) { + if (text[at] == '.') { + if (point >= 0) + return std::nullopt; + point = static_cast(digits.size()); + } else + digits += text[at]; + } + if (digits.empty()) + return std::nullopt; + if (point < 0) + point = static_cast(digits.size()); + long long exponent = 0; + if (at < text.size() && (text[at] == 'e' || text[at] == 'E')) { + const auto [end, + error] = std::from_chars(text.data() + at + 1 + (text.size() > at + 1 && text[at + 1] == '+' ? 1 : 0), text.data() + text.size(), exponent); + if (error != std::errc{} || end != text.data() + text.size() || exponent < -4096 || exponent > 4096) + return std::nullopt; + at = text.size(); + } + if (at != text.size()) + return std::nullopt; + const long long whole = point + exponent; // the number of digits before the point + if (whole < 0) + return digits.find_first_not_of('0') == std::string::npos ? std::optional{"0"} : std::nullopt; + if (static_cast(whole) < digits.size()) { + if (digits.find_first_not_of('0', static_cast(whole)) != std::string::npos) + return std::nullopt; // a fraction that is not zero + digits.resize(static_cast(whole)); + } else + digits.append(static_cast(whole) - digits.size(), '0'); + const auto first = digits.find_first_not_of('0'); + digits = first == std::string::npos ? std::string{"0"} : digits.substr(first); + return digits == "0" || !negative ? digits : '-' + digits; +} + template [[nodiscard]] const forms::Description& descriptionOf() { static const forms::Description description = [] { @@ -705,21 +750,27 @@ struct FieldRender { case forms::Kind::integer: case forms::Kind::number: { const auto number = forms::detail::parseFloating(text); - // A text the double parser refuses may still be a whole number beyond 2^53: it is one when the whole - // text is read without an error (an empty text and a number too large both stop at its end, with one). - const auto wholeAs = [text](auto parsed) -> std::optional { - const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), parsed); - if (error == std::errc{} && end == text.data() + text.size()) + // An integer field takes exactly a whole number: "1.0" and "1e0" are, "1.00000000000000001" is not, + // although a double reads it as 1. + const auto plain = described->kind == forms::Kind::integer ? exactInteger(text) : std::nullopt; + if (described->kind == forms::Kind::integer && !plain) + throw ParseError("Not a whole number"); + // A whole number is read exactly, also beyond 2^53 where a double no longer tells neighbours apart: it + // is one when the whole text is read without an error (an empty text, a number too large, stop with one). + const auto exactText = plain ? std::string_view{*plain} : text; + const auto exactAs = [exactText](auto parsed) -> std::optional { + const auto [end, error] = std::from_chars(exactText.data(), exactText.data() + exactText.size(), parsed); + if (error == std::errc{} && end == exactText.data() + exactText.size()) return parsed; return std::nullopt; }; - const auto signedWhole = wholeAs(0LL); - const auto bigWhole = signedWhole ? std::nullopt : wholeAs(0ULL); - const bool exact = signedWhole || bigWhole; + const auto signedWhole = exactAs(0LL); + const auto bigWhole = signedWhole ? std::nullopt : exactAs(0ULL); + if (described->kind == forms::Kind::integer && !signedWhole && !bigWhole) + throw ParseError("Out of the range of a whole number"); + const bool exact = signedWhole || bigWhole; if (!number && !exact) throw ParseError("Not a number"); - if (described->kind == forms::Kind::integer && !exact && std::trunc(*number) != *number) - throw ParseError("Not a whole number"); if (described->range) { // A whole number is compared exactly: as a double, 2^53 + 1 would round onto a bound of 2^53. const bool inside = signedWhole ? forms::detail::atLeast(*signedWhole, described->range->min) diff --git a/include/webfront/Watches.hpp b/include/webfront/Watches.hpp index 03ed3d79..49edf770 100644 --- a/include/webfront/Watches.hpp +++ b/include/webfront/Watches.hpp @@ -334,6 +334,10 @@ class WatchRegistry { core = std::move(found->second); entries.erase(found); ++currentRevision; + // Closed in the same section as the erasure: an operation that found the watch before cannot start once the + // registry tells it is gone. + std::scoped_lock closing{core->lifecycle}; + core->removed = true; } retire(*core); std::vector> open; @@ -796,7 +800,9 @@ template && (Shape::visitor || (detail::returnsReference() && hasExecutor)); - using Root = std::conditional_t; + // The object is read as what it is: a source of non-constant elements keeps the operations that only a non-constant + // object offers (a PagedSource's visit). Whether a value may be written is told by access.writable alone. + using Root = Object; auto core = std::make_shared(); core->name = std::move(name); diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index d0acfb33..8f040d1f 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -28,7 +28,7 @@ "js/developer/environment/inspector.mjs": "3fb29ac2f6f268bfa125d66dbbaddd68115e2f497b3f4f15de36b45e1d5aba7e", "js/developer/environment/inspector-packages.mjs": "1c3f6350780b841784f83bc20ead2945157c48a1f136c47e3a7a90d89bea8522", "js/developer/environment/inspector-registry.mjs": "bdddca4f710567b9c5030a741ed96ca6b79ebbd080da6e0bb3336e91bb1f7b39", - "js/developer/environment/inspector-watches.mjs": "530ba2c9bb92deb863fbb201e59578c530908be5a108d168840dbe05d286bffd", + "js/developer/environment/inspector-watches.mjs": "e116bbeac792d6d4ee4c1bd469520e61a92cffdb7805070c4833a348e13d572f", "js/developer/environment/inspector.html": "66bfb80d6bd29bc9aabf71e0dd9b163dfcd1f1c77d1a41818645af1a4f9b8616", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", diff --git a/js/developer/environment/inspector-watches.mjs b/js/developer/environment/inspector-watches.mjs index 84853de0..7b260871 100644 --- a/js/developer/environment/inspector-watches.mjs +++ b/js/developer/environment/inspector-watches.mjs @@ -144,11 +144,13 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () async function resynchronize(answered) { revision = answered; nodes.clear(); - await list('', 0); + if (!stopped) await list('', 0); } /** One page of the children of `path` from `start`, then the unfolded children that came back. Runs inside the queue. */ async function list(path, start) { + // A tree stopped while a call was awaited reads nothing more: it would change C++'s memory of a closed panel. + if (stopped) return; let page; try { page = readNodePage(await call(functions.children)(watch, path, revision, start, count)); } catch (error) { @@ -312,9 +314,12 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () const [answered, code, message] = answer; revision = answered; // Written or not, what the node shows now is read again: the parent of a leaf gives it with its siblings' state. - await list(path, 0); + // A reading that fails does not undo what C++ answered: the write is not to be sent again. + let refresh = ''; + try { await list(path, 0); } + catch (error) { refresh = error?.message ?? String(error); } onUpdate(); - return {code, message}; + return refresh ? {code, message, refresh} : {code, message}; }); }, /** @@ -407,6 +412,16 @@ export function createTreeView({tree, list, view = globalThis}) { return made; }; const report = work => Promise.resolve(work).catch(() => {}).finally(render); + // The windows that failed to load, by "path@from": they are loaded again only when the user asks, never as they come + // into view, which would ask again and again. + const failedLoads = new Map(); + const load = (path, from) => { + const key = `${path}@${from}`; + failedLoads.delete(key); + return Promise.resolve(tree.load(path, from)) + .catch(error => { failedLoads.set(key, error?.message ?? String(error)); }) + .finally(render); + }; function edit(path) { const entry = tree.nodes.get(path); @@ -429,6 +444,7 @@ export function createTreeView({tree, list, view = globalThis}) { } const answer = await tree.write(path, text, expected, shown).catch(error => ({code: error?.code ?? 'webfront.error', message: error?.message ?? String(error)})); if (answer.code) notes.set(path, writeFailure(answer)); + else if (answer.refresh) notes.set(path, `Written; the value could not be read again: ${answer.refresh}`); render(); } @@ -491,8 +507,12 @@ export function createTreeView({tree, list, view = globalThis}) { let expected = 0; const gap = (from, to) => { const more = element('li'); - more.append(button('more', from === to - 1 ? `[${from}] not loaded` : `[${from}] to [${to - 1}] not loaded`, - `Load the children of ${node.label} from ${from}`, () => report(tree.load(path, from)))); + const key = `${path}@${from}`; + const loader = button('more', from === to - 1 ? `[${from}] not loaded` : `[${from}] to [${to - 1}] not loaded`, + `Load the children of ${node.label} from ${from}`, () => load(path, from)); + loader.dataset.load = key; + more.append(loader); + if (failedLoads.has(key)) more.append(element('span', 'note', `could not be loaded: ${failedLoads.get(key)}`)); more.dataset.from = String(from); return more; }; @@ -518,7 +538,7 @@ export function createTreeView({tree, list, view = globalThis}) { const position = Number(input.value); if (event.key === 'Enter' && input.value !== '' && Number.isSafeInteger(position) && position >= 0 && position < node.children) { positions.delete(path); - report(tree.load(path, position)); + load(path, position); } }); jump.dataset.jump = path; @@ -555,7 +575,7 @@ export function createTreeView({tree, list, view = globalThis}) { observer?.disconnect(); observer = new view.IntersectionObserver(entries => { for (const entry of entries) - if (entry.isIntersecting && !tree.busy) entry.target.click(); + if (entry.isIntersecting && !tree.busy && !failedLoads.has(entry.target.dataset.load)) entry.target.click(); }); for (const more of list.querySelectorAll('button.more')) observer.observe(more); } diff --git a/test/developer/specs/inspector-watches-specs.mjs b/test/developer/specs/inspector-watches-specs.mjs index 514695fc..68cd14e2 100644 --- a/test/developer/specs/inspector-watches-specs.mjs +++ b/test/developer/specs/inspector-watches-specs.mjs @@ -376,6 +376,37 @@ describe('The tree of a watch', () => { await folding; }); + it('reads nothing more once it is stopped, also when a pass answers a resynchronization', async () => { + const bridge = fakeWatch(['a', 'b']); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + bridge.answers[functions.reset](); // C++'s memory moved: the next pass resynchronizes + const release = bridge.hold(functions.changes); + const passing = tree.refresh(); + await Promise.resolve(); + tree.stop(); // the panel closes while the pass is awaited + const before = bridge.calls.length; + release(); + await passing; + expect(bridge.calls.slice(before).some(([name]) => name === functions.children)).toBeFalse(); + }); + + it('keeps a write that C++ confirmed when only the reading again fails', async () => { + const values = ['a', 'b']; + const bridge = fakeWatch(values); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + const children = bridge.answers[functions.children]; + bridge.answers[functions.write] = (...args) => { + bridge.answers[functions.children] = () => { throw Object.assign(new Error('the executor has no loop'), {code: codes.unavailable}); }; + return [bridge.revision + 1, '', '']; + }; + const answer = await tree.write('/#1', 'B'); + expect(answer.code).toBe(''); + expect(answer.refresh).toContain('no loop'); + bridge.answers[functions.children] = children; + }); + it('tells once that its watch is gone, and sends nothing more', async () => { const bridge = fakeWatch(['a']); let gone = 0; @@ -514,6 +545,40 @@ describe('The view of a tree', () => { expect(list.querySelector('input.position').value).toBe(''); }); + it('does not load again by itself a window that failed: the user asks for it', async () => { + const bridge = fakeWatch(Array.from({length: 7}, (unused, index) => `v${index}`), {pageSize: 3}); + const list = document.createElement('ul'); + document.body.append(list); + const observed = []; + class FakeObserver { + constructor(callback) { this.callback = callback; observed.push(this); this.targets = []; } + observe(target) { this.targets.push(target); } + disconnect() { this.targets = []; } + fire() { this.callback(this.targets.map(target => ({target, isIntersecting: true}))); } + } + let shown = null; + const tree = createWatchTree({bridge, watch: 1, onUpdate: () => shown?.render()}); + shown = createTreeView({tree, list, view: {IntersectionObserver: FakeObserver}}); + await tree.open(); + const children = bridge.answers[functions.children]; + let refused = 0; + bridge.answers[functions.children] = () => { ++refused; throw Object.assign(new Error('the executor has no loop'), {code: codes.unavailable}); }; + observed.at(-1).fire(); + await tree.settled(); + await new Promise(resolve => setTimeout(resolve)); + expect(refused).toBe(1); + expect(list.querySelector('button.more').parentElement.textContent).toContain('could not be loaded'); + observed.at(-1).fire(); // the window comes into view again: nothing is asked + await new Promise(resolve => setTimeout(resolve)); + expect(refused).toBe(1); + bridge.answers[functions.children] = children; + list.querySelector('button.more').click(); // the user asks + await tree.settled(); + await new Promise(resolve => setTimeout(resolve)); + expect(tree.nodes.has('/#3')).toBeTrue(); + list.remove(); + }); + it('says why a write was not applied, beside the node', async () => { const {list, tree, view} = await shown(['a']); view.edit('/#0'); diff --git a/test/unit/ViewAssociationTests.cpp b/test/unit/ViewAssociationTests.cpp index 2ea9e58d..63ef571a 100644 --- a/test/unit/ViewAssociationTests.cpp +++ b/test/unit/ViewAssociationTests.cpp @@ -662,15 +662,35 @@ const Scenario inspectorTreeAccess{ auto watch = browser.app.watch("grid", visitor); const auto id = static_cast(watch.id()); then("every function of the trees is refused as denied, and nothing is read or written", [&] { - callWithoutArgument("webfront.inspector.limits", 10); - callWith("webfront.inspector.reset", 11, id); - callWith("webfront.inspector.children", 12, id, std::string{}, 2.0, 0.0, 200.0); - callWith("webfront.inspector.changes", 13, id, 2.0, 0.0, 200.0); - callWith("webfront.inspector.value", 14, id, std::string{}, 0.0, 0.0); - callWith("webfront.inspector.fold", 15, id, std::string{}, 2.0); - callWith("webfront.inspector.write", 16, id, 2.0, std::string{"/#1"}, std::string{"2"}, std::string{"20"}); - require(ViewSocket::wrote(inspect::code::denied)); - require(!ViewSocket::wrote("sequence")); + // Each answer on its own: one function that answered would not hide behind the refusal of another. + const auto refused = [](auto&& call) { + const auto offset = ViewSocket::writtenText().size(); + call(); + const auto answer = ViewSocket::writtenText().substr(offset); + check(answer.contains(inspect::code::denied)); + check(!answer.contains("sequence")); + }; + refused([] { + callWithoutArgument("webfront.inspector.limits", 10); + }); + refused([&] { + callWith("webfront.inspector.reset", 11, id); + }); + refused([&] { + callWith("webfront.inspector.children", 12, id, std::string{}, 2.0, 0.0, 200.0); + }); + refused([&] { + callWith("webfront.inspector.changes", 13, id, 2.0, 0.0, 200.0); + }); + refused([&] { + callWith("webfront.inspector.value", 14, id, std::string{}, 0.0, 0.0); + }); + refused([&] { + callWith("webfront.inspector.fold", 15, id, std::string{}, 2.0); + }); + refused([&] { + callWith("webfront.inspector.write", 16, id, 2.0, std::string{"/#1"}, std::string{"2"}, std::string{"20"}); + }); requireEqual(grid, std::vector({1, 2, 3})); }); }); diff --git a/test/unit/WatchPassTests.cpp b/test/unit/WatchPassTests.cpp index 8efd2230..7fd3889f 100644 --- a/test/unit/WatchPassTests.cpp +++ b/test/unit/WatchPassTests.cpp @@ -265,7 +265,7 @@ const Scenario watchPassInterrupted{ requireEqual(values[2999], 7); require(std::get<0>(answer) != revisionOf(pass)); const auto missing = finish(bench, id, bench.changes(id, std::get<0>(answer), 0, 1000)); - requireEqual(missing.size(), std::size_t{1995}); // the write is in the memory: it is not a difference + requireEqual(missing.size(), std::size_t{1996}); // the write is told by the pass, as any other change }); then("by a write whose target is in a page not served: it is compared with what the user sees, and refused as stale", [&] { changeUpTo(3000); diff --git a/test/unit/WatchTreeTests.cpp b/test/unit/WatchTreeTests.cpp index 66c5f335..724a8d8e 100644 --- a/test/unit/WatchTreeTests.cpp +++ b/test/unit/WatchTreeTests.cpp @@ -412,6 +412,17 @@ const Scenario watchSourcesRead{"A watch reads through the source the applicatio requireEqual(std::get<1>(bench.write(id, revisionOf(page), "/#5", "102", "65535")), std::string{}); requireEqual(std::get<5>(characters), 65535); }); + then("an accessor that returns a non-constant reference without executor is read as it is, and not written", [&] { + Keyed root; + for (const auto* name : {"a", "b"}) + root.items.push_back(Keyed{.name = name, .text = name, .items = {}, .keyFails = false, .visits = 0}); + const auto id = bench.watch("reference", [&]() -> Keyed& { + return root; // a PagedSource whose visit is not constant + }); + const auto page = bench.open(id); + requireEqual(pathsOf(page), std::vector({"", "/ka", "/kb"})); + checkEqual(std::get<4>(std::get<0>(bench.registry->page(0, 0, 10, 4096)).back()), false); + }); then("a paged source that gives its elements by value is read through copies", [&] { Squares squares{.count = 1000}; const auto id = bench.watch("squares", visiting(squares)); diff --git a/test/unit/WatchWriteTests.cpp b/test/unit/WatchWriteTests.cpp index 44ce21ad..5631dcce 100644 --- a/test/unit/WatchWriteTests.cpp +++ b/test/unit/WatchWriteTests.cpp @@ -189,19 +189,23 @@ const Scenario watchWrites{"A value is written only where the application allows std::get<2>(page) = std::get<0>(answer); // the inspector adopts the revision of every answer return answer; }; - then("an accepted write changes the object, the memory, and gives a new revision", [&] { + then("an accepted write changes the object, gives a new revision, and the next pass tells the value", [&] { const auto before = revisionOf(page); const auto answer = write("/#0/#1", "2", "20"); requireEqual(std::get<1>(answer), std::string{}); require(std::get<0>(answer) != before); requireEqual(std::get<0>(board)[1], 20); - require(nodesOf(bench.changes(id, std::get<0>(answer))).empty()); // the memory already holds the new value + // The memory keeps what the inspector was sent: the next pass tells the value written, as any other change. + const auto pass = bench.changes(id, std::get<0>(answer)); + requireEqual(pathsOf(pass), std::vector{"/#0/#1"}); + requireEqual(valuesOf(pass), std::vector{"20"}); }); then("each writable kind parses its own text", [&] { checkEqual(std::get<1>(write("/#1", "name", "other\nname")), std::string{}); checkEqual(std::get<1>(board), std::string{"other\nname"}); // The value now shows a control character as its picture: writing what is shown would replace it, so the node // is no longer writable. + page = bench.children(id, "/#1", revisionOf(page)); // the node read again, as the panel does checkEqual(codeOf([&] { return bench.write(id, revisionOf(page), "/#1", "other\xE2\x90\x8Aname", "x"); }), @@ -352,8 +356,10 @@ const Scenario watchMutators{ requireEqual(seenPath, std::string{"/#1"}); requireEqual(seenText, std::string{"5"}); requireEqual(values, std::vector({7, 7, 7})); - // The memory holds what the target shows now; the other nodes are found by the next pass. - requireEqual(pathsOf(bench.changes(id, std::get<0>(answer))), std::vector({"/#0", "/#2"})); + // The next pass tells what the object holds now, the target included: 7, not the text written. + const auto pass = bench.changes(id, std::get<0>(answer)); + requireEqual(pathsOf(pass), std::vector({"/#0", "/#1", "/#2"})); + requireEqual(valuesOf(pass), std::vector({"7", "7", "7"})); // The text was parsed for the node first: the mutator is not called for a text that is not a number. seenText.clear(); checkEqual(codeOf([&] { @@ -414,14 +420,54 @@ const Scenario watchMutators{ ++calls; }); const auto page = bench.open(id); - for (const std::string_view text : {"", "-", "1e", "101", "99999999999999999999999999"}) + for (const std::string_view text : {"", "-", "1e", "101", "99999999999999999999999999", "1.00000000000000001", "1e-1", "1.5"}) checkEqual(codeOf([&] { return bench.write(id, revisionOf(page), "/.0", "0", text); }), std::string{code::parse}); requireEqual(calls, 0); - requireEqual(std::get<1>(bench.write(id, revisionOf(page), "/.0", "0", "42")), std::string{}); + auto answer = bench.write(id, revisionOf(page), "/.0", "0", "42"); + requireEqual(std::get<1>(answer), std::string{}); requireEqual(calls, 1); + // The written forms of a whole number are taken, never through a rounding double. This mutator changes nothing: + // the field still shows 0, under the revision of each answer. + for (const std::string_view text : {"1.0", "1e1", "2.50e1", "0.5e1", "-0", "+7"}) { + answer = bench.write(id, std::get<0>(answer), "/.0", "0", text); + checkEqual(std::get<1>(answer), std::string{}); + } + requireEqual(calls, 7); + requireEqual(inspect::detail::exactInteger("2.50e1").value_or("none"), std::string{"25"}); + requireEqual(inspect::detail::exactInteger("-1.2e1").value_or("none"), std::string{"-12"}); + requireEqual(inspect::detail::exactInteger("1.00000000000000001").value_or("none"), std::string{"none"}); + requireEqual(inspect::detail::exactInteger("100e-2").value_or("none"), std::string{"1"}); + requireEqual(inspect::detail::exactInteger(".").value_or("none"), std::string{"none"}); + }); + then("a diagnostic that fails does not replace the answer of a write that was applied", [&] { + bench.registry->diagnostic = [](std::string_view) { + throw std::runtime_error("the diagnostics are down"); + }; + bool failAfter = false; + const auto id = bench.watch("late", [&](Visit> visit) { + visit(values); + if (failAfter) + throw std::runtime_error("after the visit"); + }); + const auto page = bench.open(id); + failAfter = true; + const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "20"); + requireEqual(std::get<1>(answer), std::string{}); + requireEqual(values[1], 20); + }); + then("a mutator that stores another value than the text: the next pass tells the one stored", [&] { + const auto id = bench.watch("values", visiting(values), [](std::vector& object, std::string_view, std::string_view text) { + object[1] = std::stoi(std::string(text)) - 5; // the application adjusts the value + }); + const auto page = bench.open(id); + const auto answer = bench.write(id, revisionOf(page), "/#1", "2", "20"); + requireEqual(std::get<1>(answer), std::string{}); + const auto pass = bench.changes(id, std::get<0>(answer)); + requireEqual(pathsOf(pass), std::vector{"/#1"}); + requireEqual(valuesOf(pass), std::vector{"15"}); }); then("a whole number is compared exactly with the bounds of its field", [&] { Big big; @@ -619,7 +665,11 @@ const Scenario watchDestruction{"Destroying a watch's handle waits for an operat removed = true; }); const Opening opening{gate}; - std::this_thread::sleep_for(50ms); + // The registry forgets the watch before it waits for the operation: once it is gone + // from the registry, the removal has begun. + requireEventually([&] { + return !bench.registry->contains(id); + }); require(!removed); // the operation still reads the application's objects gate.release(); removing.get(); @@ -798,17 +848,18 @@ const Scenario watchExecutors{"With an executor, a watch's operations run on the return await(children(revision)); }); }; - auto earlier = ask(); - std::this_thread::sleep_for(50ms); - auto later = ask(); - std::this_thread::sleep_for(50ms); + // Whichever is queued first is served first; the other one then carries a revision + // that is no longer the memory's. Nothing here depends on the order the threads ran. + auto first = ask(); + auto second = ask(); requireEqual(reads.load(), 0); // queued on the executor, not run where they were asked owner.start(); - const auto answered = earlier.get(); - const auto stale = later.get(); - require(!resyncOf(answered)); + const auto one = first.get(); + const auto other = second.get(); + require(resyncOf(one) != resyncOf(other)); + const auto& answered = resyncOf(one) ? other : one; requireEqual(nodesOf(answered).size(), std::size_t{4}); - require(resyncOf(stale)); + requireEqual(reads.load(), 1); // the stale one never reached the source }); then("an operation queued when the watch is removed is refused without calling the source", [&] { const auto revision = bench.reset(id); diff --git a/test/web/suite/specs/inspector-specs.mjs b/test/web/suite/specs/inspector-specs.mjs index 467c30ad..5d884b77 100644 --- a/test/web/suite/specs/inspector-specs.mjs +++ b/test/web/suite/specs/inspector-specs.mjs @@ -220,7 +220,11 @@ describe('The inspectors\' watches', () => { expect(refused?.code).toBe('webfront.inspector.readOnly'); const old = await inspector('write')(rows, opened, '/#4', 'row 4', 'x').then(() => null, failure => failure); expect(old?.code).toBe('webfront.inspector.stale'); - expect((await inspector('write')(rows, after, '/#3', 'écrit €', 'row 3'))[1]).toBe(''); + // The memory keeps what was sent, not what was written: the node is read again, as the panel does, before it is + // written with what it shows now. + const [[reread], , current] = await inspector('children')(rows, '/#3', after, 0, 10); + expect(reread[3]).toBe('écrit €'); + expect((await inspector('write')(rows, current, '/#3', 'écrit €', 'row 3'))[1]).toBe(''); }); it('give a full value by fragments of one snapshot, which never cut a character', async () => {