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
use futures::Stream;
pub use futures::StreamExt;
pub use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::header::{ACCEPT, AUTHORIZATION};
pub use reqwest::{StatusCode, Url};
use serde::de::DeserializeOwned;
use std::panic::{RefUnwindSafe, UnwindSafe};
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

/// Response from the API
pub struct Response {
    res: reqwest::Response,
    client: Arc<ClientInner>,
    config: ConfigInner,
}

impl Response {
    /// Fetch a single JSON object from the API
    pub async fn obj<T: DeserializeOwned>(self) -> Result<T, GHError> {
        Ok(self.res.json().await?)
    }

    /// Stream an array of objects from the API
    pub fn array<T: DeserializeOwned + Unpin + 'static>(self) -> impl Stream<Item = Result<T, GHError>> {
        let mut res = self.res;
        let client = self.client;
        let config = self.config;

        // Pin is required for easy iteration, otherwise the caller would have to pin it
        Box::pin(async_stream::try_stream! {
            #[allow(clippy::large_futures)]
            loop {
                let next_link = res.headers().get("link")
                    .and_then(|h| h.to_str().ok())
                    .and_then(parse_next_link);
                let items = res.json::<Vec<T>>().await?;
                for item in items {
                    yield item;
                }
                match next_link {
                    Some(url) => res = client.raw_get(&url, &config).await?,
                    None => break,
                }
            }
        })
    }

    /// Response headers
    pub fn headers(&self) -> &HeaderMap {
        self.res.headers()
    }

    /// Response status
    pub fn status(&self) -> StatusCode {
        self.res.status()
    }

    /// Final URL
    pub fn url(&self) -> &Url {
        self.res.url()
    }
}

/// See `Client::get()`
///
/// Make a new request by constructing the request URL bit by bit
pub struct Builder {
    client: Arc<ClientInner>,
    config: ConfigInner,
    url: String,
    query_string_started: bool,
}

impl Builder {
    /// Add a constant path to the request, e.g. `.path("users")`
    ///
    /// Inner slashes are OK, but the string must not start or end with a slash.
    ///
    /// Panics if query string has been added.
    ///
    /// It's appended raw, so must be URL-safe.
    #[must_use]
    pub fn path(mut self, url_part: &'static str) -> Self {
        debug_assert_eq!(url_part, url_part.trim_matches('/'));
        assert!(!self.query_string_started);

        self.url.push('/');
        self.url.push_str(url_part);
        self
    }

    /// Add a user-supplied argument to the request path, e.g. `.path("users").arg(username)`,
    /// or after a call to `query()`, starts adding fragments to the query string with no delimiters.
    ///
    /// The arg is URL-escaped, so it's safe to use any user-supplied data.
    #[must_use]
    pub fn arg(mut self, arg: &str) -> Self {
        if !self.query_string_started {
            self.url.push('/');
        }
        use std::fmt::Write;
        write!(&mut self.url, "{}", urlencoding::Encoded(arg)).unwrap();
        self
    }

    /// Add a raw unescaped query string. The string must *not* start with `?`
    ///
    /// ```rust
    /// # github_v3::Client::new(None)
    /// .get().path("search/users").query("q=").arg("somestring");
    /// ```
    #[must_use]
    pub fn query(mut self, query_string: &str) -> Self {
        debug_assert!(!query_string.starts_with('?'));
        debug_assert!(!query_string.starts_with('&'));
        self.url.push(if self.query_string_started { '&' } else { '?' });
        self.url.push_str(query_string);
        self.query_string_started = true;
        self
    }

    /// Make the request
    pub async fn send(self) -> Result<Response, GHError> {
        let res = Box::pin(self.client.raw_get(&self.url, &self.config)).await?;
        Ok(Response {
            client: self.client,
            config: self.config,
            res,
        })
    }
}

struct ClientInner {
    client: reqwest::Client,
    // FIXME: this should be per endpoint, because search and others have different throttling
    wait_until_timestamp_ms: AtomicU64,
}

#[derive(Clone)]
struct ConfigInner {
    authorization_header: Option<HeaderValue>,
}

impl UnwindSafe for Client {}
impl RefUnwindSafe for Client {}

/// API Client. Start here.
#[derive(Clone)]
pub struct Client {
    inner: Arc<ClientInner>,
    config: ConfigInner,
}

impl Client {
    /// Reads `GITHUB_TOKEN` env var.
    #[must_use] pub fn new_from_env() -> Self {
        Self::new(std::env::var("GITHUB_TOKEN").ok().as_deref())
    }

    /// Takes API token for authenticated requests (make the token in GitHub settings)
    #[must_use]
    pub fn new(token: Option<&str>) -> Self {
        let mut default_headers = HeaderMap::with_capacity(2);
        default_headers.insert(ACCEPT, HeaderValue::from_static("application/vnd.github.v3+json"));
        default_headers.insert("X-GitHub-Api-Version", HeaderValue::from_static("2022-11-28"));

        Self {
            config: ConfigInner {
                authorization_header: token.and_then(|token| HeaderValue::from_str(&format!("token {token}")).ok()),
            },
            inner: Arc::new(ClientInner {
                client: reqwest::Client::builder()
                    .user_agent(concat!("rust-github-v3/{}", env!("CARGO_PKG_VERSION")))
                    .default_headers(default_headers)
                    .connect_timeout(Duration::from_secs(4))
                    .timeout(Duration::from_secs(20))
                    .build()
                    .unwrap(),
                wait_until_timestamp_ms: AtomicU64::new(0),
            }),
        }
    }

    /// Takes raw header value (e.g. "Bearer …")
    #[must_use]
    pub fn with_authorization(&self, header: Option<&str>) -> Self {
        Self {
            config: ConfigInner {
                authorization_header: header.and_then(|header| HeaderValue::from_str(header).ok()),
            },
            inner: self.inner.clone(),
        }
    }

    /// Make a new request to the API.
    #[must_use]
    pub fn get(&self) -> Builder {
        let mut url = String::with_capacity(100);
        url.push_str("https://api.github.com");
        Builder {
            client: self.inner.clone(),
            config: self.config.clone(),
            url,
            query_string_started: false,
        }
    }

    pub fn wait_time(&self) -> Duration {
        self.inner.wait_time()
    }
}

