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
46 changes: 42 additions & 4 deletions include/webfront/automation/Enable.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,38 @@
#include <type_traits>

namespace webfront::automation {
/// `from + after`, saturated: a very large duration (`seconds::max()` to disable a delay) must not overflow the clock's tick
/// count, which is undefined behavior and would yield a deadline already past. Nothing is computed that can overflow: the room
/// left before `time_point::max()` is measured in whole seconds (never more than twice the clock's range, whatever the origin,
/// negative included), `after` is compared to it without being incremented, and the sum is made in two steps when `after`
/// alone exceeds the clock's tick range while the deadline stays representable. A zero or negative duration returns `from`.
template <typename Duration>
[[nodiscard]] constexpr std::chrono::steady_clock::time_point deadlineAfter(std::chrono::steady_clock::time_point from, Duration after) noexcept {
using Clock = std::chrono::steady_clock;
using std::chrono::duration_cast;
using std::chrono::seconds;
if (after <= Duration::zero())
return from;
const auto capacity = duration_cast<seconds>(Clock::time_point::max().time_since_epoch());
const auto room = capacity - duration_cast<seconds>(from.time_since_epoch());
const auto whole = duration_cast<seconds>(after);
// One second of margin for the truncations; `room - 1` cannot overflow, `room` being at least 1.
if (whole >= room - seconds{1})
return Clock::time_point::max();
if (whole < capacity)
return from + after; // `after` converts to ticks: it is below the clock's range
// `after` exceeds the range of the ticks but the deadline does not: `from` is negative, so a first step of the largest
// whole number of `Duration` the clock can hold stays representable, then the rest.
const auto step = duration_cast<Duration>(Clock::duration::max());
return from + duration_cast<Clock::duration>(step) + (after - step);
}

/// The end of the startup window, saturated (see `deadlineAfter`).
[[nodiscard]] constexpr std::chrono::steady_clock::time_point startupDeadline(std::chrono::steady_clock::time_point launched,
std::chrono::seconds startup) noexcept {
return deadlineAfter(launched, startup);
}

struct AutomationOptions {
/// Granted operations (`check`, `build`, `test`, `preview`, `inspect`, `interact`, and the setup grants). None
/// leaves only session discovery.
Expand All @@ -46,10 +78,12 @@ struct AutomationOptions {
/// Per-operation native deadline.
std::chrono::seconds timeout{120};
/// How long the window may take to claim the session, counted from the activation: a renderer blocked before its first
/// poll has no operation for `timeout` to expire. Past it the session is revoked like a deadline.
/// poll has no operation for `timeout` to expire. Past it the session is revoked like a deadline. Must be positive;
/// `seconds::max()` disables the delay.
std::chrono::seconds startupTimeout{120};
/// After a deadline revokes the session, how long the window may take to close on its own. `window.close()` cannot run
/// in a renderer stuck in a loop, so past this grace the endpoint and record are removed and `onUnresponsive` is called.
/// Must not be negative; `milliseconds::max()` waits for the window without limit.
std::chrono::milliseconds closeGrace{5000};
/// What to do with a window that did not close. By default the process ends with status 72 (as `webfront-agent`
/// does): `show()` cannot be interrupted from another thread. Set it to close the application another way.
Expand All @@ -66,7 +100,7 @@ class Automation {
"Automation's Clock must return std::chrono::steady_clock::time_point");

public:
/// @throws std::invalid_argument for an unknown grant, an empty `listen` path, or a `listen` directory inside the project
/// @throws std::invalid_argument for an unknown grant, a non-positive `startupTimeout`, a negative `closeGrace`, an empty `listen` path, or a `listen` directory inside the project
/// @throws std::runtime_error (including std::filesystem::filesystem_error) when the endpoint or the discovery directory cannot be
/// created or is refused (an existing one that other users can read). Nothing stays registered in the application.
Automation(App& app, AutomationOptions options)
Expand All @@ -87,11 +121,11 @@ class Automation {
// A renderer in a loop never runs that request: after the grace the window is declared unresponsive.
supervisor = std::jthread([this](std::stop_token stop) {
while (!stop.stop_requested()) {
if (session->expire(Clock::now()) || session->expireStartup(launched + startup, Clock::now()))
if (session->expire(Clock::now()) || session->expireStartup(startupDeadline(launched, startup), Clock::now()))
session->close("Native automation deadline exceeded");
if (session->isClosed()) {
// The grace starts when the window is asked to close, so a closeBrowser() that blocks does not extend it.
const auto deadline = Clock::now() + grace;
const auto deadline = deadlineAfter(Clock::now(), grace);
binding.closeBrowser();
// Whatever revoked the session (a deadline, a signal, an attached client's --shutdown, the page's own failure
// report, a lost WebSocket), the window was only asked to close: a stuck renderer ignores it, and a lost
Expand Down Expand Up @@ -172,6 +206,10 @@ class Automation {
static std::shared_ptr<Session> make(App& app, const AutomationOptions& options) {
if (options.listen.empty())
throw std::invalid_argument("Automation needs a new private `listen` directory for its endpoint");
if (options.startupTimeout <= std::chrono::seconds::zero())
throw std::invalid_argument("Automation startupTimeout must be positive");
if (options.closeGrace < std::chrono::milliseconds::zero())
throw std::invalid_argument("Automation closeGrace must not be negative");
return std::make_shared<Session>(SessionOptions{.project = app.projectDirectory(), .allow = options.grants, .timeout = options.timeout, .callbacks = options.callbacks});
}
static discovery::Entry record(const Session& session, const std::filesystem::path& endpoint) {
Expand Down
87 changes: 87 additions & 0 deletions test/unit/AutomationDiscoveryTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -518,3 +518,90 @@ const Scenario defaultAutomation{"The default automation clock supervises a rend
require(automation->controller()->isClosed());
require(discovery::list(root.path() / "sessions").empty());
}};

const Scenario startupDeadlineSaturates{"A delay too large for the clock never expires, whatever the clock origin", [] {
using namespace std::chrono;
const auto now = steady_clock::now();
const auto negative = steady_clock::time_point{steady_clock::duration{-1'000'000'000'000}};
const auto limit = steady_clock::time_point::max();
given("an ordinary timeout", [&] {
then("the deadline is the origin plus the timeout, for a positive or a negative origin", [&] {
check(startupDeadline(now, seconds{30}) == now + seconds{30});
check(startupDeadline(negative, seconds{30}) == negative + seconds{30});
check(deadlineAfter(now, milliseconds{100}) == now + milliseconds{100});
});
});
given("a zero or negative delay", [&] {
then("the deadline is the origin itself", [&] {
check(startupDeadline(negative, seconds{0}) == negative);
check(startupDeadline(now, seconds{-5}) == now);
check(deadlineAfter(negative, milliseconds{-1}) == negative);
});
});
given("the largest representable delay", [&] {
then("the deadline saturates instead of overflowing into the past", [&] {
check(startupDeadline(now, seconds::max()) == limit);
check(startupDeadline(negative, seconds::max()) == limit);
check(startupDeadline(steady_clock::time_point::min(), seconds::max()) == limit);
check(deadlineAfter(now, milliseconds::max()) == limit);
check(deadlineAfter(negative, milliseconds::max()) == limit);
});
});
given("a delay beyond the clock's tick range from an origin that makes the deadline representable", [&] {
then("the deadline is exact instead of overflowing in the conversion", [&] {
if constexpr (std::is_same_v<steady_clock::duration, nanoseconds> && sizeof(steady_clock::rep) == 8) {
const auto from = steady_clock::time_point::min();
// min() + 1e10 s = -9223372036854775808 + 1e19 ticks
check(deadlineAfter(from, seconds{10'000'000'000}) == steady_clock::time_point{nanoseconds{776'627'963'145'224'192LL}});
check(deadlineAfter(from, milliseconds{10'000'000'000'000}) == steady_clock::time_point{nanoseconds{776'627'963'145'224'192LL}});
}
});
});
}};

const Scenario unboundedDelaysKeepTheSession{"Unbounded startup and grace options neither revoke the session nor end the window", [] {
SupervisorClock::reset();
webfront::test::TemporaryDirectory root;
std::filesystem::create_directory(root.path() / "project");
ConsumerApp app{.project = root.path() / "project"};
std::atomic<int> unresponsive{0};
const auto options = [&](std::chrono::seconds startup, std::chrono::milliseconds grace) {
return AutomationOptions{.grants = {"check"},
.listen = root.path() / "endpoint",
.discovery = root.path() / "sessions",
.startupTimeout = startup,
.closeGrace = grace,
.onUnresponsive =
[&] {
++unresponsive;
},
.announce = false};
};
given("a startup timeout of seconds::max()", [&] {
Automation<ConsumerApp, SupervisorClock> automation{app, options(std::chrono::seconds::max(), std::chrono::milliseconds{100})};
then("a window that never claims the session is not revoked", [&] {
advanceSupervisor(std::chrono::hours{24});
require(!automation.controller()->isClosed());
require(unresponsive.load() == 0);
});
});
given("a close grace of milliseconds::max()", [&] {
Automation<ConsumerApp, SupervisorClock> automation{app, options(std::chrono::seconds{120}, std::chrono::milliseconds::max())};
automation.controller()->close("Developer window disconnected");
awaitCloseGrace(&automation);
then("the window is never declared unresponsive", [&] {
advanceSupervisor(std::chrono::hours{24});
require(unresponsive.load() == 0);
});
});
given("a non-positive startup timeout or a negative grace", [&] {
then("the activation is refused before anything is registered", [&] {
requireThrows<std::invalid_argument>([&] {
Automation<ConsumerApp, SupervisorClock>{app, options(std::chrono::seconds{0}, std::chrono::milliseconds{100})};
});
requireThrows<std::invalid_argument>([&] {
Automation<ConsumerApp, SupervisorClock>{app, options(std::chrono::seconds{120}, std::chrono::milliseconds{-1})};
});
});
});
}};
Loading