Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
BasicExecutionContext.hpp
1#pragma once
2
3#include "util/Assert.hpp"
4#include "util/async/Concepts.hpp"
5#include "util/async/Error.hpp"
6#include "util/async/Operation.hpp"
7#include "util/async/Outcome.hpp"
8#include "util/async/context/impl/Cancellation.hpp"
9#include "util/async/context/impl/Execution.hpp"
10#include "util/async/context/impl/Strand.hpp"
11#include "util/async/context/impl/Timer.hpp"
12#include "util/async/context/impl/Utils.hpp"
13#include "util/async/impl/ErrorHandling.hpp"
14
15#include <boost/asio.hpp>
16#include <boost/asio/error.hpp>
17#include <boost/asio/strand.hpp>
18#include <boost/asio/thread_pool.hpp>
19
20#include <chrono>
21#include <cstddef>
22#include <expected>
23#include <memory>
24#include <optional>
25#include <type_traits>
26#include <utility>
27
39namespace util::async {
40namespace impl {
41
43 using Executor = boost::asio::strand<boost::asio::thread_pool::executor_type>;
44 using Timer = SteadyTimer<Executor>;
45
46 Executor&
47 getExecutor()
48 {
49 return executor;
50 }
51
52 Executor executor;
53};
54
55struct AsioPoolContext {
56 using Executor = boost::asio::thread_pool;
57 using Timer = SteadyTimer<Executor>;
58 using Strand = AsioPoolStrandContext;
59
60 AsioPoolContext(std::size_t numThreads) : executor(std::make_unique<Executor>(numThreads))
61 {
62 }
63
64 AsioPoolContext(AsioPoolContext const&) = delete;
65 AsioPoolContext(AsioPoolContext&&) = default;
66
67 [[nodiscard]] Strand
68 makeStrand() const
69 {
70 ASSERT(executor, "Called after executor was moved from.");
71 return {boost::asio::make_strand(*executor)};
72 }
73
74 void
75 stop() const
76 {
77 if (executor) // don't call if executor was moved from
78 executor->stop();
79 }
80
81 void
82 join() const
83 {
84 if (executor) // don't call if executor was moved from
85 executor->join();
86 }
87
88 [[nodiscard]] Executor&
89 getExecutor() const
90 {
91 ASSERT(executor, "Called after executor was moved from.");
92 return *executor;
93 }
94
95 std::unique_ptr<Executor> executor;
96};
97
98} // namespace impl
99
114template <
115 typename ContextType,
116 typename StopSourceType,
117 typename DispatcherType,
118 typename TimerContextProvider = impl::SelfContextProvider,
119 typename ErrorHandlerType = impl::DefaultErrorHandler>
121 ContextType context_;
122
126
127public:
131 static constexpr bool kIsNoexcept = noexcept(ErrorHandlerType::wrap([](auto&) { throw 0; })) and
132 noexcept(ErrorHandlerType::catchAndAssert([] { throw 0; }));
133
134 using ContextHolderType = ContextType;
135
136 using ExecutorType = ContextHolderType::Executor;
137
143 template <typename T>
144 using ValueType = std::expected<T, ExecutionError>;
145
146 using StopSource = StopSourceType;
147
148 using StopToken = StopSourceType::Token;
149
155 template <typename T>
157
163 template <typename T>
165
171 StopSourceType,
172 DispatcherType,
173 TimerContextProvider,
174 ErrorHandlerType>;
175
176 using Timer = ContextHolderType::Timer;
177
184 template <typename T>
186
192
198 explicit BasicExecutionContext(std::size_t numThreads = 1) noexcept : context_{numThreads}
199 {
200 }
201
206 {
207 stop();
208 }
209
212
221 [[nodiscard]] auto
223 SomeStdDuration auto delay,
225 std::optional<std::chrono::milliseconds> timeout = std::nullopt
226 ) noexcept(kIsNoexcept)
227 {
228 if constexpr (not std::is_same_v<
229 decltype(TimerContextProvider::getContext(*this)),
230 decltype(*this)>) {
231 return TimerContextProvider::getContext(*this).scheduleAfter(
232 delay, std::forward<decltype(fn)>(fn), timeout
233 );
234 } else {
235 using FnRetType = std::decay_t<std::invoke_result_t<decltype(fn), StopToken>>;
237 impl::extractAssociatedExecutor(*this),
238 delay,
239 [this, timeout, fn = std::forward<decltype(fn)>(fn)](auto) mutable {
240 return this->execute(
241 [fn = std::forward<decltype(fn)>(fn)](auto stopToken) mutable {
242 if constexpr (std::is_void_v<FnRetType>) {
243 std::invoke(std::forward<decltype(fn)>(fn), std::move(stopToken));
244 } else {
245 return std::invoke(
246 std::forward<decltype(fn)>(fn), std::move(stopToken)
247 );
248 }
249 },
250 timeout
251 );
252 }
253 );
254 }
255 }
256
266 [[nodiscard]] auto
268 SomeStdDuration auto delay,
270 std::optional<std::chrono::milliseconds> timeout = std::nullopt
271 ) noexcept(kIsNoexcept)
272 {
273 if constexpr (not std::is_same_v<
274 decltype(TimerContextProvider::getContext(*this)),
275 decltype(*this)>) {
276 return TimerContextProvider::getContext(*this).scheduleAfter(
277 delay, std::forward<decltype(fn)>(fn), timeout
278 );
279 } else {
280 using FnRetType = std::decay_t<std::invoke_result_t<decltype(fn), StopToken, bool>>;
282 impl::extractAssociatedExecutor(*this),
283 delay,
284 [this, timeout, fn = std::forward<decltype(fn)>(fn)](auto ec) mutable {
285 return this->execute(
286 [fn = std::forward<decltype(fn)>(fn),
287 isAborted = (ec == boost::asio::error::operation_aborted)](
288 auto stopToken
289 ) mutable {
290 if constexpr (std::is_void_v<FnRetType>) {
291 std::invoke(
292 std::forward<decltype(fn)>(fn), std::move(stopToken), isAborted
293 );
294 } else {
295 return std::invoke(
296 std::forward<decltype(fn)>(fn), std::move(stopToken), isAborted
297 );
298 }
299 },
300 timeout
301 );
302 }
303 );
304 }
305 }
306
315 [[nodiscard]] auto
317 SomeStdDuration auto interval,
319 ) noexcept(kIsNoexcept)
320 {
321 if constexpr (not std::is_same_v<
322 decltype(TimerContextProvider::getContext(*this)),
323 decltype(*this)>) {
324 return TimerContextProvider::getContext(*this).executeRepeatedly(
325 interval, std::forward<decltype(fn)>(fn)
326 );
327 } else {
328 return RepeatedOperation(
329 impl::extractAssociatedExecutor(*this), interval, std::forward<decltype(fn)>(fn)
330 );
331 }
332 }
333
341 [[nodiscard]] auto
344 std::optional<std::chrono::milliseconds> timeout = std::nullopt
345 ) noexcept(kIsNoexcept)
346 {
347 return DispatcherType::dispatch(
348 context_,
349 impl::outcomeForHandler<StopSourceType>(fn),
350 ErrorHandlerType::wrap([this, timeout, fn = std::forward<decltype(fn)>(fn)](
351 auto& outcome, auto& stopSource, auto stopToken
352 ) mutable {
353 [[maybe_unused]] auto const timeoutHandler = impl::getTimeoutHandleIfNeeded(
354 TimerContextProvider::getContext(*this), timeout, stopSource
355 );
356
357 using FnRetType = std::decay_t<std::invoke_result_t<decltype(fn), StopToken>>;
358 if constexpr (std::is_void_v<FnRetType>) {
359 std::invoke(std::forward<decltype(fn)>(fn), std::move(stopToken));
360 outcome.setValue();
361 } else {
362 outcome.setValue(
363 std::invoke(std::forward<decltype(fn)>(fn), std::move(stopToken))
364 );
365 }
366 })
367 );
368 }
369
377 [[nodiscard]] auto
378 execute(SomeHandlerWith<StopToken> auto&& fn, SomeStdDuration auto timeout) noexcept(
380 )
381 {
382 return execute(
383 std::forward<decltype(fn)>(fn),
384 std::make_optional(std::chrono::duration_cast<std::chrono::milliseconds>(timeout))
385 );
386 }
387
395 [[nodiscard]] auto
397 {
398 return DispatcherType::dispatch(
399 context_,
400 impl::outcomeForHandler<StopSourceType>(fn),
401 ErrorHandlerType::wrap([fn = std::forward<decltype(fn)>(fn)](auto& outcome) mutable {
402 using FnRetType = std::decay_t<std::invoke_result_t<decltype(fn)>>;
403 if constexpr (std::is_void_v<FnRetType>) {
404 std::invoke(std::forward<decltype(fn)>(fn));
405 outcome.setValue();
406 } else {
407 outcome.setValue(std::invoke(std::forward<decltype(fn)>(fn)));
408 }
409 })
410 );
411 }
412
419 void
421 {
422 DispatcherType::post(context_, ErrorHandlerType::catchAndAssert(fn));
423 }
424
430 [[nodiscard]] Strand
432 {
433 return Strand(*this, context_.makeStrand());
434 }
435
439 void
440 stop() const noexcept
441 {
442 context_.stop();
443 }
444
448 void
449 join() const noexcept
450 {
451 context_.join();
452 }
453
462 ContextType::Executor&
464 {
465 return context_.getExecutor();
466 }
467};
468
483
493
494} // namespace util::async
A highly configurable execution context.
Definition BasicExecutionContext.hpp:120
void submit(SomeHandlerWithoutStopToken auto &&fn) noexcept(kIsNoexcept)
Schedule an operation on the execution context without expectations of a result.
Definition BasicExecutionContext.hpp:420
ContextType ContextHolderType
The underlying context type.
Definition BasicExecutionContext.hpp:134
StoppableOperation< ValueType< T >, StopSourceType > StoppableOperation
The operation type returned for stoppable work on this context.
Definition BasicExecutionContext.hpp:156
auto execute(SomeHandlerWith< StopToken > auto &&fn, std::optional< std::chrono::milliseconds > timeout=std::nullopt) noexcept(kIsNoexcept)
Schedule an operation on the execution context.
Definition BasicExecutionContext.hpp:342
ScheduledOperation< BasicExecutionContext, StoppableOperation< T > > ScheduledOperation
The operation type returned for work scheduled after a delay.
Definition BasicExecutionContext.hpp:185
auto scheduleAfter(SomeStdDuration auto delay, SomeHandlerWith< StopToken > auto &&fn, std::optional< std::chrono::milliseconds > timeout=std::nullopt) noexcept(kIsNoexcept)
Schedule an operation on the execution context.
Definition BasicExecutionContext.hpp:222
Strand makeStrand()
Create a strand for this execution context.
Definition BasicExecutionContext.hpp:431
auto execute(SomeHandlerWith< StopToken > auto &&fn, SomeStdDuration auto timeout) noexcept(kIsNoexcept)
Schedule an operation on the execution context.
Definition BasicExecutionContext.hpp:378
ContextType::Executor & getExecutor()
Get the underlying executor.
Definition BasicExecutionContext.hpp:463
Operation< ValueType< T > > Operation
The operation type returned for non-stoppable work on this context.
Definition BasicExecutionContext.hpp:164
ContextHolderType::Executor ExecutorType
Executor of the underlying context.
Definition BasicExecutionContext.hpp:136
StopSourceType::Token StopToken
Stop token passed to stoppable user functions.
Definition BasicExecutionContext.hpp:148
auto executeRepeatedly(SomeStdDuration auto interval, SomeHandlerWithoutStopToken auto &&fn) noexcept(kIsNoexcept)
Schedule a repeating operation on the execution context.
Definition BasicExecutionContext.hpp:316
impl::BasicStrand< BasicExecutionContext, StopSourceType, DispatcherType, TimerContextProvider, ErrorHandlerType > Strand
The strand type created by this context to serialize execution.
Definition BasicExecutionContext.hpp:169
std::expected< T, ExecutionError > ValueType
The result type of operations: the value or an ExecutionError.
Definition BasicExecutionContext.hpp:144
BasicExecutionContext(std::size_t numThreads=1) noexcept
Create a new execution context with the given number of threads.
Definition BasicExecutionContext.hpp:198
StopSourceType StopSource
The stop source type used by stoppable operations.
Definition BasicExecutionContext.hpp:146
auto scheduleAfter(SomeStdDuration auto delay, SomeHandlerWith< StopToken, bool > auto &&fn, std::optional< std::chrono::milliseconds > timeout=std::nullopt) noexcept(kIsNoexcept)
Schedule an operation on the execution context.
Definition BasicExecutionContext.hpp:267
auto execute(SomeHandlerWithoutStopToken auto &&fn) noexcept(kIsNoexcept)
Schedule an operation on the execution context.
Definition BasicExecutionContext.hpp:396
void join() const noexcept
Block until all operations are completed.
Definition BasicExecutionContext.hpp:449
void stop() const noexcept
Stop the execution context as soon as possible.
Definition BasicExecutionContext.hpp:440
RepeatingOperation< BasicExecutionContext > RepeatedOperation
The operation type returned for work executed repeatedly at an interval.
Definition BasicExecutionContext.hpp:191
ContextHolderType::Timer Timer
The timer type of the underlying context.
Definition BasicExecutionContext.hpp:176
~BasicExecutionContext() override
Stops the underlying thread pool.
Definition BasicExecutionContext.hpp:205
The future side of async operations that automatically repeat until aborted.
Definition Operation.hpp:220
Definition Strand.hpp:24
Definition Timer.hpp:8
Definition Cancellation.hpp:34
Specifies the interface for a handler that can be invoked with the specified args.
Definition Concepts.hpp:203
Specifies the interface for a handler that is invocable without a stop token.
Definition Concepts.hpp:192
Specifies that the type must be some std::duration.
Definition Concepts.hpp:213
This namespace implements an async framework built on top of execution contexts.
Definition AnyExecutionContext.hpp:18
BasicExecutionContext< impl::AsioPoolContext, impl::BasicStopSource, impl::PostDispatchStrategy > PoolExecutionContext
A asio::thread_pool-based execution context.
Definition BasicExecutionContext.hpp:491
BasicExecutionContext< impl::AsioPoolContext, impl::YieldContextStopSource, impl::SpawnDispatchStrategy > CoroExecutionContext
A Boost.Coroutine-based (asio yield_context) execution context.
Definition BasicExecutionContext.hpp:479
Tag type for identifying execution context types.
Definition Concepts.hpp:20
Definition BasicExecutionContext.hpp:55
Definition BasicExecutionContext.hpp:42
Definition ErrorHandling.hpp:16
Definition Execution.hpp:13