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