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 /// Stream validated, owned repository pages without buffering the inventory.
391 ///
392 /// The stream owns its client and login and is `Send + 'static`. Requests start
393 /// when polled; dropping the stream cancels traversal. An error ends the stream.
394 /// Pages are provisional until the stream ends successfully, and are not sorted.
395 /// Validation and authentication errors are returned as stream items.
396 ///
397 /// ```no_run
398 /// use futures_util::TryStreamExt;
399 /// use std::pin::pin;
400 ///
401 /// # async fn example(service: &github_rust::GitHubService) -> github_rust::Result<()> {
402 /// let mut pages = pin!(service.get_owned_repository_pages("rust-lang"));
403 /// while let Some(page) = pages.try_next().await? {
404 /// for repository in page.repositories {
405 /// println!("{}", repository.name_with_owner);
406 /// }
407 /// }
408 /// # Ok(())
409 /// # }
410 /// ```
411 pub fn get_owned_repository_pages(
412 &self,
413 login: &str,
414 ) -> impl futures_util::Stream<Item = Result<super::RepositoryPage>> + Send + 'static + use<>
415 {
416 super::accounts::repository_pages(self.client.clone(), login.to_owned(), self.fetch_options)
417 }
418
419 /// List repositories owned by a user or organization, including visible private,
420 /// forked and archived repositories. Results are sorted by full name.
421 pub async fn get_owned_repositories(&self, login: &str) -> Result<super::OwnedRepositories> {
422 super::accounts::repositories(
423 &self.client,
424 login,
425 self.fetch_options,
426 None::<super::pagination::NoProgress<_>>,
427 )
428 .await
429 }
430
431 /// List owned repositories, lending each validated page to an asynchronous callback.
432 /// Use `async |page| { ...; Ok(()) }` to borrow the page across await points.
433 /// Pages are provisional until this method succeeds. A callback error or dropping
434 /// the returned future cancels traversal; no background tasks are spawned.
435 /// GitHub does not provide a transactional snapshot across pages.
436 ///
437 /// For a `Send` stream of owned pages, use [`Self::get_owned_repository_pages`].
438 pub async fn get_owned_repositories_with_progress<F>(
439 &self,
440 login: &str,
441 progress: F,
442 ) -> Result<super::OwnedRepositories>
443 where
444 F: AsyncFnMut(&super::RepositoryPage) -> Result<()>,
445 {
446 super::accounts::repositories(&self.client, login, self.fetch_options, Some(progress)).await
447 }
448}
449
450impl GitHubService {
451 /// Stream validated, owned issue pages across explicit repository scopes.
452 ///
453 /// Scopes are validated before any request. Empty scopes need no token.
454 /// Pages arrive in completion order with bounded repository concurrency;
455 /// requests advance only while the stream is polled. An error ends traversal.
456 /// The stream is `Send + 'static`; dropping it cancels pending requests.
457 /// Pages remain provisional until all scopes finish successfully.
458 /// See [`Self::get_owned_repository_pages`] for a page-processing example.
459 pub fn get_open_issue_pages(
460 &self,
461 repositories: &[super::RepositoryCoordinates],
462 ) -> impl futures_util::Stream<Item = Result<super::WorkItemPage<super::Issue>>>
463 + Send
464 + 'static
465 + use<> {
466 super::work_items::pages(
467 self.client.clone(),
468 repositories.to_vec(),
469 self.fetch_options,
470 )
471 }
472
473 /// Fetch every open work item in one repository, sorted by update time descending.
474 pub async fn get_open_issues(&self, owner: &str, name: &str) -> Result<Vec<super::Issue>> {
475 self.get_open_issues_for_repositories(&[super::RepositoryCoordinates::new(owner, name)?])
476 .await
477 }
478 /// Fetch open work items in explicit repository scopes without rediscovering ownership.
479 /// Archived repositories are included if supplied; applications choose their scopes.
480 pub async fn get_open_issues_for_repositories(
481 &self,
482 repositories: &[super::RepositoryCoordinates],
483 ) -> Result<Vec<super::Issue>> {
484 super::work_items::collect(
485 &self.client,
486 repositories,
487 self.fetch_options,
488 None::<super::pagination::NoProgress<_>>,
489 )
490 .await
491 }
492 /// Traverse repository scopes with bounded concurrency and lend each page to an async callback.
493 /// Empty scopes return immediately without authentication or a callback.
494 /// Use `async |page| { ...; Ok(()) }` to borrow the page across await points.
495 /// Pages are provisional until the whole call succeeds. Callback errors and dropping
496 /// the future cancel traversal. No tasks are spawned. Labels and assignees must fit
497 /// their embedded 100-node pages, otherwise this returns a pagination error.
498 /// Totals, cursors and repository identity are checked; GitHub offers no snapshot isolation.
499 /// For a `Send` stream of owned pages, use [`Self::get_open_issue_pages`].
500 pub async fn get_open_issues_with_progress<F>(
501 &self,
502 repositories: &[super::RepositoryCoordinates],
503 progress: F,
504 ) -> Result<Vec<super::Issue>>
505 where
506 F: AsyncFnMut(&super::WorkItemPage<super::Issue>) -> Result<()>,
507 {
508 super::work_items::collect(
509 &self.client,
510 repositories,
511 self.fetch_options,
512 Some(progress),
513 )
514 .await
515 }
516}
517
518impl GitHubService {
519 /// Stream validated, owned pull-request pages across explicit repository scopes.
520 ///
521 /// Has the same ordering, validation and cancellation guarantees as
522 /// [`Self::get_open_issue_pages`]. The stream is `Send + 'static` and does not
523 /// borrow the service or the repository scopes.
524 pub fn get_open_pull_request_pages(
525 &self,
526 repositories: &[super::RepositoryCoordinates],
527 ) -> impl futures_util::Stream<Item = Result<super::WorkItemPage<super::PullRequest>>>
528 + Send
529 + 'static
530 + use<> {
531 super::work_items::pages(
532 self.client.clone(),
533 repositories.to_vec(),
534 self.fetch_options,
535 )
536 }
537
538 /// Fetch every open work item in one repository, sorted by update time descending.
539 pub async fn get_open_pull_requests(
540 &self,
541 owner: &str,
542 name: &str,
543 ) -> Result<Vec<super::PullRequest>> {
544 self.get_open_pull_requests_for_repositories(&[super::RepositoryCoordinates::new(
545 owner, name,
546 )?])
547 .await
548 }
549 /// Fetch open work items in explicit repository scopes without rediscovering ownership.
550 /// Archived repositories are included if supplied; applications choose their scopes.
551 pub async fn get_open_pull_requests_for_repositories(
552 &self,
553 repositories: &[super::RepositoryCoordinates],
554 ) -> Result<Vec<super::PullRequest>> {
555 super::work_items::collect(
556 &self.client,
557 repositories,
558 self.fetch_options,
559 None::<super::pagination::NoProgress<_>>,
560 )
561 .await
562 }
563 /// Traverse repository scopes with bounded concurrency and lend each page to an async callback.
564 /// Empty scopes return immediately without authentication or a callback.
565 /// Use `async |page| { ...; Ok(()) }` to borrow the page across await points.
566 /// Pages are provisional until the whole call succeeds. Callback errors and dropping
567 /// the future cancel traversal. No tasks are spawned. Labels and assignees must fit
568 /// their embedded 100-node pages, otherwise this returns a pagination error.
569 /// Totals, cursors and repository identity are checked; GitHub offers no snapshot isolation.
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}
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592
593 #[test]
594 fn test_github_service_creation() {
595 let service = GitHubService::new();
596 assert!(service.is_ok());
597 }
598
599 #[test]
600 fn test_github_service_has_token_detection() {
601 let service = GitHubService::new().unwrap();
602 // Token detection should work without panicking
603 let _has_token = service.has_token();
604 }
605}