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
25template <typename RetType>
27public:
33 /* implicit */ AnyOperation(impl::ErasedOperation&& operation)
34 : operation_{std::move(operation)}
35 {
36 }
37
38 ~AnyOperation() = default;
39
40 AnyOperation(AnyOperation const&) = delete;
41 AnyOperation(AnyOperation&&) = default;
43 operator=(AnyOperation const&) = delete;
45 operator=(AnyOperation&&) = default;
46
51 void
52 wait() noexcept
53 {
54 operation_.wait();
55 }
56
63 void
65 {
66 operation_.abort();
67 }
68
74 [[nodiscard]] std::expected<RetType, ExecutionError>
76 {
77 try {
78 auto data = operation_.get();
79 if (not data)
80 return std::unexpected(std::move(data).error());
81
82 if constexpr (std::is_void_v<RetType>) {
83 return {};
84 } else {
85 return std::any_cast<RetType>(std::move(data).value());
86 }
87
88 } catch (std::bad_any_cast const& e) {
89 return std::unexpected{
90 ExecutionError(fmt::format("{}", std::this_thread::get_id()), "Bad any cast")
91 };
92 }
93 }
94
101 void
103 {
104 operation_.invoke();
105 }
106
107private:
108 impl::ErasedOperation operation_;
109};
110
111} // namespace util::async
A type-erased operation that can be executed via AnyExecutionContext.
Definition AnyOperation.hpp:26
void abort()
Abort the operation.
Definition AnyOperation.hpp:64
void invoke()
Force-invoke the operation.
Definition AnyOperation.hpp:102
AnyOperation(impl::ErasedOperation &&operation)
Construct a new type-erased Operation object.
Definition AnyOperation.hpp:33
void wait() noexcept
Wait for the operation to complete.
Definition AnyOperation.hpp:52
std::expected< RetType, ExecutionError > get()
Get the result of the operation.
Definition AnyOperation.hpp:75
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