-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmod.rs
More file actions
453 lines (418 loc) · 15.2 KB
/
mod.rs
File metadata and controls
453 lines (418 loc) · 15.2 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// TODO: root level doc might be needed here. It's pretty complicated.
use async_trait::async_trait;
use futures::future::join_all;
use near_openapi_client::Client;
use std::sync::Arc;
use tracing::{debug, error, info, instrument};
use crate::{
config::{NetworkConfig, RetryResponse, retry},
errors::{ArgumentValidationError, QueryError, SendRequestError},
};
pub mod block_rpc;
pub mod handlers;
pub mod query_request;
pub mod query_rpc;
pub mod validator_rpc;
pub use handlers::*;
const QUERY_EXECUTOR_TARGET: &str = "near_api::query::executor";
type ResultWithMethod<T, E> = core::result::Result<T, QueryError<E>>;
#[async_trait]
pub trait RpcType: Send + Sync + std::fmt::Debug {
type RpcReference: Send + Sync + Clone;
type Response;
type Error: std::fmt::Debug + Send + Sync;
async fn send_query(
&self,
client: &Client,
network: &NetworkConfig,
reference: &Self::RpcReference,
) -> RetryResponse<Self::Response, SendRequestError<Self::Error>>;
}
pub type RequestBuilder<T> = RpcBuilder<<T as ResponseHandler>::Query, T>;
pub type MultiRequestBuilder<T> = MultiRpcBuilder<<T as ResponseHandler>::Query, T>;
/// A builder for querying multiple items at once.
///
/// Sometimes to construct some complex type, you would need to query multiple items at once, and combine them into one.
/// This is where this builder comes in handy. Almost every time, you would want to use [Self::map] method to combine the responses into your desired type.
///
/// Currently, `MultiQueryHandler` supports tuples of sizes 2 and 3.
/// For single responses, use `RequestBuilder` instead.
///
/// Here is a list of examples on how to use this:
/// - [Tokens::ft_balance](crate::tokens::Tokens::ft_balance)
/// - [StakingPool::staking_pool_info](crate::stake::Staking::staking_pool_info)
pub struct MultiRpcBuilder<Query, Handler>
where
Query: RpcType,
Query::Response: std::fmt::Debug + Send + Sync,
Query::Error: std::fmt::Debug + Send + Sync,
Handler: Send + Sync,
{
reference: Query::RpcReference,
#[allow(clippy::type_complexity)]
requests: Vec<
Result<
Arc<
dyn RpcType<
Response = Query::Response,
RpcReference = Query::RpcReference,
Error = Query::Error,
> + Send
+ Sync,
>,
ArgumentValidationError,
>,
>,
handler: Handler,
}
impl<Query, Handler> MultiRpcBuilder<Query, Handler>
where
Handler: Default + Send + Sync,
Query: RpcType,
Query::Response: std::fmt::Debug + Send + Sync,
Query::Error: std::fmt::Debug + Send + Sync,
{
pub fn with_reference(reference: impl Into<Query::RpcReference>) -> Self {
Self {
reference: reference.into(),
requests: vec![],
handler: Default::default(),
}
}
}
impl<Query, Handler> MultiRpcBuilder<Query, Handler>
where
Handler: ResponseHandler<Query = Query> + Send + Sync,
Query: RpcType,
Query::Response: std::fmt::Debug + Send + Sync,
Query::Error: std::fmt::Debug + Send + Sync,
{
pub fn new(handler: Handler, reference: impl Into<Query::RpcReference>) -> Self {
Self {
reference: reference.into(),
requests: vec![],
handler,
}
}
/// Map response of the queries to another type. The `map` function is executed after the queries are fetched.
///
/// The `Handler::Response` is the type returned by the handler's `process_response` method.
///
/// For single responses, use `RequestBuilder` instead.
///
/// ## Example
/// ```rust,no_run
/// use near_api::advanced::{MultiQueryHandler, CallResultHandler, MultiRpcBuilder};
/// use near_api::types::{Data, Reference};
/// use std::marker::PhantomData;
///
/// // Create a handler for multiple query responses and specify the types of the responses
/// let handler = MultiQueryHandler::new((
/// CallResultHandler::<String>::new(),
/// CallResultHandler::<u128>::new(),
/// ));
///
/// // Create the builder with the handler
/// let builder = MultiRpcBuilder::new(handler, Reference::Optimistic);
///
/// // Add queries to the builder
/// builder.add_query(todo!());
///
/// // Map the tuple of responses to a combined type
/// let mapped_builder = builder.map(|(response1, response2): (Data<String>, Data<u128>)| {
/// // Process the combined data
/// format!("{}: {}", response1.data, response2.data)
/// });
/// ```
///
/// See [Tokens::ft_balance](crate::tokens::Tokens::ft_balance) implementation for a real-world example.
pub fn map<MappedType>(
self,
map: impl Fn(Handler::Response) -> MappedType + Send + Sync + 'static,
) -> MultiRpcBuilder<Query, PostprocessHandler<MappedType, Handler>> {
MultiRpcBuilder {
handler: PostprocessHandler::new(self.handler, map),
requests: self.requests,
reference: self.reference,
}
}
/// Post-process the response of the query with error handling
///
/// This is useful if you want to convert one type to another but your function might fail.
///
/// The error will be wrapped in a `QueryError::ConversionError` and returned to the caller.
///
/// ## Example
/// ```rust,no_run
/// use near_api::*;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let balance: NearToken = Contract("some_contract.testnet".parse()?)
/// .call_function("get_balance", ())
/// .read_only()
/// .and_then(|balance: Data<String>| Ok(NearToken::from_yoctonear(balance.data.parse()?)))
/// .fetch_from_testnet()
/// .await?;
/// println!("Balance: {}", balance);
/// # Ok(())
/// # }
/// ```
pub fn and_then<MappedType>(
self,
map: impl Fn(Handler::Response) -> Result<MappedType, Box<dyn std::error::Error + Send + Sync>>
+ Send
+ Sync
+ 'static,
) -> MultiRpcBuilder<Query, AndThenHandler<MappedType, Handler>> {
MultiRpcBuilder {
handler: AndThenHandler::new(self.handler, map),
requests: self.requests,
reference: self.reference,
}
}
/// Add a query to the queried items. Sometimes you might need to query multiple items at once.
/// To combine the result of multiple queries into one.
pub fn add_query(
mut self,
request: Arc<
dyn RpcType<
Response = Query::Response,
RpcReference = Query::RpcReference,
Error = Query::Error,
> + Send
+ Sync,
>,
) -> Self {
self.requests.push(Ok(request));
self
}
/// It might be easier to use this method to add a query builder to the queried items.
pub fn add_query_builder<Handler2>(mut self, query_builder: RpcBuilder<Query, Handler2>) -> Self
where
Handler2: ResponseHandler<Query = Query> + Send + Sync,
{
self.requests.push(query_builder.request);
self
}
/// Set the block reference for the queries.
pub fn at(self, reference: impl Into<Query::RpcReference>) -> Self {
Self {
reference: reference.into(),
..self
}
}
/// Fetch the queries from the provided network.
#[instrument(skip(self, network), fields(request_count = self.requests.len()))]
pub async fn fetch_from(
self,
network: &NetworkConfig,
) -> ResultWithMethod<Handler::Response, Query::Error> {
let (requests, errors) =
self.requests
.into_iter()
.fold((vec![], vec![]), |(mut v, mut e), r| {
match r {
Ok(val) => v.push(val),
Err(err) => e.push(err),
}
(v, e)
});
if !errors.is_empty() {
return Err(QueryError::ArgumentValidationError(
ArgumentValidationError::multiple(errors),
));
}
debug!(target: QUERY_EXECUTOR_TARGET, "Preparing queries");
info!(target: QUERY_EXECUTOR_TARGET, "Sending {} queries", requests.len());
let requests = requests.into_iter().map(|request| {
let reference = &self.reference;
async move {
retry(network.clone(), |client| {
let request = &request;
async move {
let result = request.send_query(&client, network, reference).await;
tracing::debug!(
target: QUERY_EXECUTOR_TARGET,
"Querying RPC with {:?} resulted in {:?}",
request,
result
);
result
}
})
.await
}
});
let requests: Vec<_> = join_all(requests)
.await
.into_iter()
.collect::<Result<_, _>>()?;
if requests.is_empty() {
error!(target: QUERY_EXECUTOR_TARGET, "No responses received");
return Err(QueryError::InternalErrorNoResponse);
}
debug!(target: QUERY_EXECUTOR_TARGET, "Processing {} responses", requests.len());
self.handler.process_response(requests)
}
/// Fetch the queries from the default mainnet network configuration.
pub async fn fetch_from_mainnet(self) -> ResultWithMethod<Handler::Response, Query::Error> {
let network = NetworkConfig::mainnet();
self.fetch_from(&network).await
}
/// Fetch the queries from the default testnet network configuration.
pub async fn fetch_from_testnet(self) -> ResultWithMethod<Handler::Response, Query::Error> {
let network = NetworkConfig::testnet();
self.fetch_from(&network).await
}
}
pub struct RpcBuilder<Query, Handler>
where
Query: RpcType,
Query::Response: std::fmt::Debug + Send + Sync,
Query::Error: std::fmt::Debug + Send + Sync,
Handler: Send + Sync,
{
reference: Query::RpcReference,
#[allow(clippy::type_complexity)]
request: Result<
Arc<
dyn RpcType<
Response = Query::Response,
RpcReference = Query::RpcReference,
Error = Query::Error,
> + Send
+ Sync,
>,
ArgumentValidationError,
>,
handler: Handler,
}
impl<Query, Handler> RpcBuilder<Query, Handler>
where
Handler: ResponseHandler<Query = Query> + Send + Sync,
Query: RpcType + 'static,
Query::Response: std::fmt::Debug + Send + Sync,
Query::Error: std::fmt::Debug + Send + Sync,
{
pub fn new(
request: Query,
reference: impl Into<Query::RpcReference>,
handler: Handler,
) -> Self {
Self {
reference: reference.into(),
request: Ok(Arc::new(request)),
handler,
}
}
pub fn with_deferred_error(mut self, error: ArgumentValidationError) -> Self {
self.request = Err(error);
self
}
/// Set the block reference for the query.
pub fn at(self, reference: impl Into<Query::RpcReference>) -> Self {
Self {
reference: reference.into(),
..self
}
}
/// Post-process the response of the query.
///
/// This is useful if you want to convert one type to another.
///
/// ## Example
/// ```rust,no_run
/// use near_api::*;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let balance: NearToken = Contract("some_contract.testnet".parse()?)
/// .call_function("get_balance", ())
/// .read_only()
/// .map(|balance: Data<u128>| NearToken::from_yoctonear(balance.data))
/// .fetch_from_testnet()
/// .await?;
/// println!("Balance: {}", balance);
/// # Ok(())
/// # }
/// ```
pub fn map<MappedType>(
self,
map: impl Fn(Handler::Response) -> MappedType + Send + Sync + 'static,
) -> RpcBuilder<Query, PostprocessHandler<MappedType, Handler>> {
RpcBuilder {
handler: PostprocessHandler::new(self.handler, map),
request: self.request,
reference: self.reference,
}
}
/// Post-process the response of the query with error handling
///
/// This is useful if you want to convert one type to another but your function might fail.
///
/// The error will be wrapped in a `QueryError::ConversionError` and returned to the caller.
///
/// ## Example
/// ```rust,no_run
/// use near_api::*;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let balance: NearToken = Contract("some_contract.testnet".parse()?)
/// .call_function("get_balance", ())
/// .read_only()
/// .and_then(|balance: Data<String>| Ok(NearToken::from_yoctonear(balance.data.parse()?)))
/// .fetch_from_testnet()
/// .await?;
/// println!("Balance: {}", balance);
/// # Ok(())
/// # }
/// ```
pub fn and_then<MappedType>(
self,
map: impl Fn(Handler::Response) -> Result<MappedType, Box<dyn std::error::Error + Send + Sync>>
+ Send
+ Sync
+ 'static,
) -> RpcBuilder<Query, AndThenHandler<MappedType, Handler>> {
RpcBuilder {
handler: AndThenHandler::new(self.handler, map),
request: self.request,
reference: self.reference,
}
}
/// Fetch the query from the provided network.
#[instrument(skip(self, network))]
pub async fn fetch_from(
self,
network: &NetworkConfig,
) -> ResultWithMethod<Handler::Response, Query::Error> {
let request = self.request?;
debug!(target: QUERY_EXECUTOR_TARGET, "Preparing query");
let query_response = retry(network.clone(), |client| {
let request = &request;
let reference = &self.reference;
async move {
let result = request.send_query(&client, network, reference).await;
tracing::debug!(
target: QUERY_EXECUTOR_TARGET,
"Querying RPC with {:?} resulted in {:?}",
request,
result
);
result
}
})
.await?;
debug!(target: QUERY_EXECUTOR_TARGET, "Processing query response");
self.handler.process_response(vec![query_response])
}
/// Fetch the query from the default mainnet network configuration.
pub async fn fetch_from_mainnet(self) -> ResultWithMethod<Handler::Response, Query::Error> {
let network = NetworkConfig::mainnet();
self.fetch_from(&network).await
}
/// Fetch the query from the default testnet network configuration.
pub async fn fetch_from_testnet(self) -> ResultWithMethod<Handler::Response, Query::Error> {
let network = NetworkConfig::testnet();
self.fetch_from(&network).await
}
}