-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpending_request.rs
More file actions
308 lines (285 loc) · 12.9 KB
/
pending_request.rs
File metadata and controls
308 lines (285 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use crate::{AsyncResponseSender, BlockingResponseSender, MethodAndParams, Request, ResponseError};
/// A tracked or untracked asynchronous request, paired with an optional response sender.
///
/// If `Some(sender)` is present, the response will be delivered through it.
/// If `None`, the response is expected to be emitted as an [`Event`] instead.
///
/// [`Event`]: crate::Event
pub type AsyncPendingRequestTuple<Req, Resp> = (Req, Option<AsyncResponseSender<Resp>>);
/// A tracked or untracked blocking request, paired with an optional response sender.
///
/// If `Some(sender)` is present, the response will be sent through it.
/// If `None`, the response is expected to be emitted as an [`Event`] instead.
///
/// [`Event`]: crate::Event
pub type BlockingPendingRequestTuple<Req, Resp> = (Req, Option<BlockingResponseSender<Resp>>);
macro_rules! gen_pending_request_types {
($($name:ident),*) => {
/// A successfully handled request and its decoded server response.
///
/// This enum is returned when a request has been fully processed and the server replied
/// with a valid `result`. It contains both the original request and the corresponding
/// response.
///
/// `SatisfiedRequest` is used by the [`Event::Response`] variant to expose typed
/// request-response pairs to the caller.
///
/// You typically don’t construct this manually — it is created internally by the client
/// after decoding JSON-RPC responses.
///
/// [`Event::Response`]: crate::Event::Response
#[derive(Debug, Clone)]
pub enum SatisfiedRequest {
$($name {
req: crate::request::$name,
resp: <crate::request::$name as Request>::Response,
}),*,
}
/// A request that received an error response from the Electrum server.
///
/// This enum represents a completed request where the server returned a JSON-RPC error
/// instead of a `result`. It contains both the original request and the associated error.
///
/// This is used by the [`Event::ResponseError`] variant to expose server-side failures
/// in a typed manner.
///
/// Like [`SatisfiedRequest`], this is created internally by the client during response
/// processing.
///
/// [`Event::ResponseError`]: crate::Event::ResponseError
#[derive(Debug, Clone)]
pub enum ErroredRequest {
$($name {
req: crate::request::$name,
error: ResponseError,
}),*,
}
impl core::fmt::Display for ErroredRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
$(Self::$name { req, error } => write!(f, "Server responsed to {:?} with error: {}", req, error)),*,
}
}
}
impl std::error::Error for ErroredRequest {}
/// A trait representing a request that has been sent to the Electrum server and is awaiting
/// a response.
///
/// This trait is used internally to track the lifecycle of a request, including:
/// - extracting its method and parameters before sending,
/// - handling a successful server response,
/// - handling an error response.
///
/// Both [`AsyncPendingRequest`] and [`BlockingPendingRequest`] implement this trait.
/// These are generated enums that hold the original request and, optionally, a response
/// channel.
///
/// You should not implement this trait manually — it is only used inside the client engine
/// for matching raw Electrum responses to typed results.
///
/// [`AsyncPendingRequest`]: crate::pending_request::AsyncPendingRequest
/// [`BlockingPendingRequest`]: crate::pending_request::BlockingPendingRequest
pub trait PendingRequest {
/// Returns the Electrum method name and parameters for this request.
///
/// This is used to serialize the request into a JSON-RPC message before sending it to
/// the server.
///
/// The method and parameters must match the format expected by the Electrum protocol.
fn to_method_and_params(&self) -> MethodAndParams;
/// Attempts to decode a successful server response (`result`) into a typed value.
///
/// This is called when a matching response arrives from the server. If the request was
/// tracked, this method deserializes the response and either:
/// - completes the associated response channel (if present), or
/// - returns a [`SatisfiedRequest`] directly, if untracked.
///
/// Returns an error if deserialization fails.
///
/// [`SatisfiedRequest`]: crate::SatisfiedRequest
fn satisfy(self, raw_resp: serde_json::Value) -> Result<Option<SatisfiedRequest>, serde_json::Error>;
/// Handles a server-side error response (`error`) for this request.
///
/// If the request was tracked, this sends the error through the associated response
/// channel. Otherwise, it returns a [`ErroredRequest`] containing the original request
/// and the error.
///
/// [`ErroredRequest`]: crate::ErroredRequest
fn satisfy_error(self, raw_error: serde_json::Value) -> Option<ErroredRequest>;
}
/// An internal representation of a pending asynchronous Electrum request.
///
/// Each variant corresponds to a specific request type. The enum holds:
/// - the original request (`req`), and
/// - an optional response channel (`resp_tx`) that will be completed once a server response
/// is received.
///
/// This type is created when calling [`AsyncBatchRequest::request`] or
/// [`AsyncBatchRequest::event_request`], and is consumed by the client when processing
/// responses.
///
/// If `resp_tx` is present, the request is tracked and its response will complete the
/// associated future. If `resp_tx` is `None`, the response will be delivered as an
/// [`Event`] instead.
///
/// You typically don’t construct this type directly — it is produced by the batch builder
/// or macros.
///
/// [`AsyncBatchRequest::request`]: crate::AsyncBatchRequest::request
/// [`AsyncBatchRequest::event_request`]: crate::AsyncBatchRequest::event_request
/// [`Event`]: crate::Event
#[derive(Debug)]
pub enum AsyncPendingRequest {
$($name {
req: crate::request::$name,
resp_tx: Option<AsyncResponseSender<<crate::request::$name as Request>::Response>>,
}),*,
}
$(
impl From<AsyncPendingRequestTuple<crate::request::$name, <crate::request::$name as Request>::Response>> for AsyncPendingRequest {
fn from((req, resp_tx): AsyncPendingRequestTuple<crate::request::$name, <crate::request::$name as Request>::Response>) -> Self {
Self::$name{ req, resp_tx }
}
}
)*
impl PendingRequest for AsyncPendingRequest {
fn to_method_and_params(&self) -> MethodAndParams {
match self {
$(AsyncPendingRequest::$name{ req, .. } => req.to_method_and_params()),*
}
}
fn satisfy(self, raw_resp: serde_json::Value) -> Result<Option<SatisfiedRequest>, serde_json::Error> {
use crate::request;
match self {
$(Self::$name{ req, resp_tx } => {
let resp = serde_json::from_value::<<request::$name as Request>::Response>(raw_resp)?;
Ok(match resp_tx {
Some(tx) => {
let _ = tx.send(Ok(resp));
None
}
None => Some(SatisfiedRequest::$name { req, resp }),
})
}),*
}
}
fn satisfy_error(self, raw_error: serde_json::Value) -> Option<ErroredRequest> {
let error = ResponseError(raw_error);
match self {
$(Self::$name{ req, resp_tx } => {
match resp_tx {
Some(tx) => { let _ = tx.send(Err(error)); None }
None => Some(ErroredRequest::$name{ req, error }),
}
}),*
}
}
}
/// An internal representation of a pending blocking Electrum request.
///
/// Each variant corresponds to a specific request type. The enum holds:
/// - the original request (`req`), and
/// - an optional response channel (`resp_tx`) that will be fulfilled once a server response
/// is received.
///
/// This type is created when calling [`BlockingBatchRequest::request`] or
/// [`BlockingBatchRequest::event_request`], and is consumed by the client when processing
/// server responses.
///
/// If `resp_tx` is present, the request is tracked and the response will be sent through
/// the associated receiver. If `resp_tx` is `None`, the response will be delivered as an
/// [`Event`] instead.
///
/// This type is used internally by the blocking client and is typically not constructed
/// directly.
///
/// [`BlockingBatchRequest::request`]: crate::BlockingBatchRequest::request
/// [`BlockingBatchRequest::event_request`]: crate::BlockingBatchRequest::event_request
/// [`Event`]: crate::Event
#[derive(Debug)]
pub enum BlockingPendingRequest {
$($name {
req: crate::request::$name,
resp_tx: Option<BlockingResponseSender<<crate::request::$name as Request>::Response>>,
}),*,
}
$(
impl From<BlockingPendingRequestTuple<crate::request::$name, <crate::request::$name as Request>::Response>> for BlockingPendingRequest {
fn from((req, resp_tx): BlockingPendingRequestTuple<crate::request::$name, <crate::request::$name as Request>::Response>) -> Self {
Self::$name{ req, resp_tx }
}
}
)*
impl PendingRequest for BlockingPendingRequest {
fn to_method_and_params(&self) -> MethodAndParams {
match self {
$(BlockingPendingRequest::$name{ req, .. } => req.to_method_and_params()),*
}
}
fn satisfy(self, raw_resp: serde_json::Value) -> Result<Option<SatisfiedRequest>, serde_json::Error> {
use crate::request;
match self {
$(Self::$name{ req, resp_tx } => {
let resp = serde_json::from_value::<<request::$name as Request>::Response>(raw_resp)?;
Ok(match resp_tx {
Some(tx) => {
let _ = tx.send(Ok(resp));
None
}
None => Some(SatisfiedRequest::$name { req, resp }),
})
}),*
}
}
fn satisfy_error(self, raw_error: serde_json::Value) -> Option<ErroredRequest> {
let error = ResponseError(raw_error);
match self {
$(Self::$name{ req, resp_tx } => {
match resp_tx {
Some(tx) => { let _ = tx.send(Err(error)); None }
None => Some(ErroredRequest::$name{ req, error }),
}
}),*
}
}
}
};
}
gen_pending_request_types! {
Header,
HeaderWithProof,
Headers,
HeadersWithCheckpoint,
EstimateFee,
HeadersSubscribe,
RelayFee,
GetBalance,
GetHistory,
GetMempool,
ListUnspent,
ScriptHashSubscribe,
ScriptHashUnsubscribe,
BroadcastTx,
GetTx,
GetTxMerkle,
GetTxidFromPos,
GetFeeHistogram,
Banner,
Features,
Ping,
Custom
}
impl<A: PendingRequest> PendingRequest for Box<A> {
fn to_method_and_params(&self) -> MethodAndParams {
self.as_ref().to_method_and_params()
}
fn satisfy(
self,
raw_resp: serde_json::Value,
) -> Result<Option<SatisfiedRequest>, serde_json::Error> {
(*self).satisfy(raw_resp)
}
fn satisfy_error(self, raw_error: serde_json::Value) -> Option<ErroredRequest> {
(*self).satisfy_error(raw_error)
}
}