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/// Configures HTTP requests and authentication, and retrieves quota information.
9/// Requests are not automatically delayed or retried when quotas are exhausted.
10/// For most use cases, prefer using [`GitHubService`](crate::GitHubService) instead.
11#[derive(Clone)]
12pub struct GitHubClient {
13    client: Client,
14    rest_url: String,
15    graphql_url: String,
16    /// Token stored securely - automatically zeroized on drop
17    token: Option<SecretString>,
18}
19
20impl GitHubClient {
21    /// Creates a new GitHub API client with connection pooling and optional token authentication.
22    ///
23    /// Reads `GITHUB_TOKEN` from the environment. An unset, empty or whitespace-only
24    /// variable produces an anonymous client; the builder itself still rejects empty tokens.
25    /// The token is stored securely using [`SecretString`] and is automatically
26    /// zeroized when the client is dropped.
27    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    /// Creates a builder with no token; environment variables are not read.
39    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    /// Raw HTTP transport. Library authentication headers are added only by API methods.
82    #[must_use]
83    pub fn client(&self) -> &Client {
84        &self.client
85    }
86
87    /// Returns the REST core quota. Use `check_rate_limits` for GraphQL and search quotas.
88    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    /// Retrieves separate quotas for every resource returned by GitHub.
97    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/// Quotas indexed by GitHub resource names such as `core`, `search` and `graphql`.
107#[derive(Debug, Clone, serde::Deserialize)]
108pub struct RateLimits {
109    pub resources: std::collections::BTreeMap<String, RateLimit>,
110}
111
112/// Explicit configuration for authentication, endpoints and HTTP transport.
113///
114/// Custom endpoints receive the configured token. Only use endpoints you trust.
115/// An injected HTTP client controls timeouts, proxies and redirects.
116pub 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    /// Set the token, for example `.token("your-token".into())`.
136    /// Empty tokens and invalid authorization header values are rejected by `build()`.
137    pub fn token(mut self, token: SecretString) -> Self {
138        self.token = Some(token);
139        self
140    }
141
142    /// Use this transport's timeout, proxy and redirect policy instead of the defaults.
143    pub fn http_client(mut self, client: Client) -> Self {
144        self.client = Some(client);
145        self
146    }
147
148    /// Set the REST base URL, including any Enterprise API prefix.
149    /// Configure `graphql_url` separately when using a custom installation.
150    pub fn rest_url(mut self, url: impl Into<String>) -> Self {
151        self.rest_url = url.into();
152        self
153    }
154
155    /// Set the complete GraphQL endpoint URL. It receives the configured token.
156    pub fn graphql_url(mut self, url: impl Into<String>) -> Self {
157        self.graphql_url = url.into();
158        self
159    }
160
161    /// Validate endpoints and token, then create the client.
162    /// The default transport uses a 30-second request timeout.
163    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 paths are appended to this base; the GraphQL URL is posted to as given.
197            rest_url: self.rest_url.trim_end_matches('/').to_owned(),
198            graphql_url: self.graphql_url,
199        })
200    }
201}
202
203/// GitHub API rate limit information.
204///
205/// Provides information about API usage limits and reset times.
206/// Quotas depend on the API resource and authentication type.
207#[derive(Debug, Clone, serde::Deserialize)]
208pub struct RateLimit {
209    /// Maximum requests or points allowed in the current resource-specific window
210    pub limit: u64,
211    /// Number of requests remaining in the current window
212    pub remaining: u64,
213    /// Unix timestamp when the rate limit resets
214    pub reset: u64,
215}
216
217impl RateLimit {
218    /// Returns the reset datetime, or None if the timestamp cannot be represented.
219    #[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    /// Returns the duration until the rate limit resets.
227    #[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    /// Returns true if the rate limit has been exceeded (no requests remaining).
238    #[must_use]
239    pub fn is_exceeded(&self) -> bool {
240        self.remaining == 0
241    }
242
243    /// Returns the number of requests used in the current window.
244    #[must_use]
245    pub fn used(&self) -> u64 {
246        self.limit.saturating_sub(self.remaining)
247    }
248}