Skip to main content

github_rust/github/
client.rs

1use crate::{config::*, error::*};
2use reqwest::{Client, Url, header::HeaderValue};
3use secrecy::{ExposeSecret, SecretString};
4use std::env;
5
6/// Low-level GitHub API client with connection pooling.
7///
8/// Handles HTTP requests, authentication, and rate limiting.
9/// For most use cases, prefer using [`GitHubService`](crate::GitHubService) instead.
10#[derive(Clone)]
11pub struct GitHubClient {
12    client: Client,
13    rest_url: String,
14    graphql_url: String,
15    /// Token stored securely - automatically zeroized on drop
16    token: Option<SecretString>,
17}
18
19impl GitHubClient {
20    /// Creates a new GitHub API client with connection pooling and optional token authentication.
21    ///
22    /// Automatically detects `GITHUB_TOKEN` from environment variables.
23    /// The token is stored securely using [`SecretString`] and is automatically
24    /// zeroized when the client is dropped.
25    #[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    /// Creates a builder with no token; environment variables are not read.
35    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    /// Raw HTTP transport. Library authentication headers are added only by API methods.
78    #[must_use]
79    pub fn client(&self) -> &Client {
80        &self.client
81    }
82
83    /// Returns the REST core quota. Use `check_rate_limits` for GraphQL and search quotas.
84    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    /// Retrieves separate quotas for every resource returned by GitHub.
93    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/// Quotas indexed by GitHub resource names such as `core`, `search` and `graphql`.
103#[derive(Debug, Clone, serde::Deserialize)]
104pub struct RateLimits {
105    pub resources: std::collections::BTreeMap<String, RateLimit>,
106}
107
108/// Explicit configuration for authentication, endpoints and HTTP transport.
109///
110/// Custom endpoints receive the configured token. Only use endpoints you trust.
111/// An injected HTTP client controls timeouts, proxies and redirects.
112pub 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/// GitHub API rate limit information.
191///
192/// Provides information about API usage limits and reset times.
193/// Quotas depend on the API resource and authentication type.
194#[derive(Debug, Clone, serde::Deserialize)]
195pub struct RateLimit {
196    /// Maximum requests or points allowed in the current resource-specific window
197    pub limit: u64,
198    /// Number of requests remaining in the current window
199    pub remaining: u64,
200    /// Unix timestamp when the rate limit resets
201    pub reset: u64,
202}
203
204impl RateLimit {
205    /// Returns the reset datetime, or None if the timestamp cannot be represented.
206    #[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    /// Returns the duration until the rate limit resets.
214    #[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    /// Returns true if the rate limit has been exceeded (no requests remaining).
225    #[must_use]
226    pub fn is_exceeded(&self) -> bool {
227        self.remaining == 0
228    }
229
230    /// Returns the number of requests used in the current window.
231    #[must_use]
232    pub fn used(&self) -> u64 {
233        self.limit.saturating_sub(self.remaining)
234    }
235}