Skip to main content

github_rust/github/
service.rs

1use crate::error::*;
2use crate::github::client::GitHubClient;
3use crate::github::graphql::{self, Repository};
4use crate::github::{rest, search};
5
6/// REST fallback policy for authenticated repository lookups.
7#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
8pub enum FallbackPolicy {
9    /// Preserve every GraphQL error without trying REST.
10    Never,
11    /// Try REST only when GraphQL returns HTTP 502, 503 or 504.
12    #[default]
13    OnServerUnavailable,
14}
15
16/// High-level service for GitHub API operations.
17///
18/// `GitHubService` is the main entry point for interacting with the GitHub API.
19/// It provides a simple, ergonomic interface with automatic fallback from GraphQL
20/// to REST API when needed.
21///
22/// # Authentication
23///
24/// The service automatically detects the `GITHUB_TOKEN` environment variable.
25/// Token permissions control access. Quotas vary by API resource and token type.
26///
27/// # Example
28///
29/// ```no_run
30/// use github_rust::GitHubService;
31///
32/// # async fn example() -> github_rust::Result<()> {
33/// let service = GitHubService::new()?;
34///
35/// // Check authentication status
36/// if service.has_token() {
37///     println!("Authenticated with higher rate limits");
38/// }
39///
40/// // Get repository information
41/// let repo = service.get_repository_info("rust-lang", "rust").await?;
42/// println!("{} has {} stars", repo.name_with_owner, repo.stargazer_count);
43/// # Ok(())
44/// # }
45/// ```
46pub struct GitHubService {
47    /// The underlying HTTP client with connection pooling.
48    pub client: GitHubClient,
49    fallback_policy: FallbackPolicy,
50    pub(crate) fetch_options: super::FetchOptions,
51}
52
53impl GitHubService {
54    /// Creates a new GitHub service with default configuration.
55    ///
56    /// Automatically detects `GITHUB_TOKEN` from environment variables.
57    ///
58    /// # Errors
59    ///
60    /// Returns an error if the HTTP client cannot be initialized (rare, typically
61    /// indicates system-level TLS or network configuration issues).
62    ///
63    /// # Example
64    ///
65    /// ```no_run
66    /// use github_rust::GitHubService;
67    ///
68    /// let service = GitHubService::new()?;
69    /// # Ok::<(), github_rust::GitHubError>(())
70    /// ```
71    #[must_use = "Creating a service without using it is wasteful"]
72    pub fn new() -> Result<Self> {
73        let client = GitHubClient::new()?;
74        Ok(Self::with_client(client))
75    }
76
77    /// Creates a GitHub service with a custom client.
78    ///
79    /// Useful for testing or when you need custom HTTP configuration.
80    #[must_use]
81    pub fn with_client(client: GitHubClient) -> Self {
82        Self {
83            client,
84            fallback_policy: FallbackPolicy::default(),
85            fetch_options: super::FetchOptions::default(),
86        }
87    }
88
89    /// Selects which authenticated GraphQL failures may trigger REST.
90    /// Anonymous repository lookups always use REST directly.
91    #[must_use]
92    pub fn with_fallback_policy(mut self, policy: FallbackPolicy) -> Self {
93        self.fallback_policy = policy;
94        self
95    }
96
97    /// Fetches detailed information about a GitHub repository.
98    ///
99    /// Uses REST directly without a token. Authenticated lookups use GraphQL,
100    /// with REST fallback only for HTTP 502/503/504 by default.
101    /// Authentication, permission, quota and decoding errors are returned unchanged.
102    ///
103    /// # Arguments
104    ///
105    /// * `owner` - Repository owner (username or organization)
106    /// * `name` - Repository name
107    ///
108    /// # Returns
109    ///
110    /// Full repository details including stars, forks, language, topics, license, etc.
111    ///
112    /// # Errors
113    ///
114    /// * [`GitHubError::NotFoundError`] - Repository doesn't exist or is private without auth
115    /// * [`GitHubError::RateLimitError`] - API rate limit exceeded
116    /// * [`GitHubError::AccessBlockedError`] - Repository access blocked by GitHub
117    /// * [`GitHubError::DmcaBlockedError`] - Repository blocked for legal reasons
118    ///
119    /// # Example
120    ///
121    /// ```no_run
122    /// # use github_rust::GitHubService;
123    /// # async fn example() -> github_rust::Result<()> {
124    /// let service = GitHubService::new()?;
125    /// let repo = service.get_repository_info("microsoft", "vscode").await?;
126    ///
127    /// println!("Name: {}", repo.name_with_owner);
128    /// println!("Stars: {}", repo.stargazer_count);
129    /// println!("Forks: {}", repo.fork_count);
130    /// if let Some(lang) = &repo.primary_language {
131    ///     println!("Language: {}", lang.name);
132    /// }
133    /// # Ok(())
134    /// # }
135    /// ```
136    pub async fn get_repository_info(&self, owner: &str, name: &str) -> Result<Repository> {
137        if !self.client.has_token() {
138            return rest::get_repository_info(&self.client, owner, name).await;
139        }
140        match graphql::get_repository_info(&self.client, owner, name).await {
141            Ok(repo) => Ok(repo),
142            Err(graphql_error)
143                if self.fallback_policy == FallbackPolicy::OnServerUnavailable
144                    && matches!(
145                        &graphql_error,
146                        GitHubError::ApiError {
147                            status: 502..=504,
148                            ..
149                        }
150                    ) =>
151            {
152                tracing::debug!("GraphQL unavailable, trying REST: {graphql_error}");
153                rest::get_repository_info(&self.client, owner, name)
154                    .await
155                    .map_err(|rest_error| GitHubError::FallbackError {
156                        graphql: Box::new(graphql_error),
157                        rest: Box::new(rest_error),
158                    })
159            }
160            Err(error) => Err(error),
161        }
162    }
163
164    /// Searches for recently created repositories with filtering options.
165    ///
166    /// Finds repositories created within the specified time period, filtered by
167    /// language and minimum star count. Results are sorted by stars (descending).
168    ///
169    /// # Arguments
170    ///
171    /// * `days_back` - Search for repos created in the last N days
172    /// * `limit` - Maximum number of results (capped at 1000)
173    /// * `language` - Optional programming language filter (e.g., "rust", "python", "C++")
174    /// * `min_stars` - Minimum number of stars required
175    ///
176    /// # Errors
177    ///
178    /// * [`GitHubError::InvalidInput`] - Invalid language parameter
179    /// * [`GitHubError::RateLimitError`] - API rate limit exceeded
180    /// * [`GitHubError::AuthenticationError`] - Token required for this operation
181    ///
182    /// # Example
183    ///
184    /// ```no_run
185    /// # use github_rust::GitHubService;
186    /// # async fn example() -> github_rust::Result<()> {
187    /// let service = GitHubService::new()?;
188    ///
189    /// // Find Rust repos created in last 30 days with 50+ stars
190    /// let repos = service.search_repositories(
191    ///     30,           // days back
192    ///     100,          // limit
193    ///     Some("rust"), // language
194    ///     50,           // min stars
195    /// ).await?;
196    ///
197    /// for repo in repos {
198    ///     println!("{}: {} stars", repo.name_with_owner, repo.stargazer_count);
199    /// }
200    /// # Ok(())
201    /// # }
202    /// ```
203    pub async fn search_repositories(
204        &self,
205        days_back: u32,
206        limit: usize,
207        language: Option<&str>,
208        min_stars: u32,
209    ) -> Result<Vec<search::SearchRepository>> {
210        search::search_repositories(&self.client, days_back, limit, language, min_stars).await
211    }
212
213    /// Checks the current GitHub API rate limit status.
214    ///
215    /// Useful for monitoring API usage and implementing backoff strategies.
216    ///
217    /// # Returns
218    ///
219    /// Rate limit information including limit, remaining requests, and reset time.
220    ///
221    /// # Example
222    ///
223    /// ```no_run
224    /// # use github_rust::GitHubService;
225    /// # async fn example() -> github_rust::Result<()> {
226    /// let service = GitHubService::new()?;
227    /// let limits = service.check_rate_limit().await?;
228    ///
229    /// println!("Remaining: {}/{}", limits.remaining, limits.limit);
230    /// println!("Resets at: {:?}", limits.reset_datetime());
231    ///
232    /// if limits.is_exceeded() {
233    ///     println!("Rate limited! Wait {:?}", limits.time_until_reset());
234    /// }
235    /// # Ok(())
236    /// # }
237    /// ```
238    pub async fn check_rate_limit(&self) -> Result<crate::RateLimit> {
239        self.client.check_rate_limit().await
240    }
241
242    /// Returns separate REST core, search and GraphQL quotas when available.
243    pub async fn check_rate_limits(&self) -> Result<crate::RateLimits> {
244        self.client.check_rate_limits().await
245    }
246
247    /// Returns whether a GitHub token is configured.
248    ///
249    /// Useful for conditional logic based on authentication status.
250    ///
251    /// # Example
252    ///
253    /// ```no_run
254    /// # use github_rust::GitHubService;
255    /// let service = GitHubService::new()?;
256    ///
257    /// if service.has_token() {
258    ///     println!("Token configured");
259    /// } else {
260    ///     println!("Anonymous access");
261    /// }
262    /// # Ok::<(), github_rust::GitHubError>(())
263    /// ```
264    #[must_use]
265    pub fn has_token(&self) -> bool {
266        self.client.has_token()
267    }
268
269    /// Gets all repositories starred by the authenticated user.
270    ///
271    /// Requires authentication via `GITHUB_TOKEN`.
272    ///
273    /// # Returns
274    ///
275    /// List of repository full names in "owner/repo" format.
276    /// Returns a pagination error if more than 100 pages must be fetched.
277    ///
278    /// # Errors
279    ///
280    /// * [`GitHubError::AuthenticationError`] - No token or invalid token
281    /// * [`GitHubError::RateLimitError`] - API rate limit exceeded
282    ///
283    /// # Example
284    ///
285    /// ```no_run
286    /// # use github_rust::GitHubService;
287    /// # async fn example() -> github_rust::Result<()> {
288    /// let service = GitHubService::new()?;
289    /// let starred = service.get_user_starred_repositories().await?;
290    ///
291    /// println!("You have starred {} repositories", starred.len());
292    /// for repo in starred.iter().take(5) {
293    ///     println!("  - {}", repo);
294    /// }
295    /// # Ok(())
296    /// # }
297    /// ```
298    pub async fn get_user_starred_repositories(&self) -> Result<Vec<String>> {
299        rest::get_user_starred_repositories(&self.client).await
300    }
301
302    /// Gets the profile of the authenticated user.
303    ///
304    /// Requires authentication via `GITHUB_TOKEN`.
305    ///
306    /// # Errors
307    ///
308    /// * [`GitHubError::AuthenticationError`] - No token or invalid token
309    ///
310    /// # Example
311    ///
312    /// ```no_run
313    /// # use github_rust::GitHubService;
314    /// # async fn example() -> github_rust::Result<()> {
315    /// let service = GitHubService::new()?;
316    /// let profile = service.get_user_profile().await?;
317    ///
318    /// println!("Logged in as: {}", profile.login);
319    /// if let Some(name) = profile.name {
320    ///     println!("Name: {}", name);
321    /// }
322    /// # Ok(())
323    /// # }
324    /// ```
325    pub async fn get_user_profile(&self) -> Result<rest::UserProfile> {
326        rest::get_user_profile(&self.client).await
327    }
328
329    /// Gets users who starred a repository with timestamps.
330    ///
331    /// Returns stargazers with the date they starred the repository.
332    /// Supports pagination. GitHub restricts listing access to repository admins
333    /// and collaborators; empty results may also reflect access restrictions.
334    ///
335    /// # Arguments
336    ///
337    /// * `owner` - Repository owner
338    /// * `name` - Repository name
339    /// * `per_page` - Results per page (max 100, default 30)
340    /// * `page` - Page number (default 1)
341    ///
342    /// # Errors
343    ///
344    /// * [`GitHubError::NotFoundError`] - Repository not found
345    /// * [`GitHubError::RateLimitError`] - API rate limit exceeded
346    ///
347    /// # Example
348    ///
349    /// ```no_run
350    /// # use github_rust::GitHubService;
351    /// # async fn example() -> github_rust::Result<()> {
352    /// let service = GitHubService::new()?;
353    ///
354    /// // Get first 100 stargazers
355    /// let stargazers = service.get_repository_stargazers(
356    ///     "rust-lang", "rust",
357    ///     Some(100),  // per_page
358    ///     Some(1),    // page
359    /// ).await?;
360    ///
361    /// for sg in stargazers {
362    ///     println!("{} starred at {}", sg.user.login, sg.starred_at);
363    /// }
364    /// # Ok(())
365    /// # }
366    /// ```
367    pub async fn get_repository_stargazers(
368        &self,
369        owner: &str,
370        name: &str,
371        per_page: Option<u32>,
372        page: Option<u32>,
373    ) -> Result<Vec<crate::github::types::StargazerWithDate>> {
374        rest::get_repository_stargazers(&self.client, owner, name, per_page, page).await
375    }
376}
377
378impl GitHubService {
379    /// Configure limits for account, owned-repository and open-work-item collections.
380    pub fn with_fetch_options(mut self, options: super::FetchOptions) -> Result<Self> {
381        self.fetch_options = options.validate()?;
382        Ok(self)
383    }
384
385    /// Fetch the authenticated account and all organizations visible to its token.
386    pub async fn get_viewer(&self) -> Result<super::Viewer> {
387        super::accounts::viewer(&self.client, self.fetch_options).await
388    }
389
390    /// List repositories owned by a user or organization, including visible private,
391    /// forked and archived repositories. Results are sorted by full name.
392    pub async fn get_owned_repositories(&self, login: &str) -> Result<super::OwnedRepositories> {
393        super::accounts::repositories(
394            &self.client,
395            login,
396            self.fetch_options,
397            None::<super::pagination::NoProgress<_>>,
398        )
399        .await
400    }
401
402    /// List owned repositories, lending each validated page to an asynchronous callback.
403    /// Use `async |page| { ...; Ok(()) }` to borrow the page across await points.
404    /// Pages are provisional until this method succeeds. A callback error or dropping
405    /// the returned future cancels traversal; no background tasks are spawned.
406    /// GitHub does not provide a transactional snapshot across pages.
407    pub async fn get_owned_repositories_with_progress<F>(
408        &self,
409        login: &str,
410        progress: F,
411    ) -> Result<super::OwnedRepositories>
412    where
413        F: AsyncFnMut(&super::RepositoryPage) -> Result<()>,
414    {
415        super::accounts::repositories(&self.client, login, self.fetch_options, Some(progress)).await
416    }
417}
418
419impl GitHubService {
420    /// Fetch every open work item in one repository, sorted by update time descending.
421    pub async fn get_open_issues(&self, owner: &str, name: &str) -> Result<Vec<super::Issue>> {
422        self.get_open_issues_for_repositories(&[super::RepositoryCoordinates::new(owner, name)?])
423            .await
424    }
425    /// Fetch open work items in explicit repository scopes without rediscovering ownership.
426    /// Archived repositories are included if supplied; applications choose their scopes.
427    pub async fn get_open_issues_for_repositories(
428        &self,
429        repositories: &[super::RepositoryCoordinates],
430    ) -> Result<Vec<super::Issue>> {
431        super::work_items::collect(
432            &self.client,
433            repositories,
434            self.fetch_options,
435            None::<super::pagination::NoProgress<_>>,
436        )
437        .await
438    }
439    /// Traverse repository scopes with bounded concurrency and lend each page to an async callback.
440    /// Empty scopes return immediately without authentication or a callback.
441    /// Use `async |page| { ...; Ok(()) }` to borrow the page across await points.
442    /// Pages are provisional until the whole call succeeds. Callback errors and dropping
443    /// the future cancel traversal. No tasks are spawned. Labels and assignees must fit
444    /// their embedded 100-node pages, otherwise this returns a pagination error.
445    /// Totals, cursors and repository identity are checked; GitHub offers no snapshot isolation.
446    pub async fn get_open_issues_with_progress<F>(
447        &self,
448        repositories: &[super::RepositoryCoordinates],
449        progress: F,
450    ) -> Result<Vec<super::Issue>>
451    where
452        F: AsyncFnMut(&super::WorkItemPage<super::Issue>) -> Result<()>,
453    {
454        super::work_items::collect(
455            &self.client,
456            repositories,
457            self.fetch_options,
458            Some(progress),
459        )
460        .await
461    }
462}
463
464impl GitHubService {
465    /// Fetch every open work item in one repository, sorted by update time descending.
466    pub async fn get_open_pull_requests(
467        &self,
468        owner: &str,
469        name: &str,
470    ) -> Result<Vec<super::PullRequest>> {
471        self.get_open_pull_requests_for_repositories(&[super::RepositoryCoordinates::new(
472            owner, name,
473        )?])
474        .await
475    }
476    /// Fetch open work items in explicit repository scopes without rediscovering ownership.
477    /// Archived repositories are included if supplied; applications choose their scopes.
478    pub async fn get_open_pull_requests_for_repositories(
479        &self,
480        repositories: &[super::RepositoryCoordinates],
481    ) -> Result<Vec<super::PullRequest>> {
482        super::work_items::collect(
483            &self.client,
484            repositories,
485            self.fetch_options,
486            None::<super::pagination::NoProgress<_>>,
487        )
488        .await
489    }
490    /// Traverse repository scopes with bounded concurrency and lend each page to an async callback.
491    /// Empty scopes return immediately without authentication or a callback.
492    /// Use `async |page| { ...; Ok(()) }` to borrow the page across await points.
493    /// Pages are provisional until the whole call succeeds. Callback errors and dropping
494    /// the future cancel traversal. No tasks are spawned. Labels and assignees must fit
495    /// their embedded 100-node pages, otherwise this returns a pagination error.
496    /// Totals, cursors and repository identity are checked; GitHub offers no snapshot isolation.
497    pub async fn get_open_pull_requests_with_progress<F>(
498        &self,
499        repositories: &[super::RepositoryCoordinates],
500        progress: F,
501    ) -> Result<Vec<super::PullRequest>>
502    where
503        F: AsyncFnMut(&super::WorkItemPage<super::PullRequest>) -> Result<()>,
504    {
505        super::work_items::collect(
506            &self.client,
507            repositories,
508            self.fetch_options,
509            Some(progress),
510        )
511        .await
512    }
513}
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518
519    #[test]
520    fn test_github_service_creation() {
521        let service = GitHubService::new();
522        assert!(service.is_ok());
523    }
524
525    #[test]
526    fn test_github_service_has_token_detection() {
527        let service = GitHubService::new().unwrap();
528        // Token detection should work without panicking
529        let _has_token = service.has_token();
530    }
531}