github_rust/github/
client.rs1use crate::{config::*, error::*};
2use reqwest::{Client, Url, header::HeaderValue};
3use secrecy::{ExposeSecret, SecretString};
4use std::env;
5
6#[derive(Clone)]
12pub struct GitHubClient {
13 client: Client,
14 rest_url: String,
15 graphql_url: String,
16 token: Option<SecretString>,
18}
19
20impl GitHubClient {
21 pub fn new() -> Result<Self> {
28 let mut builder = Self::builder();
29 if let Some(token) = env::var("GITHUB_TOKEN")
30 .ok()
31 .filter(|token| !token.trim().is_empty())
32 {
33 builder = builder.token(SecretString::from(token));
34 }
35 builder.build()
36 }
37
38 pub fn builder() -> GitHubClientBuilder {
40 GitHubClientBuilder::default()
41 }
42
43 pub(crate) fn rest_url(&self) -> &str {
44 &self.rest_url
45 }
46
47 pub(crate) fn graphql_url(&self) -> &str {
48 &self.graphql_url
49 }
50
51 pub(crate) fn get(&self, url: impl reqwest::IntoUrl) -> reqwest::RequestBuilder {
52 self.request(reqwest::Method::GET, url)
53 }
54
55 pub(crate) fn post(&self, url: impl reqwest::IntoUrl) -> reqwest::RequestBuilder {
56 self.request(reqwest::Method::POST, url)
57 }
58
59 fn request(
60 &self,
61 method: reqwest::Method,
62 url: impl reqwest::IntoUrl,
63 ) -> reqwest::RequestBuilder {
64 let request = self
65 .client
66 .request(method, url)
67 .header("User-Agent", USER_AGENT)
68 .header("Accept", "application/vnd.github+json")
69 .header("X-GitHub-Api-Version", "2022-11-28");
70 match &self.token {
71 Some(token) => request.bearer_auth(token.expose_secret()),
72 None => request,
73 }
74 }
75
76 #[must_use]
77 pub fn has_token(&self) -> bool {
78 self.token.is_some()
79 }
80
81 #[must_use]
83 pub fn client(&self) -> &Client {
84 &self.client
85 }
86
87 pub async fn check_rate_limit(&self) -> Result<RateLimit> {
89 self.check_rate_limits()
90 .await?
91 .resources
92 .remove("core")
93 .ok_or_else(|| GitHubError::ParseError("Missing core rate limit resource".into()))
94 }
95
96 pub async fn check_rate_limits(&self) -> Result<RateLimits> {
98 let response = self
99 .get(format!("{}/rate_limit", self.rest_url()))
100 .send()
101 .await?;
102 Ok(super::response::check(response).await?.json().await?)
103 }
104}
105
106#[derive(Debug, Clone, serde::Deserialize)]
108pub struct RateLimits {
109 pub resources: std::collections::BTreeMap<String, RateLimit>,
110}
111
112pub struct GitHubClientBuilder {
117 client: Option<Client>,
118 token: Option<SecretString>,
119 rest_url: String,
120 graphql_url: String,
121}
122
123impl Default for GitHubClientBuilder {
124 fn default() -> Self {
125 Self {
126 client: None,
127 token: None,
128 rest_url: GITHUB_API_URL.to_owned(),
129 graphql_url: GITHUB_GRAPHQL_URL.to_owned(),
130 }
131 }
132}
133
134impl GitHubClientBuilder {
135 pub fn token(mut self, token: SecretString) -> Self {
138 self.token = Some(token);
139 self
140 }
141
142 pub fn http_client(mut self, client: Client) -> Self {
144 self.client = Some(client);
145 self
146 }
147
148 pub fn rest_url(mut self, url: impl Into<String>) -> Self {
151 self.rest_url = url.into();
152 self
153 }
154
155 pub fn graphql_url(mut self, url: impl Into<String>) -> Self {
157 self.graphql_url = url.into();
158 self
159 }
160
161 pub fn build(self) -> Result<GitHubClient> {
164 for endpoint in [&self.rest_url, &self.graphql_url] {
165 let url = Url::parse(endpoint)
166 .map_err(|_| GitHubError::ConfigError("Invalid API endpoint URL".into()))?;
167 if !matches!(url.scheme(), "http" | "https")
168 || url.host_str().is_none()
169 || !url.username().is_empty()
170 || url.password().is_some()
171 || url.query().is_some()
172 || url.fragment().is_some()
173 {
174 return Err(GitHubError::ConfigError(
175 "API endpoints must be HTTP(S) URLs without credentials, query or fragment"
176 .into(),
177 ));
178 }
179 }
180 if let Some(token) = &self.token {
181 if token.expose_secret().trim().is_empty() {
182 return Err(GitHubError::ConfigError(
183 "GitHub token cannot be empty".into(),
184 ));
185 }
186 HeaderValue::from_str(&format!("Bearer {}", token.expose_secret()))
187 .map_err(|_| GitHubError::ConfigError("Invalid Authorization header".into()))?;
188 }
189 let client = match self.client {
190 Some(client) => client,
191 None => Client::builder().timeout(DEFAULT_TIMEOUT).build()?,
192 };
193 Ok(GitHubClient {
194 client,
195 token: self.token,
196 rest_url: self.rest_url.trim_end_matches('/').to_owned(),
198 graphql_url: self.graphql_url,
199 })
200 }
201}
202
203#[derive(Debug, Clone, serde::Deserialize)]
208pub struct RateLimit {
209 pub limit: u64,
211 pub remaining: u64,
213 pub reset: u64,
215}
216
217impl RateLimit {
218 #[must_use]
220 pub fn reset_datetime(&self) -> Option<chrono::DateTime<chrono::Utc>> {
221 i64::try_from(self.reset)
222 .ok()
223 .and_then(|reset| chrono::DateTime::from_timestamp(reset, 0))
224 }
225
226 #[must_use]
228 pub fn time_until_reset(&self) -> std::time::Duration {
229 let now = chrono::Utc::now().timestamp() as u64;
230 if self.reset > now {
231 std::time::Duration::from_secs(self.reset - now)
232 } else {
233 std::time::Duration::ZERO
234 }
235 }
236
237 #[must_use]
239 pub fn is_exceeded(&self) -> bool {
240 self.remaining == 0
241 }
242
243 #[must_use]
245 pub fn used(&self) -> u64 {
246 self.limit.saturating_sub(self.remaining)
247 }
248}