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 ///
408 /// # Send adapters
409 ///
410 /// Generic adapters using async closures can hit Rust's `Send` inference
411 /// limitation when borrowing the callback. Capture it by value with `async move`
412 /// and give the callback owned state (for example, `Arc` for shared state).
413 /// This example forwards owned pages, so it clones at that boundary:
414 ///
415 /// ```no_run
416 /// use github_rust::{GitHubService, RepositoryPage, Result};
417 /// use std::future::Future;
418 ///
419 /// async fn collect<F, Fut>(service: &GitHubService, mut progress: F) -> Result<()>
420 /// where
421 /// F: FnMut(RepositoryPage) -> Fut + Send,
422 /// Fut: Future<Output = Result<()>> + Send,
423 /// {
424 /// service.get_owned_repositories_with_progress(
425 /// "owner",
426 /// async move |page| { progress(page.clone()).await },
427 /// ).await?;
428 /// Ok(())
429 /// }
430 /// # fn assert_send(_: impl Future<Output = Result<()>> + Send) {}
431 /// # fn check(service: &GitHubService) {
432 /// # assert_send(collect(service, |_| async { Ok(()) }));
433 /// # }
434 /// ```
435 pub async fn get_owned_repositories_with_progress<F>(
436 &self,
437 login: &str,
438 progress: F,
439 ) -> Result<super::OwnedRepositories>
440 where
441 F: AsyncFnMut(&super::RepositoryPage) -> Result<()>,
442 {
443 super::accounts::repositories(&self.client, login, self.fetch_options, Some(progress)).await
444 }
445}
446
447impl GitHubService {
448 /// Fetch every open work item in one repository, sorted by update time descending.
449 pub async fn get_open_issues(&self, owner: &str, name: &str) -> Result<Vec<super::Issue>> {
450 self.get_open_issues_for_repositories(&[super::RepositoryCoordinates::new(owner, name)?])
451 .await
452 }
453 /// Fetch open work items in explicit repository scopes without rediscovering ownership.
454 /// Archived repositories are included if supplied; applications choose their scopes.
455 pub async fn get_open_issues_for_repositories(
456 &self,
457 repositories: &[super::RepositoryCoordinates],
458 ) -> Result<Vec<super::Issue>> {
459 super::work_items::collect(
460 &self.client,
461 repositories,
462 self.fetch_options,
463 None::<super::pagination::NoProgress<_>>,
464 )
465 .await
466 }
467 /// Traverse repository scopes with bounded concurrency and lend each page to an async callback.
468 /// Empty scopes return immediately without authentication or a callback.
469 /// Use `async |page| { ...; Ok(()) }` to borrow the page across await points.
470 /// Pages are provisional until the whole call succeeds. Callback errors and dropping
471 /// the future cancel traversal. No tasks are spawned. Labels and assignees must fit
472 /// their embedded 100-node pages, otherwise this returns a pagination error.
473 /// Totals, cursors and repository identity are checked; GitHub offers no snapshot isolation.
474 /// For generic adapters requiring `Send`, see the `async move` adapter example on
475 /// [`Self::get_owned_repositories_with_progress`]. Here callbacks receive
476 /// `&WorkItemPage<Issue>`.
477 pub async fn get_open_issues_with_progress<F>(
478 &self,
479 repositories: &[super::RepositoryCoordinates],
480 progress: F,
481 ) -> Result<Vec<super::Issue>>
482 where
483 F: AsyncFnMut(&super::WorkItemPage<super::Issue>) -> Result<()>,
484 {
485 super::work_items::collect(
486 &self.client,
487 repositories,
488 self.fetch_options,
489 Some(progress),
490 )
491 .await
492 }
493}
494
495impl GitHubService {
496 /// Fetch every open work item in one repository, sorted by update time descending.
497 pub async fn get_open_pull_requests(
498 &self,
499 owner: &str,
500 name: &str,
501 ) -> Result<Vec<super::PullRequest>> {
502 self.get_open_pull_requests_for_repositories(&[super::RepositoryCoordinates::new(
503 owner, name,
504 )?])
505 .await
506 }
507 /// Fetch open work items in explicit repository scopes without rediscovering ownership.
508 /// Archived repositories are included if supplied; applications choose their scopes.
509 pub async fn get_open_pull_requests_for_repositories(
510 &self,
511 repositories: &[super::RepositoryCoordinates],
512 ) -> Result<Vec<super::PullRequest>> {
513 super::work_items::collect(
514 &self.client,
515 repositories,
516 self.fetch_options,
517 None::<super::pagination::NoProgress<_>>,
518 )
519 .await
520 }
521 /// Traverse repository scopes with bounded concurrency and lend each page to an async callback.
522 /// Empty scopes return immediately without authentication or a callback.
523 /// Use `async |page| { ...; Ok(()) }` to borrow the page across await points.
524 /// Pages are provisional until the whole call succeeds. Callback errors and dropping
525 /// the future cancel traversal. No tasks are spawned. Labels and assignees must fit
526 /// their embedded 100-node pages, otherwise this returns a pagination error.
527 /// Totals, cursors and repository identity are checked; GitHub offers no snapshot isolation.
528 /// For generic adapters requiring `Send`, see the `async move` adapter example on
529 /// [`Self::get_owned_repositories_with_progress`]. Here callbacks receive
530 /// `&WorkItemPage<PullRequest>`.
531 pub async fn get_open_pull_requests_with_progress<F>(
532 &self,
533 repositories: &[super::RepositoryCoordinates],
534 progress: F,
535 ) -> Result<Vec<super::PullRequest>>
536 where
537 F: AsyncFnMut(&super::WorkItemPage<super::PullRequest>) -> Result<()>,
538 {
539 super::work_items::collect(
540 &self.client,
541 repositories,
542 self.fetch_options,
543 Some(progress),
544 )
545 .await
546 }
547}
548
549#[cfg(test)]
550mod tests {
551 use super::*;
552
553 #[test]
554 fn test_github_service_creation() {
555 let service = GitHubService::new();
556 assert!(service.is_ok());
557 }
558
559 #[test]
560 fn test_github_service_has_token_detection() {
561 let service = GitHubService::new().unwrap();
562 // Token detection should work without panicking
563 let _has_token = service.has_token();
564 }
565}