Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
AnyOperation.hpp
1#pragma once
2
3#include "util/async/Error.hpp"
4#include "util/async/impl/ErasedOperation.hpp"
5
6#include <fmt/format.h>
7#include <fmt/std.h>
8
9#include <any>
10#include <expected>
11#include <thread>
12#include <type_traits>
13#include <utility>
14
15// TODO: In the future, perhaps cancel and requestStop should be combined into one.
16// Users of the library should not care whether the operation is cancellable or stoppable - users
17// just want to cancel it whatever that means internally.
18
19namespace util::async {
20
24template <typename RetType>
26public:
32 /* implicit */ AnyOperation(impl::ErasedOperation&& operation)
33 : operation_{std::move(operation)}
34 {
35 }
36
37 ~AnyOperation() = default;
38
39 AnyOperation(AnyOperation const&) = delete;
40 AnyOperation(AnyOperation&&) = default;
42 operator=(AnyOperation const&) = delete;
44 operator=(AnyOperation&&) = default;
45
50 void
51 wait() noexcept
52 {
53 operation_.wait();
54 }
55
62 void
64 {
65 operation_.abort();
66 }
67
73 [[nodiscard]] std::expected<RetType, ExecutionError>
75 {
76 try {
77 auto data = operation_.get();
78 if (not data)
79 return std::unexpected(std::move(data).error());
80
81 if constexpr (std::is_void_v<RetType>) {
82 return {};
83 } else {
84 return std::any_cast<RetType>(std::move(data).value());
85 }
86
87 } catch (std::bad_any_cast const& e) {
88 return std::unexpected{
89 ExecutionError(fmt::format("{}", std::this_thread::get_id()), "Bad any cast")
90 };
91 }
92 }
93
100 void
102 {
103 operation_.invoke();
104 }
105
106private:
107 impl::ErasedOperation operation_;
108};
109
110} // namespace util::async
A type-erased operation that can be executed via AnyExecutionContext.
Definition AnyOperation.hpp:25
void abort()
Abort the operation.
Definition AnyOperation.hpp:63
void invoke()
Force-invoke the operation.
Definition AnyOperation.hpp:101
AnyOperation(impl::ErasedOperation &&operation)
Construct a new type-erased Operation object.
Definition AnyOperation.hpp:32
void wait() noexcept
Wait for the operation to complete.
Definition AnyOperation.hpp:51
std::expected< RetType, ExecutionError > get()
Get the result of the operation.
Definition AnyOperation.hpp:74
Definition ErasedOperation.hpp:15
This namespace implements the data access layer and related components.
Definition AmendmentCenter.cpp:56
This namespace implements an async framework built on top of execution contexts.
Definition AnyExecutionContext.hpp:17
Error channel type for async operation of any ExecutionContext.
Definition Error.hpp:19