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/Any.hpp"
5#include "util/async/impl/ErasedOperation.hpp"
6
7#include <fmt/format.h>
8#include <fmt/std.h>
9
10#include <any>
11#include <expected>
12#include <thread>
13#include <type_traits>
14#include <utility>
15
16// TODO: In the future, perhaps cancel and requestStop should be combined into one.
17// Users of the library should not care whether the operation is cancellable or stoppable - users
18// just want to cancel it whatever that means internally.
19
20namespace util::async {
21
27template <typename RetType>
29public:
35 /* implicit */ AnyOperation(impl::ErasedOperation&& operation)
36 : operation_{std::move(operation)}
37 {
38 }
39
40 ~AnyOperation() = default;
41
42 AnyOperation(AnyOperation const&) = delete;
43 AnyOperation(AnyOperation&&) = default;
45 operator=(AnyOperation const&) = delete;
47 operator=(AnyOperation&&) = default;
48
53 void
54 wait() noexcept
55 {
56 operation_.wait();
57 }
58
65 void
67 {
68 operation_.abort();
69 }
70
76 [[nodiscard]] std::expected<RetType, ExecutionError>
78 {
79 try {
80 auto data = operation_.get();
81 if (not data)
82 return std::unexpected(std::move(data).error());
83
84 if constexpr (std::is_void_v<RetType>) {
85 return {};
86 } else {
87 return std::any_cast<RetType>(std::move(data).value());
88 }
89
90 } catch (std::bad_any_cast const& e) {
91 return std::unexpected{
92 ExecutionError(fmt::format("{}", std::this_thread::get_id()), "Bad any cast")
93 };
94 }
95 }
96
103 void
105 {
106 operation_.invoke();
107 }
108
109private:
110 impl::ErasedOperation operation_;
111};
112
113} // namespace util::async
A type-erased operation that can be executed via AnyExecutionContext.
Definition AnyOperation.hpp:28
void abort()
Abort the operation.
Definition AnyOperation.hpp:66
void invoke()
Force-invoke the operation.
Definition AnyOperation.hpp:104
AnyOperation(impl::ErasedOperation &&operation)
Construct a new type-erased Operation object.
Definition AnyOperation.hpp:35
void wait() noexcept
Wait for the operation to complete.
Definition AnyOperation.hpp:54
std::expected< RetType, ExecutionError > get()
Get the result of the operation.
Definition AnyOperation.hpp:77
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:18
Error channel type for async operation of any ExecutionContext.
Definition Error.hpp:14