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
|
use std::sync::Arc;
use reqwest::r#async::Client as ReqwestClient;
pub use super::types;
pub mod endpoints;
pub mod models;
#[derive(Clone)]
pub struct Client {
inner: Arc<ClientRef>
}
impl Client {
pub fn new(id: &str) -> Client {
Client {
inner: Arc::new(ClientRef {
id: id.to_owned(),
client: ReqwestClient::new(),
})
}
}
pub fn new_with_client(id: &str, client: ReqwestClient) -> Client {
Client {
inner: Arc::new(ClientRef {
id: id.to_owned(),
client: client,
})
}
}
}
struct ClientRef {
id: String,
client: ReqwestClient,
}
/*
pub struct Limits {
global: LimiterRef
}
#[derive(Clone)]
pub struct LimiterRef {
inner: Arc<Mutex<Limiter>>
}
trait RateLimiter {
fn remaining(&self) -> usize;
fn limit(&self) -> usize;
}
impl RateLimiter for LimiterRef {
fn remaining(&self) -> usize {
let limits = self.inner.lock().unwrap();
limits.remaining
}
fn limit(&self) -> usize {
let limits = self.inner.lock().unwrap();
limits.limit
}
}
struct RequestJob {
pub request: Request,
pub on_complete: futures::sync::oneshot::Sender<Response>,
}
*/
/* API requests should be placed in a priority queue to prevent stravation.
* This implies that all requests are sent a single location and then returned
* to their callers upon completion.
* When a request is 'owned' by the queue it can be retryed when the rate limit
* is hit and allows inspect of response headers to determine remaining resources.
*/
/*
enum Task {
Add(RequestJob),
Drain,
}
pub struct Limiter {
pub remaining: u32,
pub limit: u32,
in_transit: u32,
pub last_request: Option<DateTime<Utc>>,
pub remaining_key: String,
pub limit_key: String,
pub queue: Vec<RequestJob>,
pub client: ReqwestClient,
pub chan: mpsc::UnboundedSender<Task>,
}
use futures::sync::oneshot;
fn handle_request(limits_ref: LimiterRef, request: RequestJob) {
let limits = limits_ref.inner.lock().unwrap();
limits.queue.push(request);
limits.chan.unbounded_send(Task::Drain);
}
fn handle_drain(limits_ref: LimiterRef) {
let jobs = {
let limits = limits_ref.inner.lock().unwrap();
let take =
std::cmp::max(limits.remaining - limits.in_transit, 0);
let jobs = Vec::new();
for i in 0..std::cmp::min(limits.queue.len() as u32, take) {
jobs.push(limits.queue.pop().unwrap());
}
limits.in_transit += jobs.len() as u32;
jobs
};
let client = {
let limits = limits_ref.inner.lock().unwrap();
&limits.client
};
if jobs.len() > 0 {
for job in jobs {
let clone = job.request.clone();
let f =
client.execute(job.request)
.and_then(move |response| {
let mut limits = limit_ref.inner.lock().unwrap();
limits.in_transit =
std::cmp::max(0, limits.in_transit - 1);
if response.status().is_success() {
let remaining = response.headers()
.get(limits.remaining_key)
.and_then(|value| value.to_str().ok())
.and_then(|remaining| remaining.parse::<usize>().ok());
let limit = response.headers()
.get(limits.limit_key)
.and_then(|value| value.to_str().ok())
.and_then(|remaining| remaining.parse::<usize>().ok());
if let Some(remaining) = remaining {
limits.remaining = remaining;
}
if let Some(limit) = remaining {
limits.limit = limit;
}
job.on_complete.send(Ok(response));
} else if response.status().is_client_error() {
limit.chan_tx.send(Handle(
RequestJob {
request: clone,
on_complete: job.on_complete.clone(),
}))
println!("Hit rate limit! or invalid client")
}
}
impl LimiterRef {
fn handle_drain(&self) {
}
fn handle_requests() {
chan_rx.for_each(move |task| {
match task {
Handle(request) => {
handle_request( tfdsf, request);
},
Drain => {
}
} else {
/*sleep...*/
}
}
}
Ok(())
})
.map(|_| ())
.map_err(|_| ())
}
fn new(limit: u32, remaining_key: &str, limit_key: &str, client: ReqwestClient)
-> LimiterRef
{
let (chan_tx, chan_rx) = mpsc::unbounded();
let limiter = Limiter {
remaining: limit,
limit: limit,
in_transit: 0,
last_request: None,
remaining_key: remaining_key.to_owned(),
limit_key: limit_key.to_owned(),
queue: Vec::new(),
client: client,
chan: chan_tx,
};
let _ref = LimiterRef {
inner: Arc::new(Mutex::new(limiter))
};
return _ref;
}
fn queue(&self, request: Request)
-> impl Future<Item=Result<Response, reqwest::Error>, Error=oneshot::Canceled> {
let mut limits = self.inner.lock().unwrap();
let limit_ref = self.clone();
let (tx, rx) = futures::sync::oneshot::channel();
let job = RequestJob {
request: request,
on_complete: tx,
};
limits.queue.push(job);
rx
}
/* Insert the request into a queue */
/*
Ok(response)
})
}
*/
}
*/
|