JSON-RPC 2.0
JSON-RPC 2.0 Modern C++ Library
Loading...
Searching...
No Matches
pending_request.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <condition_variable>
4#include <mutex>
5
6#include <asio.hpp>
7#include <nlohmann/json.hpp>
8
9namespace jsonrpc::endpoint {
10
18 public:
24 explicit PendingRequest(asio::strand<asio::any_io_executor> strand)
25 : strand_(std::move(strand)) {
26 }
27
28 // Prevent copying and moving
30 auto operator=(const PendingRequest&) -> PendingRequest& = delete;
33
37 ~PendingRequest() = default;
38
44 void SetResult(nlohmann::json result) {
45 // Execute within the strand to ensure thread safety
46 asio::post(strand_, [this, result = std::move(result)]() mutable {
47 if (!is_ready_) {
48 result_ = std::move(result);
49 is_ready_ = true;
50
51 // Notify any waiting consumers
52 std::lock_guard<std::mutex> lock(mutex_);
53 ready_cv_.notify_all();
54 }
55 });
56 }
57
64 void Cancel(int code, const std::string& message) {
65 // Create a JSON-RPC error object
66 nlohmann::json error = {{"error", {{"code", code}, {"message", message}}}};
67
68 has_error_ = true;
69
70 // Set the result with the error
71 SetResult(std::move(error));
72 }
73
79 auto GetResult() -> asio::awaitable<nlohmann::json> {
80 // If the result is already ready, return it immediately
81 if (is_ready_) {
82 co_return result_;
83 }
84
85 // Otherwise, wait for the result using a timer and polling
86 // This is a simplified approach that works with ASIO
87 auto executor = co_await asio::this_coro::executor;
88 asio::steady_timer timer(executor, std::chrono::milliseconds(10));
89
90 while (!is_ready_) {
91 co_await timer.async_wait(asio::use_awaitable);
92 timer.expires_after(std::chrono::milliseconds(10));
93 }
94
95 // Return the result
96 co_return result_;
97 }
98
104 [[nodiscard]] bool IsReady() const {
105 return is_ready_;
106 }
107
113 [[nodiscard]] bool HasError() const {
114 return has_error_;
115 }
116
117 private:
119 asio::strand<asio::any_io_executor> strand_;
120
122 nlohmann::json result_;
123
125 bool is_ready_{};
126
128 bool has_error_{};
129
131 std::mutex mutex_;
132
134 std::condition_variable ready_cv_;
135};
136
137} // namespace jsonrpc::endpoint
A class representing a pending RPC request.
PendingRequest(const PendingRequest &)=delete
auto operator=(PendingRequest &&) -> PendingRequest &=delete
bool IsReady() const
Check if the request is ready.
bool HasError() const
Check if the request has an error.
~PendingRequest()=default
Destructor.
auto operator=(const PendingRequest &) -> PendingRequest &=delete
void SetResult(nlohmann::json result)
Sets the result of the request.
auto GetResult() -> asio::awaitable< nlohmann::json >
Get the result asynchronously.
PendingRequest(asio::strand< asio::any_io_executor > strand)
Construct a new Pending Request object.
PendingRequest(PendingRequest &&)=delete
void Cancel(int code, const std::string &message)
Cancels the request with an error.