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
use std::error::Error;
use std::fmt::Formatter;
use std::str::FromStr;
use std::sync::Arc;
use parking_lot::Mutex;
use reqwest::{Client, Response};
use reqwest::header::{AsHeaderName, HeaderMap};
use serde::de::DeserializeOwned;
use tokio::task::JoinHandle;
use uuid::Uuid;
use crate::api::error::HypixelApiError;
use crate::api::throttler::RequestThrottler;
use crate::error::ErrorReply;
pub struct RequestHandler {
client: Client,
api_key: Uuid,
throttler: Arc<Mutex<RequestThrottler>>,
}
impl std::fmt::Debug for RequestHandler {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RequestHandler")
.field("client", &self.client)
.field("throttler", &self.throttler)
.finish()
}
}
impl RequestHandler {
/// Creates a new RequestHandler instance using an
/// [api_key](https://api.hypixel.net/#section/Authentication)
/// obtained from Hypixel.
///
/// [`RequestHandler::request`] can be used to queue as many
/// requests as required for execution without ever going over
/// the limit set by Hypixel's API. This limit is derived
/// automatically and thus can be completely avoided by user code.
///
/// # Examples
/// ```rust
/// use hypixel_api::RequestHandler;
/// # use uuid::Uuid;
/// # use std::str::FromStr;
///
/// # fn main() {
/// let api_key = Uuid::from_str(env!("HYPIXEL_API_KEY")).unwrap();
/// let request_handler = RequestHandler::new(api_key);
///
/// // Send requests ...
/// # }
/// ```
pub fn new(api_key: Uuid) -> Self {
RequestHandler {
client: Client::new(),
api_key,
throttler: RequestThrottler::new(),
}
}
/// Queues a new request for execution and returns a [`JoinHandle`] to it.
///
/// ## Arguments
/// `path` should be a relative path to the API (without leading `/`), such as `"key"`
/// or `"status?uuid=..."`. See the [API](https://api.hypixel.net/).
///
/// If `authenticated` is `true` then the API key will be sent along as a header.
///
/// # Errors
///
/// If any part of the execution process fails, a [`HypixelApiError`] will be returned.
///
/// # Examples
/// ```rust,no_run
/// # use uuid::Uuid;
/// # use std::str::FromStr;
/// # use hypixel_api::StatusReply;
/// use hypixel_api::RequestHandler;
///
/// # #[tokio::main]
/// # async fn main() {
/// let api_key = Uuid::from_str(env!("HYPIXEL_API_KEY")).unwrap();
/// let request_handler = RequestHandler::new(api_key);
/// let request1 = request_handler.request::<StatusReply>("status?uuid=069a79f4-44e9-4726-a5be-fca90e38aaf5", true);
///
/// // send more requests ...
///
/// let reply: StatusReply = request1.await.unwrap().unwrap();
/// // use reply ...
/// # }
/// ```
#[cfg_attr(feature = "tracing", tracing::instrument(name = "queue_req", skip(self)))]
pub fn request<T: DeserializeOwned + Send + 'static>(&self, path: &str, authenticated: bool) -> JoinHandle<Result<T, HypixelApiError>> {
let url = format!("https://api.hypixel.net/{}", path);
let api_key = self.api_key.hyphenated().to_string();
let client = self.client.clone();
let throttler = Arc::clone(&self.throttler);
tokio::spawn(async move {
let client = client;
let url = url;
let api_key = api_key;
let throttler = throttler;
loop {
match RequestHandler::try_request(&client, &url, &api_key, &throttler, authenticated).await {
Ok(Some(response)) => break response.json::<T>().await.map_err(|e| e.into()),
Err(error) => break Err(error),
_ => {}
}
}
})
}
#[cfg_attr(feature = "tracing", tracing::instrument(name = "try_send", level = "trace", skip_all))]
async fn try_request(client: &Client, url: &str, api_key: &str, throttler: &Arc<Mutex<RequestThrottler>>, authenticated: bool) -> Result<Option<Response>, HypixelApiError> {
let mut watcher = None;
loop {
let ticket = {
let mut throttler = throttler.lock();
let (ticket, wait_rx) = throttler.request_ticket();
if watcher.is_none() {
watcher = Some(wait_rx);
}
ticket
};
if ticket {
break Ok(());
}
if let Err(error) = watcher.as_mut().unwrap().changed().await {
break Err(error);
}
}?;
let mut response = client.get(url);
if authenticated {
response = response.header("API-Key", api_key);
}
let response = response.send().await?;
let status_code = response.status();
let headers = response.headers();
let time_before_reset = get_from_headers(headers, "ratelimit-reset", 10)?.max(1);
let requests_remaining = get_from_headers(headers, "ratelimit-remaining", 110)?.max(1);
let result_check = {
let mut throttler = throttler.lock();
throttler.on_received(status_code, time_before_reset, requests_remaining)
};
match result_check {
Ok(result) => {
if result {
Ok(Some(response))
} else {
Ok(None)
}
}
Err(HypixelApiError::UnexpectedResponseCode(code, _)) => {
let cause = response.json::<ErrorReply>().await.ok();
Err(HypixelApiError::UnexpectedResponseCode(code, cause))
}
Err(error) => Err(error)
}
}
}
fn get_from_headers<K: AsHeaderName, E: Error + Send + Sync + 'static, T: FromStr<Err=E> + Copy>(headers: &HeaderMap, name: K, default: T) -> Result<T, HypixelApiError> {
headers.get(name)
.map(|o| o.to_str())
.map(|o| o.map_or(Ok(default), |s| s.parse::<T>().map_err(|_| HypixelApiError::IntFromStrError(String::from(s)))))
.unwrap_or(Ok(default))
}