Repository navigation
Expand file tree
/
Copy pathUIExecutor.hpp
More file actions
496 lines (450 loc) · 20 KB
/
Copy pathUIExecutor.hpp
File metadata and controls
496 lines (450 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// SPDX-License-Identifier: Apache-2.0 OR CECILL-B
// Author: Ambroise Leclerc
// Created: 2026-11-09
//
// WebFront — frontend
// Role: Execution on the interface thread of a frontend (ADR-020): a sender that completes on that thread.
// Thread: ui-loop | Alloc: unrestricted
// LLM: public contract; schedule() is callable from any thread, completion is on the interface thread (ADR-006)
// Execution on the interface thread of a frontend (ADR-020, prerequisite of the native dialogs).
//
// A frontend that owns an interface thread publishes a `UIExecutorHost`: while its loop runs, it calls `attach()` on the
// interface thread with a thread-safe `wake` function, then `drain()` each time `wake` was called, and `close()` when the
// loop ends. Everything else uses the `UIExecutor` handle, whose `schedule()` is a sender that completes on the interface
// thread (ADR-006):
// - `set_value()` on the interface thread, once the host drains it;
// - `set_stopped()` when the receiver's stop token fires before the operation started to run, or when the loop closes
// with the operation still pending: it never runs after closure;
// - `set_error(UIExecutorUnavailable)` when no loop is attached (system browser without the loop mode, loop not started
// yet, or already closed).
// An operation that started to run is never interrupted: stop requests arrive too late for it.
#pragma once
#include "../networking/Tasks.hpp"
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <exception>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <string>
#include <thread>
#include <utility>
#include <vector>
namespace webfront::frontend {
/// @brief One run of a frontend's interface loop: the thread that attached it and the attach's own number. A request meant
/// for a session is dropped, on the interface thread, if the loop that runs it is another one.
struct UISession {
std::thread::id thread;
std::uint64_t id{};
friend bool operator==(const UISession&, const UISession&) = default;
};
namespace ex = networking::ex;
/// @brief No interface-thread loop is attached: the frontend has none, it has not started or it has closed.
class UIExecutorUnavailable : public std::runtime_error {
public:
UIExecutorUnavailable() : std::runtime_error("no interface thread is available: the frontend has no running loop") { }
};
namespace detail {
/// One pending operation. The first of run / stop / close / failure to claim it completes the receiver, once.
struct UIJob {
virtual ~UIJob() = default;
virtual void run() noexcept = 0; // on the interface thread
virtual void abandon() noexcept = 0; // loop closed or stop requested: completes stopped
virtual void fail(std::exception_ptr) noexcept = 0;
};
class UIExecutorShared {
public:
enum class Phase { idle, running, closed };
/// Ends one wake-up in flight, also when the wake function throws.
struct Done {
UIExecutorShared& self;
~Done() {
std::lock_guard lock(self.mutex);
--self.wakesInFlight;
self.wakesDone.notify_all();
}
};
/// Queues `job` and wakes the loop; false (job untouched) when no loop is running. Never throws: a failure to queue
/// or to copy the wake function completes the job with that error and leaves the queue as it was.
bool enqueue(const std::shared_ptr<UIJob>& job) noexcept {
std::function<void()> wake;
try {
std::lock_guard lock(mutex);
if (phase != Phase::running)
return false;
// One notification per pass: while one is pending, the next drain() will see this job too. What can throw
// (copying the wake function, growing the queue) comes first; the state changes after it cannot fail.
if (!wakePending)
wake = wakeFunction;
queue.push_back(job);
if (wake) {
wakePending = true;
++wakesInFlight; // close() waits for it: the wake may use what the loop frees once it has closed
}
} catch (...) {
job->fail(std::current_exception());
return true;
}
if (!wake)
return true;
try {
Done done{*this};
wake();
} catch (...) {
failQueued(std::current_exception());
}
return true;
}
/// The wake that was to run the queue failed: every job queued behind it relied on that notification (they asked for
/// none of their own), so all fail with its error rather than wait for a pass that nobody requested.
void failQueued(std::exception_ptr error) noexcept {
std::deque<std::shared_ptr<UIJob>> failed;
{
std::lock_guard lock(mutex);
wakePending = false;
failed.swap(queue);
}
for (auto& job : failed)
job->fail(error);
}
void remove(const std::shared_ptr<UIJob>& job) {
std::lock_guard lock(mutex);
std::erase(queue, job);
}
void attach(std::function<void()> wake) {
std::lock_guard lock(mutex);
if (phase == Phase::running)
throw std::logic_error("UIExecutorHost::attach: a loop is already attached");
wakeFunction = std::move(wake);
wakePending = false;
uiThread = std::this_thread::get_id();
++sessions;
phase = Phase::running;
}
/// Runs the operations queued when it starts, no more: one that reschedules itself, or a producer that keeps queueing,
/// runs in a later pass so that the native loop handles its events (closing, stop requests) in between. When work
/// remains, the loop is woken again.
void drain() noexcept {
std::size_t batch{};
{
std::lock_guard lock(mutex);
wakePending = false; // from here on a new job asks for a new pass
batch = queue.size();
}
for (; batch > 0; --batch) {
std::shared_ptr<UIJob> job;
{
std::lock_guard lock(mutex);
if (queue.empty())
return;
job = std::move(queue.front());
queue.pop_front();
}
job->run();
}
std::function<void()> wake;
try {
{
std::lock_guard lock(mutex);
if (queue.empty() || phase != Phase::running || wakePending)
return; // nothing left, or a job queued meanwhile already asked for the next pass
wake = wakeFunction; // may throw: nothing has changed yet
wakePending = true;
++wakesInFlight;
}
Done done{*this};
wake();
} catch (...) {
// A wake that cannot be made or that throws fails the jobs still queued (see failQueued).
failQueued(std::current_exception());
}
}
void close() noexcept {
std::deque<std::shared_ptr<UIJob>> pending;
{
std::unique_lock lock(mutex);
phase = Phase::closed;
pending.swap(queue);
// No new wake starts (phase is closed): wait for those in flight on other threads, which only signal the loop.
wakesDone.wait(lock, [&] {
return wakesInFlight == 0;
});
wakeFunction = nullptr; // may hold the session that is ending
}
for (auto& job : pending)
job->abandon();
}
[[nodiscard]] bool running() const {
std::lock_guard lock(mutex);
return phase == Phase::running;
}
[[nodiscard]] bool onUIThread() const {
std::lock_guard lock(mutex);
return phase == Phase::running && uiThread == std::this_thread::get_id();
}
[[nodiscard]] std::optional<UISession> session() const {
std::lock_guard lock(mutex);
return phase == Phase::running ? std::optional{UISession{uiThread, sessions}} : std::nullopt;
}
private:
mutable std::mutex mutex;
std::condition_variable wakesDone;
unsigned wakesInFlight{0};
bool wakePending{false};
Phase phase{Phase::idle};
std::thread::id uiThread;
std::uint64_t sessions{0}; // attach() count: names each loop, whatever thread runs it
std::function<void()> wakeFunction;
std::deque<std::shared_ptr<UIJob>> queue;
};
class UIScheduleSender {
std::weak_ptr<UIExecutorShared> target;
template <typename Receiver>
struct State final : UIJob, std::enable_shared_from_this<State<Receiver>> {
using Token = ex::stop_token_of_t<ex::env_of_t<Receiver>>;
struct OnStop {
std::weak_ptr<State> state;
void operator()() noexcept {
if (auto self = state.lock())
self->abandon();
}
};
enum class Outcome { pending, value, stopped, error };
Receiver receiver;
std::weak_ptr<UIExecutorShared> owner;
std::mutex mutex;
bool starting{true};
Outcome outcome{Outcome::pending};
std::exception_ptr failure;
std::optional<ex::stop_callback_for_t<Token, OnStop>> stopCallback;
State(Receiver r, std::weak_ptr<UIExecutorShared> o) : receiver(std::move(r)), owner(std::move(o)) { }
// The first completion wins. Delivery is deferred while start() registers the stop callback: a token already
// stopped invokes it inline, and the callback is not yet constructed.
void finish(Outcome value, std::exception_ptr error = {}) noexcept {
bool ready{};
{
std::lock_guard lock(mutex);
if (outcome != Outcome::pending)
return;
outcome = value;
failure = std::move(error);
ready = !starting;
}
if (ready)
deliver();
}
void start() noexcept {
auto self = this->shared_from_this();
auto shared = owner.lock();
try {
stopCallback.emplace(ex::get_stop_token(ex::get_env(receiver)), OnStop{this->weak_from_this()});
} catch (...) {
finish(Outcome::error, std::current_exception());
}
// From here on a completion is delivered by whoever wins it: the interface thread for a run, so that a receiver
// sees set_value() there even when the loop drains the job before start() returns.
bool ready{};
{
std::lock_guard lock(mutex);
starting = false;
ready = outcome != Outcome::pending;
}
if (ready) {
deliver();
return;
}
if (!shared || !shared->enqueue(self))
finish(Outcome::error, std::make_exception_ptr(UIExecutorUnavailable{}));
}
void run() noexcept override {
finish(Outcome::value);
}
void abandon() noexcept override {
if (auto shared = owner.lock())
shared->remove(this->shared_from_this());
finish(Outcome::stopped);
}
void fail(std::exception_ptr error) noexcept override {
finish(Outcome::error, std::move(error));
}
void deliver() noexcept {
auto self = this->shared_from_this(); // the receiver may destroy the operation
stopCallback.reset();
switch (outcome) {
case Outcome::value:
ex::set_value(std::move(receiver));
break;
case Outcome::stopped:
ex::set_stopped(std::move(receiver));
break;
case Outcome::error:
ex::set_error(std::move(receiver), std::move(failure));
break;
case Outcome::pending:
std::terminate();
}
}
};
template <typename Receiver>
class Operation {
std::shared_ptr<State<Receiver>> state;
public:
using operation_state_concept = ex::operation_state_tag;
explicit Operation(std::shared_ptr<State<Receiver>> value) : state(std::move(value)) { }
Operation(const Operation&) = delete;
Operation(Operation&&) = delete;
Operation& operator=(const Operation&) = delete;
Operation& operator=(Operation&&) = delete;
void start() noexcept {
auto keepAlive = state;
keepAlive->start();
}
};
public:
using sender_concept = ex::sender_tag;
using completion_signatures = ex::completion_signatures<ex::set_value_t(), ex::set_error_t(std::exception_ptr), ex::set_stopped_t()>;
explicit UIScheduleSender(std::weak_ptr<UIExecutorShared> value) : target(std::move(value)) { }
template <typename Receiver>
auto connect(Receiver receiver) const {
return Operation<Receiver>{std::make_shared<State<Receiver>>(std::move(receiver), target)};
}
};
} // namespace detail
/// @brief Handle to the interface thread of a frontend. Cheap to copy; a default-constructed one is never available.
class UIExecutor {
std::weak_ptr<detail::UIExecutorShared> shared;
public:
UIExecutor() = default;
explicit UIExecutor(std::weak_ptr<detail::UIExecutorShared> value) : shared(std::move(value)) { }
/// True while the frontend's loop runs. A later call to schedule() can still find it closed.
[[nodiscard]] bool available() const {
const auto state = shared.lock();
return state && state->running();
}
/// True when called from the interface thread of a running loop.
[[nodiscard]] bool onUIThread() const {
const auto state = shared.lock();
return state && state->onUIThread();
}
/// The running loop, as a session: its thread (the one that called the frontend's open()) and an identity that no
/// other loop of this frontend ever has, not even a later one on the same thread. Empty when no loop runs.
[[nodiscard]] std::optional<UISession> session() const {
const auto state = shared.lock();
return state ? state->session() : std::nullopt;
}
/// A sender completing on the interface thread; see the file comment for the other completions. Compose it with
/// `ex::then` to run a function there. The operation always goes through the queue, even from the interface thread.
[[nodiscard]] auto schedule() const {
return detail::UIScheduleSender{shared};
}
};
/// @brief The frontend's side of the executor: owns the queue and is driven by the interface thread's loop.
class UIExecutorHost {
std::shared_ptr<detail::UIExecutorShared> shared{std::make_shared<detail::UIExecutorShared>()};
public:
[[nodiscard]] UIExecutor executor() const {
return UIExecutor{shared};
}
/// Declares the calling thread as the interface thread. `wake` is thread-safe and makes the loop call drain() soon.
/// Throws std::logic_error when a loop is already attached; after close() a new loop may attach (handles stay valid).
void attach(std::function<void()> wake) {
shared->attach(std::move(wake));
}
/// Runs a bounded batch of the queued operations (those queued when it starts) and wakes the loop again if more
/// remain; call it on the interface thread only.
void drain() noexcept {
shared->drain();
}
/// Ends the loop: pending operations complete stopped, later ones fail as unavailable. Idempotent. Returns once the
/// wake-ups in flight on other threads are over, so the loop may then free what `wake` uses (never call it from `wake`).
void close() noexcept {
shared->close();
}
};
/// @brief The process-wide host of one frontend type (`Tag` is the frontend's own type): its adapter attaches it while its loop runs.
template <typename Tag>
[[nodiscard]] UIExecutorHost& uiExecutorHostOf() {
static UIExecutorHost host;
return host;
}
/// @brief Thrown on the interface thread by a frontend's `openSecondaryWindow` while its first window cannot host another
/// yet (WebView2 creates its environment after open() started). invokeOnUIThreadWhenReady() tries again from another
/// thread; on the interface thread it reaches the caller, as the std::logic_error it is.
class WindowNotReady : public std::logic_error {
public:
explicit WindowNotReady(const std::string& message) : std::logic_error(message) { }
};
namespace detail {
/// One blocking invocation (invokeOnUIThread): deletes itself when its operation completes, whatever the outcome.
template <typename Function>
struct UIInvocation {
struct Receiver {
using receiver_concept = ex::receiver_tag;
UIInvocation* self;
void finish(std::exception_ptr error) noexcept {
auto completion = std::move(self->done);
delete self;
completion.set_value(std::move(error));
}
void set_value() noexcept {
std::exception_ptr error;
try {
self->function();
} catch (...) {
error = std::current_exception();
}
finish(std::move(error));
}
void set_error(std::exception_ptr) noexcept {
finish(std::make_exception_ptr(UIExecutorUnavailable{}));
}
void set_stopped() noexcept {
finish(std::make_exception_ptr(UIExecutorUnavailable{}));
}
};
Function function;
std::promise<std::exception_ptr> done;
ex::connect_result_t<decltype(std::declval<const UIExecutor&>().schedule()), Receiver> operation;
UIInvocation(const UIExecutor& loop, Function work) : function(std::move(work)), operation(ex::connect(loop.schedule(), Receiver{this})) { }
};
} // namespace detail
/// @brief Runs `function` on the interface thread and waits for it, from any other thread (#616). Called on the interface
/// thread itself it runs the function at once (waiting there would never end). An exception of the function is rethrown to
/// the caller; `UIExecutorUnavailable` is thrown when no loop runs, or when it closes before the function started.
/// Never call it from a thread the interface thread waits for.
template <typename Function>
void invokeOnUIThread(const UIExecutor& executor, Function function) {
if (executor.onUIThread()) {
function();
return;
}
auto* invocation = new detail::UIInvocation<Function>(executor, std::move(function));
auto answer = invocation->done.get_future();
ex::start(invocation->operation);
if (auto error = answer.get())
std::rethrow_exception(error);
}
/// @brief invokeOnUIThread(), run again every 10 ms while `function` throws WindowNotReady (#646). The interface thread
/// cannot wait for itself: there, WindowNotReady reaches the caller. The frontend bounds the wait: a first window that
/// never becomes ready closes, and the call then fails as invokeOnUIThread() does.
template <typename Function>
void invokeOnUIThreadWhenReady(const UIExecutor& executor, Function function) {
for (;;) {
try {
invokeOnUIThread(executor, function);
return;
} catch (const WindowNotReady&) {
if (executor.onUIThread())
throw;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
} // namespace webfront::frontend