impl ClientInner {
    fn wait_time(&self) -> Duration {
        let ts_ms = self.wait_until_timestamp_ms.load(SeqCst);
        let until = SystemTime::UNIX_EPOCH + Duration::from_millis(ts_ms);
        until.duration_since(SystemTime::now()).unwrap_or(Duration::ZERO)
    }

    // Get a single response
    async fn raw_get(&self, url: &str, config: &ConfigInner) -> Result<reqwest::Response, GHError> {
        debug_assert!(url.starts_with("https://api.github.com/"));

        let mut retries = 5u8;
        let mut retry_delay = 1;
        loop {
            let wait_duration = self.wait_time();
            if wait_duration > Duration::ZERO {
                // This has poor behavior with concurrency. It should be pacing all requests.
                tokio::time::sleep(wait_duration).await;
            }

            let mut req = self.client.get(url);
            if let Some(auth) = &config.authorization_header {
                req = req.header(AUTHORIZATION, auth);
            }

            let res = req.send().await?;

            let headers = res.headers();
            let status = res.status();

            let now = SystemTime::now();
            let wait_duration = match (Self::rate_limit_remaining(headers), Self::rate_limit_reset(headers)) {
                (Some(rl), Some(rs)) => {
                    rs.duration_since(now).ok()
                        .and_then(|d| d.checked_div(rl + 2))
                        .unwrap_or(Duration::ZERO)
                        .min(Duration::from_secs(30)) // 30s wait max
                }
                _ => Duration::from_secs(if status == StatusCode::TOO_MANY_REQUESTS {3} else {0}),
            };
            let wait_until = now + wait_duration;
            let wait_until_timestamp_ms = wait_until.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_millis() as u64;
            self.wait_until_timestamp_ms.store(wait_until_timestamp_ms, SeqCst);

            let should_wait_for_content = status == StatusCode::ACCEPTED;
            if should_wait_for_content && retries > 0 {
                tokio::time::sleep(Duration::from_secs(retry_delay)).await;
                retry_delay *= 2;
                retries -= 1;
                continue;
            }

            return if status.is_success() && !should_wait_for_content {
                Ok(res)
            } else {
                Err(error_for_response(res).await)
            };
        }
    }

    /// GitHub's `x-ratelimit-remaining` header
    pub fn rate_limit_remaining(headers: &HeaderMap) -> Option<u32> {
        headers.get("x-ratelimit-remaining")
            .and_then(|s| s.to_str().ok())
            .and_then(|s| s.parse().ok())
    }

    /// GitHub's `x-ratelimit-reset` header
    pub fn rate_limit_reset(headers: &HeaderMap) -> Option<SystemTime> {
        headers
            .get("x-ratelimit-reset")
            .and_then(|s| s.to_str().ok())
            .and_then(|s| s.parse().ok())
            .map(|s| SystemTime::UNIX_EPOCH + Duration::from_secs(s))
    }
}

async fn error_for_response(res: reqwest::Response) -> GHError {
    let status = res.status();
    let mime = res.headers().get("content-type").and_then(|h| h.to_str().ok()).unwrap_or("");
    GHError::Response {
        status,
        message: if mime.starts_with("application/json") {
            res.json::<GitHubErrorResponse>().await.ok().map(|res| res.message)
        } else {
            None
        },
    }
}

fn parse_next_link(link: &str) -> Option<String> {
    for part in link.split(',') {
        if part.contains(r#"; rel="next""#) {
            if let Some(start) = part.find('<') {
                let next_link = &part[start + 1..];
                if let Some(end) = next_link.find('>') {
                    return Some(next_link[..end].to_owned());
                }
            }
        }
    }
    None
}

#[derive(serde::Deserialize)]
struct GitHubErrorResponse {
    message: String,
}

use thiserror::Error;

#[derive(Error, Debug)]
pub enum GHError {
    #[error("Request timed out")]
    Timeout,
    #[error("Request error: {}", _0)]
    Request(String),
    #[error("{} ({})", message.as_deref().unwrap_or("HTTP error"), status)]
    Response { status: StatusCode, message: Option<String> },
    #[error("Internal error")]
    Internal,
}

impl From<reqwest::Error> for GHError {
    fn from(e: reqwest::Error) -> Self {
        if e.is_timeout() {
            return Self::Timeout;
        }
        if let Some(status) = e.status() {
            Self::Response {
                status,
                message: Some(e.to_string()),
            }
        } else {
            Self::Request(e.to_string())
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[tokio::test]
    async fn req_test() {
        let gh = Client::new_from_env();
        gh.get().path("users/octocat/orgs").send().await.unwrap();
    }

    #[test]
    fn parse_next_link_test() {
        let example = "\"<https://api.github.com/organizations/fakeid/repos?page=1>; rel=\"prev\", <https://api.github.com/organizations/fakeid/repos?page=3>; rel=\"next\", <https://api.github.com/organizations/fakeid/repos?page=38>; rel=\"last\", <https://api.github.com/organizations/fakeid/repos?page=1>; rel=\"first\"";

        let expected = Some(String::from("https://api.github.com/organizations/fakeid/repos?page=3"));
        assert_eq!(parse_next_link(example), expected);
    }
}