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/// Repository metadata lookups use REST anonymously, or GraphQL with optional
20/// REST fallback on HTTP 502, 503 and 504 when a token is configured.
21///
22/// # Authentication
23///
24/// [`Self::new()`] reads `GITHUB_TOKEN`. [`Self::with_client()`] uses the supplied
25/// client configuration without reading the environment.
26/// Token permissions control access. Quotas vary by API resource and token type.
27///
28/// # Example
29///
30/// ```no_run
31/// use github_rust::GitHubService;
32///
33/// # async fn example() -> github_rust::Result<()> {
34/// let service = GitHubService::new()?;
35///
36/// // Token presence does not verify permissions or quotas.
37/// if service.has_token() {
38/// println!("Token configured");
39/// }
40///
41/// // Get repository information
42/// let repo = service.get_repository_info("rust-lang", "rust").await?;
43/// println!("{} has {} stars", repo.name_with_owner, repo.stargazer_count);
44/// # Ok(())
45/// # }
46/// ```
47pub struct GitHubService {
48 /// The underlying HTTP client with connection pooling.
49 pub client: GitHubClient,
50 fallback_policy: FallbackPolicy,
51 pub(crate) fetch_options: super::FetchOptions,
52}
53
54impl GitHubService {
55 /// Creates a new GitHub service with default configuration.
56 ///
57 /// Reads `GITHUB_TOKEN`; an unset, empty or whitespace-only value selects anonymous access.
58 ///
59 /// # Errors
60 ///
61 /// Returns an error if a nonempty token cannot form an Authorization header
62 /// or the HTTP client cannot be initialized. Token permissions are checked by GitHub.
63 ///
64 /// # Example
65 ///
66 /// ```no_run
67 /// use github_rust::GitHubService;
68 ///
69 /// let service = GitHubService::new()?;
70 /// # Ok::<(), github_rust::GitHubError>(())
71 /// ```
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 /// REST uses two requests: metadata, then languages. Errors from the language
102 /// request propagate, except a 404 which leaves the breakdown unavailable.
103 /// Authentication, permission, quota and decoding errors are returned unchanged.
104 ///
105 /// # Arguments
106 ///
107 /// * `owner` - Repository owner (username or organization)
108 /// * `name` - Repository name
109 ///
110 /// # Returns
111 ///
112 /// Full repository details including stars, forks, language, topics, license, etc.
113 ///
114 /// # Errors
115 ///
116 /// * [`GitHubError::NotFoundError`] - Repository doesn't exist or is private without auth
117 /// * [`GitHubError::RateLimitError`] - API rate limit exceeded
118 /// * [`GitHubError::AccessBlockedError`] - Repository access blocked by GitHub
119 /// * [`GitHubError::DmcaBlockedError`] - Repository blocked for legal reasons
120 ///
121 /// # Example
122 ///
123 /// ```no_run
124 /// # use github_rust::GitHubService;
125 /// # async fn example() -> github_rust::Result<()> {
126 /// let service = GitHubService::new()?;
127 /// let repo = service.get_repository_info("microsoft", "vscode").await?;
128 ///
129 /// println!("Name: {}", repo.name_with_owner);
130 /// println!("Stars: {}", repo.stargazer_count);
131 /// println!("Forks: {}", repo.fork_count);
132 /// if let Some(lang) = &repo.primary_language {
133 /// println!("Language: {}", lang.name);
134 /// }
135 /// # Ok(())
136 /// # }
137 /// ```
138 pub async fn get_repository_info(&self, owner: &str, name: &str) -> Result<Repository> {
139 if !self.client.has_token() {
140 return rest::get_repository_info(&self.client, owner, name).await;
141 }
142 match graphql::get_repository_info(&self.client, owner, name).await {
143 Ok(repo) => Ok(repo),
144 Err(graphql_error)
145 if self.fallback_policy == FallbackPolicy::OnServerUnavailable
146 && matches!(
147 &graphql_error,
148 GitHubError::ApiError {
149 status: 502..=504,
150 ..
151 }
152 ) =>
153 {
154 tracing::debug!("GraphQL unavailable, trying REST: {graphql_error}");
155 rest::get_repository_info(&self.client, owner, name)
156 .await
157 .map_err(|rest_error| GitHubError::FallbackError {
158 graphql: Box::new(graphql_error),
159 rest: Box::new(rest_error),
160 })
161 }
162 Err(error) => Err(error),
163 }
164 }
165
166 /// Searches for recently created repositories with filtering options.
167 ///
168 /// Finds repositories created within the specified time period, filtered by
169 /// language and minimum star count. Results are sorted by stars (descending).
170 ///
171 /// # Arguments
172 ///
173 /// * `days_back` - Search for repos created in the last N days
174 /// * `limit` - Maximum number of results (capped at 1000)
175 /// * `language` - Optional programming language filter (e.g., "rust", "python", "C++")
176 /// * `min_stars` - Minimum number of stars required
177 ///
178 /// # Errors
179 ///
180 /// * [`GitHubError::InvalidInput`] - Invalid language parameter
181 /// * [`GitHubError::RateLimitError`] - API rate limit exceeded
182 /// * [`GitHubError::AuthenticationError`] - Token required for this operation
183 ///
184 /// # Example
185 ///
186 /// ```no_run
187 /// # use github_rust::GitHubService;
188 /// # async fn example() -> github_rust::Result<()> {
189 /// let service = GitHubService::new()?;
190 ///
191 /// // Find Rust repos created in last 30 days with 50+ stars
192 /// let repos = service.search_repositories(
193 /// 30, // days back
194 /// 100, // limit
195 /// Some("rust"), // language
196 /// 50, // min stars
197 /// ).await?;
198 ///
199 /// for repo in repos {
200 /// println!("{}: {} stars", repo.name_with_owner, repo.stargazer_count);
201 /// }
202 /// # Ok(())
203 /// # }
204 /// ```
205 pub async fn search_repositories(
206 &self,
207 days_back: u32,
208 limit: usize,
209 language: Option<&str>,
210 min_stars: u32,
211 ) -> Result<Vec<search::SearchRepository>> {
212 search::search_repositories(&self.client, days_back, limit, language, min_stars).await
213 }
214
215 /// Checks the current GitHub API rate limit status.
216 ///
217 /// Useful for monitoring API usage and implementing backoff strategies.
218 ///
219 /// # Returns
220 ///
221 /// Rate limit information including limit, remaining requests, and reset time.
222 ///
223 /// # Example
224 ///
225 /// ```no_run
226 /// # use github_rust::GitHubService;
227 /// # async fn example() -> github_rust::Result<()> {
228 /// let service = GitHubService::new()?;
229 /// let limits = service.check_rate_limit().await?;
230 ///
231 /// println!("Remaining: {}/{}", limits.remaining, limits.limit);
232 /// println!("Resets at: {:?}", limits.reset_datetime());
233 ///
234 /// if limits.is_exceeded() {
235 /// println!("Rate limited! Wait {:?}", limits.time_until_reset());
236 /// }
237 /// # Ok(())
238 /// # }
239 /// ```
240 pub async fn check_rate_limit(&self) -> Result<crate::RateLimit> {
241 self.client.check_rate_limit().await
242 }
243
244 /// Returns separate REST core, search and GraphQL quotas when available.
245 pub async fn check_rate_limits(&self) -> Result<crate::RateLimits> {
246 self.client.check_rate_limits().await
247 }
248
249 /// Returns whether a GitHub token is configured.
250 ///
251 /// This does not verify the token, its permissions or its quotas.
252 ///
253 /// # Example
254 ///
255 /// ```no_run
256 /// # use github_rust::GitHubService;
257 /// let service = GitHubService::new()?;
258 ///
259 /// if service.has_token() {
260 /// println!("Token configured");
261 /// } else {
262 /// println!("Anonymous access");
263 /// }
264 /// # Ok::<(), github_rust::GitHubError>(())
265 /// ```
266 #[must_use]
267 pub fn has_token(&self) -> bool {
268 self.client.has_token()
269 }
270
271 /// Gets all repositories starred by the authenticated user.
272 ///
273 /// Requires an authorized token, configured through the builder or `new()`.
274 ///
275 /// # Returns
276 ///
277 /// List of repository full names in "owner/repo" format.
278 /// Returns a pagination error if more than 100 pages must be fetched.
279 ///
280 /// # Errors
281 ///
282 /// * [`GitHubError::AuthenticationError`] - No token or invalid token
283 /// * [`GitHubError::RateLimitError`] - API rate limit exceeded
284 ///
285 /// # Example
286 ///
287 /// ```no_run
288 /// # use github_rust::GitHubService;
289 /// # async fn example() -> github_rust::Result<()> {
290 /// let service = GitHubService::new()?;
291 /// let starred = service.get_user_starred_repositories().await?;
292 ///
293 /// println!("You have starred {} repositories", starred.len());
294 /// for repo in starred.iter().take(5) {
295 /// println!(" - {}", repo);
296 /// }
297 /// # Ok(())
298 /// # }
299 /// ```
300 pub async fn get_user_starred_repositories(&self) -> Result<Vec<String>> {
301 rest::get_user_starred_repositories(&self.client).await
302 }
303
304 /// Gets the profile of the authenticated user.
305 ///
306 /// Requires an authorized token, configured through the builder or `new()`.
307 ///
308 /// # Errors
309 ///
310 /// * [`GitHubError::AuthenticationError`] - No token or invalid token
311 ///
312 /// # Example
313 ///
314 /// ```no_run
315 /// # use github_rust::GitHubService;
316 /// # async fn example() -> github_rust::Result<()> {
317 /// let service = GitHubService::new()?;
318 /// let profile = service.get_user_profile().await?;
319 ///
320 /// println!("Logged in as: {}", profile.login);
321 /// if let Some(name) = profile.name {
322 /// println!("Name: {}", name);
323 /// }
324 /// # Ok(())
325 /// # }
326 /// ```
327 pub async fn get_user_profile(&self) -> Result<rest::UserProfile> {
328 rest::get_user_profile(&self.client).await
329 }
330
331 /// Gets users who starred a repository with timestamps.
332 ///
333 /// Returns stargazers with the date they starred the repository.
334 /// Supports pagination. GitHub restricts listing access to repository admins
335 /// and collaborators; empty results may also reflect access restrictions.
336 ///
337 /// # Arguments
338 ///
339 /// * `owner` - Repository owner
340 /// * `name` - Repository name
341 /// * `per_page` - Results per page (default 30); values above 100 are capped.
342 /// * `page` - Page number (default 1). Both arguments must be greater than zero.
343 ///
344 /// # Errors
345 ///
346 /// * [`GitHubError::NotFoundError`] - Repository not found
347 /// * [`GitHubError::RateLimitError`] - API rate limit exceeded
348 ///
349 /// # Example
350 ///
351 /// ```no_run
352 /// # use github_rust::GitHubService;
353 /// # async fn example() -> github_rust::Result<()> {
354 /// let service = GitHubService::new()?;
355 ///
356 /// // Get first 100 stargazers
357 /// let stargazers = service.get_repository_stargazers(
358 /// "rust-lang", "rust",
359 /// Some(100), // per_page
360 /// Some(1), // page
361 /// ).await?;
362 ///
363 /// for sg in stargazers {
364 /// println!("{} starred at {}", sg.user.login, sg.starred_at);
365 /// }
366 /// # Ok(())
367 /// # }
368 /// ```
369 pub async fn get_repository_stargazers(
370 &self,
371 owner: &str,
372 name: &str,
373 per_page: Option<u32>,
374 page: Option<u32>,
375 ) -> Result<Vec<crate::github::types::StargazerWithDate>> {
376 rest::get_repository_stargazers(&self.client, owner, name, per_page, page).await
377 }
378}
379
380impl GitHubService {
381 /// Configure limits for account, owned-repository and open-work-item collections.
382 pub fn with_fetch_options(mut self, options: super::FetchOptions) -> Result<Self> {
383 self.fetch_options = options.validate()?;
384 Ok(self)
385 }
386
387 /// Fetch the authenticated account and all organizations visible to its token.
388 pub async fn get_viewer(&self) -> Result<super::Viewer> {
389 super::accounts::viewer(&self.client, self.fetch_options).await
390 }
391
392 /// Stream validated, owned repository pages without buffering the inventory.
393 ///
394 /// The stream owns its client and login and is `Send + 'static`. Requests start
395 /// when polled; dropping the stream cancels traversal. An error ends the stream.
396 /// Pages are provisional until the stream ends successfully, and are not sorted.
397 /// Requires a token. Validation and authentication errors are returned as stream items.
398 ///
399 /// ```no_run
400 /// use futures_util::TryStreamExt;
401 /// use std::pin::pin;
402 ///
403 /// # async fn example(service: &github_rust::GitHubService) -> github_rust::Result<()> {
404 /// let mut pages = pin!(service.get_owned_repository_pages("rust-lang"));
405 /// while let Some(page) = pages.try_next().await? {
406 /// for repository in page.repositories {
407 /// println!("{}", repository.name_with_owner);
408 /// }
409 /// }
410 /// # Ok(())
411 /// # }
412 /// ```
413 pub fn get_owned_repository_pages(
414 &self,
415 login: &str,
416 ) -> impl futures_util::Stream<Item = Result<super::RepositoryPage>> + Send + 'static + use<>
417 {
418 super::accounts::repository_pages(self.client.clone(), login.to_owned(), self.fetch_options)
419 }
420
421 /// List repositories owned by a user or organization, including visible private,
422 /// forked and archived repositories. Requires a token. Results are sorted by full name.
423 pub async fn get_owned_repositories(&self, login: &str) -> Result<super::OwnedRepositories> {
424 super::accounts::repositories(
425 &self.client,
426 login,
427 self.fetch_options,
428 None::<super::pagination::NoProgress<_>>,
429 )
430 .await
431 }
432
433 /// List owned repositories, lending each validated page to an asynchronous callback.
434 /// Use `async |page| { ...; Ok(()) }` to borrow the page across await points.
435 /// Pages are provisional until this method succeeds. A callback error or dropping
436 /// the returned future cancels traversal; no background tasks are spawned.
437 /// GitHub does not provide a transactional snapshot across pages.
438 ///
439 /// For a `Send` stream of owned pages, use [`Self::get_owned_repository_pages`].
440 pub async fn get_owned_repositories_with_progress<F>(
441 &self,
442 login: &str,
443 progress: F,
444 ) -> Result<super::OwnedRepositories>
445 where
446 F: AsyncFnMut(&super::RepositoryPage) -> Result<()>,
447 {
448 super::accounts::repositories(&self.client, login, self.fetch_options, Some(progress)).await
449 }
450}
451
452impl GitHubService {
453 /// Stream validated, owned issue pages across explicit repository scopes.
454 ///
455 /// Scopes are validated before any request. Empty scopes need no token.
456 /// Pages arrive in completion order with bounded repository concurrency;
457 /// requests advance only while the stream is polled. An error ends traversal.
458 /// The stream is `Send + 'static`; dropping it cancels pending requests.
459 /// Pages remain provisional until all scopes finish successfully.
460 /// See [`Self::get_owned_repository_pages`] for a page-processing example.
461 pub fn get_open_issue_pages(
462 &self,
463 repositories: &[super::RepositoryCoordinates],
464 ) -> impl futures_util::Stream<Item = Result<super::WorkItemPage<super::Issue>>>
465 + Send
466 + 'static
467 + use<> {
468 super::work_items::pages(
469 self.client.clone(),
470 repositories.to_vec(),
471 self.fetch_options,
472 )
473 }
474
475 /// Fetch every open issue in one repository, sorted by update time descending.
476 /// Requires a token.
477 pub async fn get_open_issues(&self, owner: &str, name: &str) -> Result<Vec<super::Issue>> {
478 self.get_open_issues_for_repositories(&[super::RepositoryCoordinates::new(owner, name)?])
479 .await
480 }
481 /// Fetch open work items in explicit repository scopes without rediscovering ownership.
482 /// Archived repositories are included if supplied; applications choose their scopes.
483 pub async fn get_open_issues_for_repositories(
484 &self,
485 repositories: &[super::RepositoryCoordinates],
486 ) -> Result<Vec<super::Issue>> {
487 super::work_items::collect(
488 &self.client,
489 repositories,
490 self.fetch_options,
491 None::<super::pagination::NoProgress<_>>,
492 )
493 .await
494 }
495 /// Traverse repository scopes with bounded concurrency and lend each page to an async callback.
496 /// Empty scopes return immediately without authentication or a callback.
497 /// Use `async |page| { ...; Ok(()) }` to borrow the page across await points.
498 /// Pages are provisional until the whole call succeeds. Callback errors and dropping
499 /// the future cancel traversal. No tasks are spawned. Labels and assignees must fit
500 /// their embedded 100-node pages, otherwise this returns a pagination error.
501 /// Totals, cursors and repository identity are checked; GitHub offers no snapshot isolation.
502 /// For a `Send` stream of owned pages, use [`Self::get_open_issue_pages`].
503 pub async fn get_open_issues_with_progress<F>(
504 &self,
505 repositories: &[super::RepositoryCoordinates],
506 progress: F,
507 ) -> Result<Vec<super::Issue>>
508 where
509 F: AsyncFnMut(&super::WorkItemPage<super::Issue>) -> Result<()>,
510 {
511 super::work_items::collect(
512 &self.client,
513 repositories,
514 self.fetch_options,
515 Some(progress),
516 )
517 .await
518 }
519}
520
521impl GitHubService {
522 /// Stream validated, owned pull-request pages across explicit repository scopes.
523 ///
524 /// Has the same ordering, validation and cancellation guarantees as
525 /// [`Self::get_open_issue_pages`]. The stream is `Send + 'static` and does not
526 /// borrow the service or the repository scopes.
527 pub fn get_open_pull_request_pages(
528 &self,
529 repositories: &[super::RepositoryCoordinates],
530 ) -> impl futures_util::Stream<Item = Result<super::WorkItemPage<super::PullRequest>>>
531 + Send
532 + 'static
533 + use<> {
534 super::work_items::pages(
535 self.client.clone(),
536 repositories.to_vec(),
537 self.fetch_options,
538 )
539 }
540
541 /// Fetch every open pull request in one repository, sorted by update time descending.
542 /// Requires a token.
543 pub async fn get_open_pull_requests(
544 &self,
545 owner: &str,
546 name: &str,
547 ) -> Result<Vec<super::PullRequest>> {
548 self.get_open_pull_requests_for_repositories(&[super::RepositoryCoordinates::new(
549 owner, name,
550 )?])
551 .await
552 }
553 /// Fetch open work items in explicit repository scopes without rediscovering ownership.
554 /// Archived repositories are included if supplied; applications choose their scopes.
555 pub async fn get_open_pull_requests_for_repositories(
556 &self,
557 repositories: &[super::RepositoryCoordinates],
558 ) -> Result<Vec<super::PullRequest>> {
559 super::work_items::collect(
560 &self.client,
561 repositories,
562 self.fetch_options,
563 None::<super::pagination::NoProgress<_>>,
564 )
565 .await
566 }
567 /// Collect open pull requests while lending each page to an async callback.
568 /// Uses the same validation, concurrency and cancellation rules as
569 /// [`Self::get_open_issues_with_progress`].
570 /// For a `Send` stream of owned pages, use [`Self::get_open_pull_request_pages`].
571 pub async fn get_open_pull_requests_with_progress<F>(
572 &self,
573 repositories: &[super::RepositoryCoordinates],
574 progress: F,
575 ) -> Result<Vec<super::PullRequest>>
576 where
577 F: AsyncFnMut(&super::WorkItemPage<super::PullRequest>) -> Result<()>,
578 {
579 super::work_items::collect(
580 &self.client,
581 repositories,
582 self.fetch_options,
583 Some(progress),
584 )
585 .await
586 }
587}