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
9 changes: 9 additions & 0 deletions docs/ASYNC_EXECUTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,15 @@ a `jsFunctionSender` completes with an error when started, and `addScript` throw
`ConnectionError`. The 16-bit identifier of a released connection is reused only
after 65,536 later connections.

A `UI` is an assignable value: it can be kept in a `std::vector` (removed with
`std::erase_if`) or a `std::optional`, and assigned. Two values are equal when they
belong to the same application and have the same `id()`. A value identifies its
connection only until that connection closes: once the identifier is reused, a value
kept after the close equals the later browser's and reaches that browser (#428 tracks
rejecting such stale values). Remove kept values in the `subscribeUIClosed` handler.
A value must not outlive its application, and assigning one is not atomic: a
container of values shared between threads needs a lock.

`app.spawn(task)` and `ui.spawn(task)` may be called from any thread while the
application object remains alive, including concurrently with stop/shutdown.
Coroutine bodies and their resumptions execute on the server context. Synchronize
Expand Down
11 changes: 11 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@
the specs cause. The trace comes from the specs only; the published environment is unchanged. `docs/TEST_TIERS.md`
explains how to follow a test live.

- Make `BasicUI` (`UI`) an assignable value type (#400): it holds a pointer to the application instead of a
reference, so it is copy- and move-assignable and usable in `std::vector` with `std::erase_if` and in
`std::optional`. It has no default constructor, so it does not satisfy `std::regular`. Two values compare equal
when they belong to the same application and have the same `id()`. The lifetime contract is unchanged: a `UI` is
valid while its application exists and must not be used, compared included, after it is destroyed. A value only
identifies its connection until that connection closes: once the identifier is reused, a value kept after the close
reaches the later browser and equals its value, so applications remove kept values in `subscribeUIClosed` (#428
tracks rejecting such stale values). `BasicWF` now declares itself non-copyable and non-movable, which the pointer
requires. The automation binding and the Jasmine session identify their browser by this equality, and assign it
instead of re-emplacing an optional. `docs/ASYNC_EXECUTION.md` describes the value semantics.

- Add awaitable DOM events (#384): `co_await node.next(name, options)` completes with the value of
the element's next event, for sequential dialogs and wizards. Starting the sender subscribes with
the flags declared then; the event unsubscribes. It completes stopped through the task's stop token,
Expand Down
39 changes: 26 additions & 13 deletions include/webfront/WebFront.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,33 +44,42 @@ using ConnectionError = std::runtime_error;

template <typename WebFront>
class BasicUI {
WebFront& webFront;
WebFront* webFront; ///< Never null: the only constructor takes a reference, and there is no default constructor.
WebLinkId webLinkId;

public:
BasicUI(WebFront& wf, WebLinkId id) : webFront(wf), webLinkId(id) {}
BasicUI(WebFront& wf, WebLinkId id) : webFront(&wf), webLinkId(id) {}

/// Identifies this browser's connection among those connected. The 16-bit identifier of a released connection
/// is only reused after 65,536 later connections.
[[nodiscard]] WebLinkId id() const noexcept {
return webLinkId;
}

/// Two values are equal when they belong to the same application and have the same id(). A value only identifies
/// its connection until that connection closes: once its identifier is reused, a value kept after the close equals
/// the later connection's and reaches that other browser (#428), so remove kept values in subscribeUIClosed. A value
/// must not outlive its application: comparing or using it afterwards reads a dangling application address, whose
/// result is meaningless. Assigning a value is not atomic: a container of values shared between threads needs a lock.
[[nodiscard]] friend bool operator==(const BasicUI& a, const BasicUI& b) noexcept {
return a.webFront == b.webFront && a.webLinkId == b.webLinkId;
}

/**
* @brief Injects a Javascript script in the client
*
* @param script
*/
void addScript(std::string_view script) const {
const auto link = webFront.findLink(webLinkId);
const auto link = webFront->findLink(webLinkId);
if (!link)
throw ConnectionError("Connection with client lost");
link->sendCommand(msg::TextCommand(msg::TxtOpcode::injectScript, script));
}

/// Queues one DOM command on the bridge context. Rejections arrive at wfDom.rejected(batchId, reason).
void sendDomBatch(const msg::DomBatch& batch) const {
const auto link = webFront.findLink(webLinkId);
const auto link = webFront->findLink(webLinkId);
if (!link) throw ConnectionError("Connection with client lost");
link->sendCommand(batch);
}
Expand All @@ -84,13 +93,13 @@ class BasicUI {
template <typename>
friend class dom::Document;
[[nodiscard]] auto domState() const {
return webFront.domState(webLinkId);
return webFront->domState(webLinkId);
}

public:
/// The frames queued for this browser and not yet written to the network; 0 once its connection is gone.
[[nodiscard]] std::size_t pendingWrites() const {
const auto link = webFront.findLink(webLinkId);
const auto link = webFront->findLink(webLinkId);
return link ? link->pendingWrites() : 0;
}

Expand All @@ -101,37 +110,37 @@ class BasicUI {
* @return JsFunction<WebFront>
*/
[[nodiscard]] JsFunction<WebFront> jsFunction(std::string_view functionName) const {
return JsFunction{functionName, webFront, webLinkId};
return JsFunction{functionName, *webFront, webLinkId};
}

template <typename R>
[[nodiscard]] JsFunction<WebFront, R> jsFunction(std::string_view functionName) const {
return JsFunction<WebFront, R>{functionName, webFront, webLinkId};
return JsFunction<WebFront, R>{functionName, *webFront, webLinkId};
}

/** @brief Starts a coroutine owned by the application; the returned handle can cancel it. */
TaskHandle spawn(Task task) const {
return webFront.spawn(std::move(task));
return webFront->spawn(std::move(task));
}

/// A sender completing once at most `limit` frames await the network for this browser, or at once when it is gone;
/// co_await propagates the task's stop token. It paces output to a browser that reads slower than it is written.
[[nodiscard]] auto writesAtMost(std::size_t limit) const {
using Link = typename decltype(webFront.findLink(webLinkId))::element_type;
return detail::WritesAtMost<Link>{webFront.findLink(webLinkId), limit};
using Link = typename decltype(webFront->findLink(webLinkId))::element_type;
return detail::WritesAtMost<Link>{webFront->findLink(webLinkId), limit};
}

/// A sender completing on the server context after the duration; see BasicWF::resumeAfter.
template <typename Rep, typename Period>
[[nodiscard]] auto resumeAfter(std::chrono::duration<Rep, Period> duration) const {
return webFront.resumeAfter(duration);
return webFront->resumeAfter(duration);
}

/// Lazy typed call; co_await propagates the receiver's stop token. Cancellation
/// stops waiting locally; a JavaScript function already dispatched keeps running.
template <typename R = void>
[[nodiscard]] JsFunctionSender<WebFront, R> jsFunctionSender(std::string_view functionName) const {
return JsFunctionSender<WebFront, R>{functionName, webFront, webLinkId};
return JsFunctionSender<WebFront, R>{functionName, *webFront, webLinkId};
}
};

Expand Down Expand Up @@ -371,6 +380,10 @@ class BasicWF {
explicit BasicWF(std::string_view port, std::filesystem::path docRoot = ".")
: BasicWF(WebFrontConfig{.address = "0.0.0.0", .port = std::string(port), .documentRoot = std::move(docRoot)}) {}

// Each UI and the server callbacks hold the application's address: it never moves.
BasicWF(const BasicWF&) = delete;
BasicWF& operator=(const BasicWF&) = delete;

/** @brief The listening port, including the OS-assigned TCPStdnet port when configured with "0". */
std::string_view port() const noexcept { return httpPort; }

Expand Down
6 changes: 3 additions & 3 deletions include/webfront/automation/Binding.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ class Binding {
bool closing = false;
void
authorize(const AppUI& ui, std::string_view sequence, std::string_view mac, std::string_view method, std::initializer_list<std::string_view> args) {
if (!browser || browser->id() != ui.id())
if (!browser || *browser != ui)
throw std::runtime_error("Automation callback belongs to another page");
pageAuthentication.authorize(sequence, mac, method, args);
}
Expand All @@ -112,7 +112,7 @@ class Binding {
std::scoped_lock lock{owned->mutex};
if (owned->browser || !channel::sameToken(token, owned->launchToken))
throw std::runtime_error("Automation window claim rejected");
owned->browser.emplace(ui);
owned->browser = ui;
owned->launchToken.clear(); // one successful claim; later connections cannot replace the selected browser
ui.addScript(owned->closing ? std::string{"window.close()"} : connectionScript(owned->pageAuthentication.secret()));
return std::string{"null"};
Expand Down Expand Up @@ -157,7 +157,7 @@ class Binding {
});
closed = app.subscribeUIClosed([owned](AppUI ui) {
std::scoped_lock lock{owned->mutex};
if (owned->browser && owned->browser->id() == ui.id())
if (owned->browser == ui)
owned->session->close("Developer window disconnected");
});
}
Expand Down
39 changes: 22 additions & 17 deletions include/webfront/testing/Jasmine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include "../WebFront.hpp"

#include <cmath>
#include <concepts>
#include <cstdint>
#include <cstdlib>
#include <filesystem>
Expand Down Expand Up @@ -163,7 +164,9 @@ inline std::string jasmineScript() {
return "const CHUNK = " + std::to_string(jasmineChunkSize) + ";\n" + std::string(jasmineScriptBody);
}

/// The state shared by the bridge callbacks of one test run. Independent of the application type so it can be tested alone.
/// The state shared by the bridge callbacks of one test run. The caller is the application's UI, compared by its
/// equality; any equality-comparable value (a bare WebLinkId by default) tests it without an application.
template <std::equality_comparable Caller = WebLinkId>
class JasmineSession {
public:
static constexpr std::size_t chunkSize = jasmineChunkSize;
Expand All @@ -172,23 +175,23 @@ class JasmineSession {
: files(std::move(contents)), report(std::move(reportPath)) {}

/// The newest page is the one under test (a reload replaces the previous connection). Returns false once finished.
bool attach(WebLinkId id) {
bool attach(const Caller& caller) {
std::scoped_lock lock{mutex};
if (completed)
return false;
if (browser && *browser != id)
if (browser && *browser != caller)
std::cerr << "Jasmine: a new page replaced the instrumented one\n";
browser = id;
browser = caller;
return true;
}

[[nodiscard]] double count(WebLinkId caller) {
[[nodiscard]] double count(const Caller& caller) {
std::scoped_lock lock{mutex};
authorize(caller);
return static_cast<double>(files.size());
}

[[nodiscard]] std::vector<std::uint8_t> read(WebLinkId caller, double index, double offset) {
[[nodiscard]] std::vector<std::uint8_t> read(const Caller& caller, double index, double offset) {
std::scoped_lock lock{mutex};
authorize(caller);
if (!std::isfinite(index) || index < 0 || index >= static_cast<double>(files.size()) || std::floor(index) != index)
Expand All @@ -200,7 +203,7 @@ class JasmineSession {
return std::vector<std::uint8_t>(part.begin(), part.end());
}

void result(WebLinkId caller, const std::string& text) {
void result(const Caller& caller, const std::string& text) {
std::scoped_lock lock{mutex};
authorize(caller);
if (completed)
Expand Down Expand Up @@ -234,14 +237,14 @@ class JasmineSession {
}

private:
void authorize(WebLinkId caller) const {
void authorize(const Caller& caller) const {
if (!browser || *browser != caller)
throw std::runtime_error("Jasmine callback belongs to another page");
}

std::vector<std::string> files;
std::filesystem::path report;
std::optional<WebLinkId> browser;
std::optional<Caller> browser;
std::mutex mutex;
bool completed = false;
int status = 1;
Expand All @@ -261,6 +264,9 @@ inline namespace jasmine_enabled {
*/
template <typename App>
class JasmineTest {
using AppUI = typename App::UI;
using Session = detail::JasmineSession<AppUI>;

public:
explicit JasmineTest(App& app) {
const auto path = detail::jasmineConfigurationPath();
Expand All @@ -270,14 +276,13 @@ class JasmineTest {
std::vector<std::string> contents;
for (const auto& file : config.files)
contents.push_back(detail::readJasmineFile(file));
session = std::make_shared<detail::JasmineSession>(std::move(contents), config.report);
using AppUI = typename App::UI;
session = std::make_shared<Session>(std::move(contents), config.report);
const auto owned = session;
app.cppFunction("webfront.testing.count", [owned](AppUI ui) { return owned->count(ui.id()); });
app.cppFunction("webfront.testing.read", [owned](AppUI ui, double index, double offset) { return owned->read(ui.id(), index, offset); });
app.cppFunction("webfront.testing.result", [owned](AppUI ui, std::string result) { owned->result(ui.id(), result); });
app.cppFunction("webfront.testing.count", [owned](AppUI ui) { return owned->count(ui); });
app.cppFunction("webfront.testing.read", [owned](AppUI ui, double index, double offset) { return owned->read(ui, index, offset); });
app.cppFunction("webfront.testing.result", [owned](AppUI ui, std::string result) { owned->result(ui, result); });
subscription = app.subscribeUIStarted([owned](AppUI ui) {
if (owned->attach(ui.id()))
if (owned->attach(ui))
ui.addScript(detail::jasmineScript());
});
}
Expand All @@ -287,8 +292,8 @@ class JasmineTest {
}

private:
std::shared_ptr<detail::JasmineSession> session;
UISubscription subscription;
std::shared_ptr<Session> session;
UISubscription subscription;
};
} // namespace jasmine_enabled
#else
Expand Down
2 changes: 1 addition & 1 deletion test/driver/WfDriver.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ class DriverBrowser {
std::scoped_lock lock{mutex};
if (browser)
return; // Commands and wf test create their own connected frames; inject only the native page.
browser.emplace(std::move(ui));
browser = std::move(ui);
browser->addScript(closing ? "window.close()" : driverScript);
}
void close() {
Expand Down
3 changes: 3 additions & 0 deletions test/unit/AutomationTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ struct BindingApp {
void addScript(std::string text) const {
scripts->push_back(std::move(text));
}
friend bool operator==(const UI& a, const UI& b) {
return a.value == b.value;
}
};
std::function<std::string(UI, std::string)> claim;
std::function<void(UI)> started, closed;
Expand Down
4 changes: 2 additions & 2 deletions test/unit/JasmineConsumerTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ struct ReportFile {
} // namespace

SCENARIO("A Jasmine session serves its files in bounded chunks to the instrumented page only") {
constexpr auto chunk = JasmineSession::chunkSize;
constexpr auto chunk = JasmineSession<>::chunkSize;
ReportFile report{"chunks"};
GIVEN("a file that is an exact multiple of the chunk size, an empty file and a short one") {
JasmineSession session{{std::string(chunk * 2, 'a'), "", "short"}, report.path};
Expand Down Expand Up @@ -120,7 +120,7 @@ SCENARIO("A Jasmine session validates and records exactly one result") {

SCENARIO("The injected script reads in the same chunk size the session serves and reports load errors") {
const auto script = webfront::testing::detail::jasmineScript();
REQUIRE(script.starts_with("const CHUNK = " + std::to_string(JasmineSession::chunkSize) + ";"));
REQUIRE(script.starts_with("const CHUNK = " + std::to_string(JasmineSession<>::chunkSize) + ";"));
REQUIRE(script.find("49152", script.find("49152") + 1) == std::string::npos); // the number appears only in the CHUNK definition
REQUIRE(script.find("failed to load") != std::string_view::npos);
}
Loading
Loading