summaryrefslogtreecommitdiffstats
path: root/github_v3/src/lib.rs
blob: 4fb75bb89aa7f337f6569c3825ff7df65e69c716 (plain)
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
use futures::Stream;
pub use futures::StreamExt;
pub use reqwest::header::HeaderMap;
pub use reqwest::header::HeaderValue;
pub use reqwest::StatusCode;
use serde::de::DeserializeOwned;
use std::sync::atomic::AtomicU32;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

pub struct Response {
    res: reqwest::Response,
    client: Arc<ClientInner>,
}

impl Response {
    pub async fn obj<T: DeserializeOwned>(self) -> Result<T, GHError> {
        Ok(self.res.json().await?)
    }

    pub fn array<T: DeserializeOwned + std::marker::Unpin + 'static>(self) -> impl Stream<Item = Result<T, GHError>> {
        let mut res = self.res;
        let client = self.client;

        // Pin is required for easy iteration, otherwise the caller would have to pin it
        Box::pin(async_stream::try_stream! {
            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).await?,
                    None => break,
                }
            }
        })
    }

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

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

pub struct Builder {
    client: Arc<ClientInner>,
    url: String,
}

impl Builder {
    pub fn path(mut self, url_part: &str) -> Self {
        debug_assert_eq!(url_part, url_part.trim_matches('/'));

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

    pub fn arg(mut self, arg: &str) -> Self {
        self.url.push('/');
        self.url.push_str(arg);
        self
    }

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

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

pub struct Client {
    inner: Arc<ClientInner>,
}

impl Client {
    pub fn new_from_env() -> Self {
        Self::new(std::env::var("GITHUB_TOKEN").ok().as_deref())
    }

    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"));
        if let Some(token) = token {
            default_headers.insert("Authorization", HeaderValue::from_str(&format!("token {}", token)).unwrap());
        }

        Self {
            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(7))
                    .timeout(Duration::from_secs(30))
                    .build()
                    .unwrap(),
                wait_sec: AtomicU32::new(0),
            }),
        }
    }

    pub fn get(&self) -> Builder {
        let mut url = String::with_capacity(60);
        url.push_str("https://api.github.com");
        Builder {
            client: self.inner.clone(),
            url,
        }
    }
}

impl ClientInner {
    // Get a single response
    async fn raw_get(&self, url: &str) -> 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_sec = self.wait_sec.load(SeqCst);
            if wait_sec > 0 {
                // This has poor behavior with concurrency. It should be pacing all requests.
                tokio::time::delay_for(Duration::from_secs(wait_sec.into())).await;
            }

            let res = self.client.get(url).send().await?;

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

            let wait_sec = match (Self::rate_limit_remaining(headers), Self::rate_limit_reset(headers)) {
                (Some(rl), Some(rs)) => {
                    rs.duration_since(SystemTime::now()).ok()
                        .and_then(|d| d.checked_div(rl + 2))
                        .map(|d| d.as_secs() as u32)
                        .unwrap_or(0)
                }
                _ => if status == StatusCode::TOO_MANY_REQUESTS {3} else {0},
            };
            self.wait_sec.store(wait_sec, SeqCst);

            let should_wait_for_content = status == StatusCode::ACCEPTED;
            if should_wait_for_content && retries > 0 {
                tokio::time::delay_for(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)
            };
        }
    }

    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())
    }

    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) = link.find('<') {
                let link = &link[start + 1..];
                if let Some(end) = link.find('>') {
                    return Some(link[..end].to_owned());
                }
            }
        }
    }
    None
}

#[derive(serde_derive::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::*;