diff --git a/include/webfront/WatchMemory.hpp b/include/webfront/WatchMemory.hpp index 8b223861..b51e0d3f 100644 --- a/include/webfront/WatchMemory.hpp +++ b/include/webfront/WatchMemory.hpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -100,6 +101,11 @@ struct Rendered { std::tie(value, cut) = visibleText(sink.text(), maxTextBytes, true); altered = !cut && value != sink.text(); count = ops.container ? ops.size(view.node) : 0; + // The number travels as a double: beyond 2^53 it would no longer be exact, and could not be read back. + // Compared in 64-bit integers, where 2^53 fits whatever the width of size_t: a 32-bit count never reaches it, and no + // shift or conversion out of range is compiled there. JavaScript's safe integers stop at 2^53 - 1. + if (static_cast(count) >= std::uint64_t{1} << 53) + throw std::length_error("more elements than a page can tell (2^53 - 1)"); } catch (const std::exception& error) { failed = true; value = exceptionValue(error.what()); @@ -637,6 +643,19 @@ class Memory { consistent = false; } } + // With keys, every element served must still be where it was: one replaced before the last one served keeps + // the number of children and the place of that last one (one call of key() per position the memory holds). + if (consistent && ops.keyed) + for (const auto& [position, loaded] : entry.positions) { + const std::string_view segment = std::string_view{loaded}.substr(path.size() + 1); + if (!segment.starts_with('k')) + continue; + const auto key = usableKey(view.node, position); + if (!key || 'k' + encodeKey(*key) != segment) { + consistent = false; + break; + } + } if (!consistent) { dropDescendants(path, nullptr); entry.positions.clear(); diff --git a/include/webfront/WatchValues.hpp b/include/webfront/WatchValues.hpp index 578a786d..e375b118 100644 --- a/include/webfront/WatchValues.hpp +++ b/include/webfront/WatchValues.hpp @@ -821,6 +821,16 @@ struct Render { return kindName(shape); } + /// The node of a child: constant under a constant object, whatever the child's own type gives (a tuple of references, + /// a container of pointers' targets), so that nothing under a read-only branch is offered to edition. + template + static NodeRef child(E& element) noexcept { + if constexpr (std::is_const_v) + return refOf(std::as_const(element)); + else + return refOf(element); + } + static void value(const NodeRef& node, TextSink& sink) { [[maybe_unused]] const auto& object = objectOf(node); if constexpr (shape == Shape::boolean) @@ -875,9 +885,9 @@ struct Render { [[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); + ChildView view = indexedChild(index, child(member)); + view.label = std::to_string(index); + return each(view); }; static_cast((one(I, std::get(object)) && ...)); } @@ -887,10 +897,10 @@ struct Render { 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)); + ChildView view = indexedChild(0, child(*alternative)); + view.rank = index; + view.label = std::to_string(index); + static_cast(each(view)); return true; }; static_cast((one(I, std::get_if(&object)) || ...)); @@ -917,9 +927,9 @@ struct Render { 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}); + return each(ChildView{.position = position, .rank = position, .node = child(item.second), .label = std::move(label), .labelCut = cut}); } else - return each(indexedChild(position, refOf(item))); + return each(indexedChild(position, child(item))); } static void visit(const NodeRef& node, std::size_t first, std::size_t count, ChildFn each) { @@ -928,7 +938,7 @@ struct Render { return; if constexpr (shape == Shape::optional) { if (first == 0 && object) { - ChildView child = indexedChild(0, refOf(*object)); + ChildView child = indexedChild(0, Render::child(*object)); child.label = "value"; static_cast(each(child)); } diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 8f040d1f..269ebce1 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": "e116bbeac792d6d4ee4c1bd469520e61a92cffdb7805070c4833a348e13d572f", + "js/developer/environment/inspector-watches.mjs": "f5b8f901b86969bfe349d0e875cce9fba375d922f95f4fb213dc2f690083175e", "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 7b260871..7f730337 100644 --- a/js/developer/environment/inspector-watches.mjs +++ b/js/developer/environment/inspector-watches.mjs @@ -81,7 +81,7 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () 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; + let revision = 0, limits = null, gone = false, stopped = false, passes = 0, problem = null, rebuilding = false; // 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; @@ -144,7 +144,11 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () async function resynchronize(answered) { revision = answered; nodes.clear(); - if (!stopped) await list('', 0); + rebuilding = true; // until the root is read again: a reading that fails is tried again at the next refresh + onUpdate(); + if (stopped) return; + await list('', 0); + rebuilding = !nodes.has(''); } /** One page of the children of `path` from `start`, then the unfolded children that came back. Runs inside the queue. */ @@ -156,7 +160,13 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () 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; } + // The memory is full, or the node too deep. A node whose children are partly loaded stays unfolded: folding it + // is what frees the memory. + if (error?.code === codes.limit) { + problem = error.message; + if (start === 0 && !nodes.get(path)?.positions.size) expanded.delete(path); + return; + } return fail(error); } if (page.resync) return resynchronize(page.revision); @@ -249,7 +259,11 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () open() { return enqueue(async () => { limits ??= readLimits(await call(functions.limits)()); + // A tree closed while it waited sends nothing more: its reset would empty the memory of a tree of the + // same watch opened since on this connection. + if (stopped) return; revision = await call(functions.reset)(watch).catch(fail); + if (stopped) return; nodes.clear(); expanded.add(''); await list('', 0); @@ -283,7 +297,10 @@ export function createWatchTree({bridge, watch, count = pageCount, 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); + if (tree.busy || gone || stopped) return Promise.resolve(false); + // A resynchronization whose reading of the root failed: the tree is built again from the root. + if (rebuilding) return enqueue(async () => { await resynchronize(revision); onUpdate(); return true; }); + if (!nodes.size) return Promise.resolve(false); return enqueue(async () => { await pass(); onUpdate(); return true; }); }, /** @@ -327,11 +344,15 @@ export function createWatchTree({bridge, watch, count = pageCount, onUpdate = () * replaced starts again, a few times at most. */ async fullValue(path, {attempts = 3} = {}) { + const closed = () => Object.assign(new Error('The tree is closed'), {code: codes.unknown}); for (let attempt = 0; ; ++attempt) { + // Before each attempt too: a fragment refused as stale after the tree was closed starts no new reading. + if (stopped) throw closed(); try { let [part, total, next, capped, snapshot] = await call(functions.value)(watch, path, 0, 0); let text = part; while (next !== 0) { + if (stopped) throw closed(); [part, total, next, capped] = await call(functions.value)(watch, path, snapshot, next); text += part; } diff --git a/test/developer/specs/inspector-watches-specs.mjs b/test/developer/specs/inspector-watches-specs.mjs index 68cd14e2..0c266a59 100644 --- a/test/developer/specs/inspector-watches-specs.mjs +++ b/test/developer/specs/inspector-watches-specs.mjs @@ -407,6 +407,66 @@ describe('The tree of a watch', () => { bridge.answers[functions.children] = children; }); + it('keeps unfolded a list whose next page the full memory refuses, so that it can be folded', async () => { + const bridge = fakeWatch(Array.from({length: 6}, (unused, index) => `v${index}`), {pageSize: 2}); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + const children = bridge.answers[functions.children]; + bridge.answers[functions.children] = () => { throw Object.assign(new Error('memory full'), {code: codes.limit}); }; + await tree.load('', 2); + expect(tree.expanded.has('')).toBeTrue(); + expect(tree.problem).toBe('memory full'); + bridge.answers[functions.children] = children; + }); + + it('builds the tree again at the next refresh when the reading of a resynchronization fails', async () => { + const bridge = fakeWatch(['a', 'b']); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + bridge.answers[functions.reset](); // the next pass answers a resynchronization + const children = bridge.answers[functions.children]; + bridge.answers[functions.children] = () => { throw Object.assign(new Error('the executor has no loop'), {code: codes.unavailable}); }; + await expectAsync(tree.refresh()).toBeRejected(); + expect(tree.nodes.size).toBe(0); + bridge.answers[functions.children] = children; + expect(await tree.refresh()).toBeTrue(); + expect([...tree.nodes.keys()]).toEqual(['', '/#0', '/#1']); + }); + + it('sends nothing more when it is closed while it opens, or while it reads a full value', async () => { + const bridge = fakeWatch(['abcdefgh']); + const opened = createWatchTree({bridge, watch: 1}); + await opened.open(); + const tree = createWatchTree({bridge, watch: 1}); + const release = bridge.hold(functions.limits); + const opening = tree.open(); + await Promise.resolve(); + tree.stop(); + const before = bridge.calls.length; + release(); + await opening.catch(() => {}); + expect(bridge.calls.slice(before).map(([name]) => name)).not.toContain(functions.reset); + const value = bridge.answers[functions.value]; + bridge.answers[functions.value] = (...args) => { opened.stop(); return value(...args); }; + await expectAsync(opened.fullValue('/#0')).toBeRejectedWithError('The tree is closed'); + }); + + it('starts no new reading of a full value once it is closed, even after a fragment refused as stale', async () => { + const bridge = fakeWatch(['abcdefgh']); + const tree = createWatchTree({bridge, watch: 1}); + await tree.open(); + const value = bridge.answers[functions.value]; + bridge.answers[functions.value] = (...args) => { + if (args[2] === 0) return value(...args); // the first fragment of an attempt + tree.stop(); // closed while the next fragment is awaited + throw Object.assign(new Error('replaced'), {code: codes.stale}); + }; + const before = bridge.calls.length; + await expectAsync(tree.fullValue('/#0')).toBeRejectedWithError('The tree is closed'); + const initial = bridge.calls.slice(before).filter(([name, , , snapshot]) => name === functions.value && snapshot === 0); + expect(initial.length).withContext('no initial request after the closure').toBe(1); + }); + it('tells once that its watch is gone, and sends nothing more', async () => { const bridge = fakeWatch(['a']); let gone = 0; diff --git a/test/unit/WatchTreeTests.cpp b/test/unit/WatchTreeTests.cpp index 724a8d8e..0d932b45 100644 --- a/test/unit/WatchTreeTests.cpp +++ b/test/unit/WatchTreeTests.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -131,6 +132,18 @@ struct Rows { } }; +/// A paged source that tells more elements than a double counts exactly, and computes none of them. +struct Endless { + std::size_t count = std::numeric_limits::max(); + [[nodiscard]] std::size_t size() const { + return count; + } + void visit(std::size_t first, std::size_t wanted, auto&& each) const { + for (std::size_t index = 0; index < wanted && index < 3; ++index) + each(first + index); + } +}; + /// A sequence of itself: as deep as wanted. struct Tree : std::vector { }; @@ -423,6 +436,44 @@ const Scenario watchSourcesRead{"A watch reads through the source the applicatio 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 tells more elements than 2^53 is shown as such, and never converted out of range", [&] { + if constexpr (std::numeric_limits::digits <= 53) + return; // a 32-bit size_t cannot tell more than 2^53 elements + // JavaScript reads a count exactly up to 2^53 - 1 (Number.isSafeInteger): from 2^53 on, refused. + for (const std::size_t count : + {std::numeric_limits::max(), static_cast(std::uint64_t{1} << 53)}) { + Endless endless{.count = count}; + const auto id = bench.watch("endless " + std::to_string(count), visiting(endless)); + const auto page = bench.open(id); + requireEqual(nodesOf(page).size(), std::size_t{1}); + requireEqual(kindOf(nodesOf(page).front()), std::string{"opaque"}); + require(valueOf(nodesOf(page).front()).contains("2^53 - 1")); + requireEqual(countOf(nodesOf(page).front()), std::size_t{0}); + } + Endless largest{.count = static_cast((std::uint64_t{1} << 53) - 1)}; + const auto id = bench.watch("largest", visiting(largest)); + const auto page = bench.open(id, 3); + requireEqual(kindOf(nodesOf(page).front()), std::string{"sequence"}); + requireEqual(std::get<4>(nodesOf(page).front()), 9007199254740991.0); + requireEqual(nodesOf(page).size(), std::size_t{4}); + }); + then("under a constant branch nothing is writable, even what a tuple of references gives", [&] { + int target = 1; + std::tuple, std::tuple> outer{std::tuple{target}, std::tuple{target}}; + const auto id = bench.watch("outer", visiting(outer)); + auto page = bench.open(id); + page = bench.children(id, "/#0", revisionOf(page)); + requireEqual(pathsOf(page), std::vector({"/#0", "/#0/#0"})); + checkEqual(flagsOf(nodesOf(page)[1]), 0u); + requireEqual(codeOf([&] { + return bench.write(id, revisionOf(page), "/#0/#0", "1", "5"); + }), + std::string{code::readOnly}); + requireEqual(target, 1); + // The same reference under a branch that is not constant stays writable. + page = bench.children(id, "/#1", revisionOf(page)); + checkEqual(flagsOf(nodesOf(page)[1]), flag::writable); + }); 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)); @@ -793,6 +844,24 @@ const Scenario watchListsStayCoherent{"A list of children is read on one state, page = bench.children(id, "", revisionOf(page), 0, 10); requireEqual(pathsOf(page), std::vector{"", "/kc", "/kb", "/ka", "/kd"}); }); + then("with keys, an element served that was replaced before the next page makes the list start 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("replaced", visiting(root)); + auto page = bench.open(id, 2); + requireEqual(pathsOf(page), std::vector{"", "/ka", "/kb"}); + root.items[0].name = "x"; // the size and the place of b are kept, no key served comes back + 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", "/kb", "/kc", "/kd"}); + // Unchanged, a list goes on where it was asked. + page = bench.children(id, "", revisionOf(page), 0, 2); + page = bench.children(id, "", revisionOf(page), 2, 2); + requireEqual(pathsOf(page), std::vector{"", "/kc", "/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"}) diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index ea9781f5..9320ddd0 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -895,26 +895,42 @@ try { // The tab's context menu (#679): its panels, the root first, and the entries of one of them. menus: () => [...page.querySelectorAll('.webfront-menu')], entries: level => [...(page.querySelectorAll('.webfront-menu')[level]?.querySelectorAll('[role=menuitem]') ?? [])], - press: (target, init) => target.dispatchEvent(new view.KeyboardEvent('keydown', {bubbles: true, cancelable: true, ...init})), - rightClick: (target, x, y) => target.dispatchEvent(new view.MouseEvent('contextmenu', {bubbles: true, cancelable: true, button: 2, clientX: x, clientY: y})), + // An absent target is a mistake of the spec, said as such: the probes below press only what is rendered. + press: (target, init) => { + if (!target) throw new Error(`press(${init?.key}): no such element in the menu`); + return target.dispatchEvent(new view.KeyboardEvent('keydown', {bubbles: true, cancelable: true, ...init})); + }, + rightClick: (target, x, y) => { + if (!target) throw new Error('rightClick: no such element'); + return target.dispatchEvent(new view.MouseEvent('contextmenu', {bubbles: true, cancelable: true, button: 2, clientX: x, clientY: y})); + }, }; }; + // Opens the submenu of `group` again: closes an open submenu, then opens the group's. False, for `until` to try again, + // while the root menu or the submenu is not (or no longer) rendered: a probe presses only what is there. + const reopenSubmenu = (layoutOf, group) => { + if (layoutOf.menus().length > 1) { + const inner = layoutOf.entries(1)[0]; + if (!inner) return false; + layoutOf.press(inner, {key: 'ArrowLeft'}); + } + const entry = layoutOf.entries(0)[group]; + if (!entry) return false; + layoutOf.press(entry, {key: 'ArrowRight'}); + return true; + }; // Opens the submenu of `group` until its entries are available: the page is admitted and the menu read its access. const availableEntries = async (layoutOf, group) => { - await until(() => { - layoutOf.menus().slice(1).forEach(() => layoutOf.press(layoutOf.entries(1)[0], {key: 'ArrowLeft'})); - layoutOf.press(layoutOf.entries(0)[group], {key: 'ArrowRight'}); - return layoutOf.entries(1).length > 0 && layoutOf.entries(1).every(entry => entry.getAttribute('aria-disabled') !== 'true'); - }, 'The inspector entries of an admitted page must be available'); + await until(() => reopenSubmenu(layoutOf, group) + && layoutOf.entries(1).length > 0 && layoutOf.entries(1).every(entry => entry.getAttribute('aria-disabled') !== 'true'), + 'The inspector entries of an admitted page must be available'); return layoutOf.entries(1); }; // Opens the submenu of `group` (1: C++ state, 2: TypeScript state) until the menu has read the page's access. const inspectorEntries = async (layoutOf, group, expected) => { - await until(() => { - layoutOf.menus().slice(1).forEach(() => layoutOf.press(layoutOf.entries(1)[0], {key: 'ArrowLeft'})); - layoutOf.press(layoutOf.entries(0)[group], {key: 'ArrowRight'}); - return expected.test(layoutOf.menus()[1]?.querySelector('.webfront-menu-reason')?.textContent ?? ''); - }, 'The inspector entries must give the reason they are unavailable'); + await until(() => reopenSubmenu(layoutOf, group) + && expected.test(layoutOf.menus()[1]?.querySelector('.webfront-menu-reason')?.textContent ?? ''), + 'The inspector entries must give the reason they are unavailable'); return layoutOf.entries(1); }; const here = layout(document);