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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions include/webfront/WatchMemory.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

#include <atomic>
#include <cmath>
#include <limits>
#include <map>
#include <mutex>
#include <set>
Expand Down Expand Up @@ -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<std::uint64_t>(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());
Expand Down Expand Up @@ -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();
Expand Down
30 changes: 20 additions & 10 deletions include/webfront/WatchValues.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 <typename E>
static NodeRef child(E& element) noexcept {
if constexpr (std::is_const_v<T>)
return refOf(std::as_const(element));
else
return refOf(element);
}

static void value(const NodeRef& node, TextSink& sink) {
[[maybe_unused]] const auto& object = objectOf<const U>(node);
if constexpr (shape == Shape::boolean)
Expand Down Expand Up @@ -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<void>((one(I, std::get<I>(object)) && ...));
}
Expand All @@ -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<void>(each(child));
ChildView view = indexedChild(0, child(*alternative));
view.rank = index;
view.label = std::to_string(index);
static_cast<void>(each(view));
return true;
};
static_cast<void>((one(I, std::get_if<I>(&object)) || ...));
Expand All @@ -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) {
Expand All @@ -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<void>(each(child));
}
Expand Down
2 changes: 1 addition & 1 deletion js/developer/environment/bundles.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
29 changes: 25 additions & 4 deletions js/developer/environment/inspector-watches.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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. */
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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; });
},
/**
Expand Down Expand Up @@ -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;
}
Expand Down
60 changes: 60 additions & 0 deletions test/developer/specs/inspector-watches-specs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading