Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Fix github api pagination #247

Merged
merged 1 commit into from
Feb 8, 2025
Merged

Fix github api pagination #247

merged 1 commit into from
Feb 8, 2025

Conversation

dhirenmathur
Copy link
Contributor

@dhirenmathur dhirenmathur commented Feb 8, 2025

Summary by CodeRabbit

  • New Features
    • GitHub integration now leverages asynchronous processing, resulting in faster and more efficient data retrieval.
    • Improved handling of multi-page results ensures all repositories and installations are fetched reliably.
  • Bug Fixes
    • Addressed issues with incomplete data retrieval and enhanced error reporting for a more stable user experience.

Copy link
Contributor

coderabbitai bot commented Feb 8, 2025

Walkthrough

The pull request refactors the GithubService class’s get_repos_for_user method by converting it from synchronous to asynchronous. The method now uses aiohttp to fetch GitHub installations and repositories concurrently, implementing pagination for both data sets. It gathers installations in batches and iterates through repository pages using the "next" link in response headers. Enhanced error handling logs issues and raises appropriate HTTP exceptions for failed requests.

Changes

File Change Summary
app/.../github_service.py Converted get_repos_for_user to asynchronous using aiohttp; implemented pagination for installations (batch fetching) and repositories (using "next" link); improved error logging and HTTP exception raising.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant G as GithubService
    participant API as GitHub API

    C->>G: get_repos_for_user(user_id)
    G->>API: GET /installations?page=1
    API-->>G: Returns headers (total pages) and data
    G->>API: [Async] GET /installations?page=2...N
    API-->>G: Aggregated installations data
    loop For each installation
        G->>API: GET /repos (with pagination)
        API-->>G: Repositories data or next link info
    end
    G-->>C: Aggregated installations & repositories
Loading

Poem

Hopping through code with a joyful beat,
I turned sync calls into an async treat.
Carrots of pagination lined up in a row,
Fetching installations and repos in one go.
A rabbit’s leap in code so fleet — oh what a show!
🐇💻

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

sonarqubecloud bot commented Feb 8, 2025

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
app/modules/code_provider/github/github_service.py (1)

192-254: Streamline the pagination loop for better PEP 8 compliance and readability.
While your pagination logic is well-structured, some list comprehensions and logging statements are triggering the pipeline’s PEP 8 style warnings. Consider splitting the line comprehension for page_urls, and ensure that logging statements meet the pipeline’s formatting guidelines.

Apply something similar to the following diff to address the pipeline warnings:

- page_urls = [f"{base_url}?page={page}" for page in range(2, last_page + 1)]
+ page_urls = [
+     f"{base_url}?page={page}"
+     for page in range(2, last_page + 1)
+ ]

- logger.info(f"Fetched {len(installations)} installations from {url}")
+ logger.info(
+     f"Fetched {len(installations)} installations from {url}"
+ )
🧰 Tools
🪛 GitHub Actions: Pre-commit

[warning] 203-205: Code does not adhere to PEP 8 standards. The logging statement should be formatted using f-strings.


[warning] 228-230: Code does not adhere to PEP 8 standards. The list comprehension should be split into multiple lines for better readability.


[warning] 238-240: Code does not adhere to PEP 8 standards. The logging statement should be formatted using f-strings.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0360f58 and 6c22fcd.

📒 Files selected for processing (1)
  • app/modules/code_provider/github/github_service.py (3 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
app/modules/code_provider/github/github_service.py

273-273: Local variable github is assigned to but never used

Remove assignment to unused variable github

(F841)

🪛 GitHub Actions: Pre-commit
app/modules/code_provider/github/github_service.py

[warning] 203-205: Code does not adhere to PEP 8 standards. The logging statement should be formatted using f-strings.


[warning] 228-230: Code does not adhere to PEP 8 standards. The list comprehension should be split into multiple lines for better readability.


[warning] 238-240: Code does not adhere to PEP 8 standards. The logging statement should be formatted using f-strings.


[warning] 254-256: Code does not adhere to PEP 8 standards. The logging statement should be formatted using f-strings.

🔇 Additional comments (1)
app/modules/code_provider/github/github_service.py (1)

8-8: Import looks good.
No issues with introducing aiohttp for asynchronous operations.

@@ -217,20 +266,35 @@ async def get_repos_for_user(self, user_id: str):
elif account_type == "Organization" and account_login in org_logins:
user_installations.append(installation)


repos = []
for installation in user_installations:
app_auth = auth.get_installation_auth(installation["id"])
github = Github(auth=app_auth)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove unused variable.
'github' is assigned to but never used, which might confuse readers and violate lint checks.

- github = Github(auth=app_auth)
  repos_url = installation["repositories_url"]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
github = Github(auth=app_auth)
repos_url = installation["repositories_url"]
🧰 Tools
🪛 Ruff (0.8.2)

273-273: Local variable github is assigned to but never used

Remove assignment to unused variable github

(F841)

Comment on lines +275 to +294

# Handle pagination for repositories as well
next_repos_url = repos_url
while next_repos_url:
repos_response = requests.get(
next_repos_url,
headers={"Authorization": f"Bearer {app_auth.token}"}
)

if repos_response.status_code == 200:
repos.extend(repos_response.json().get("repositories", []))

# Check for next page in Link header
next_repos_url = None
if "links" in repos_response.__dict__:
for link in repos_response.links.values():
if link.get("rel") == "next":
next_repos_url = link.get("url")
break
else:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider using aiohttp for repository pagination to maintain consistency.
You’re performing synchronous GET requests inside an async method, which can block the event loop. Switch to the existing aiohttp session (or open another context) for fetching paginated repositories to leverage concurrency benefits.

Example approach:

- repos_response = requests.get(
-     next_repos_url,
-     headers={"Authorization": f"Bearer {app_auth.token}"}
- )
+ async with session.get(
+     next_repos_url,
+     headers={"Authorization": f"Bearer {app_auth.token}"}
+ ) as response:
+     if response.status == 200:
+         data = await response.json()
+         repos.extend(data.get("repositories", []))
+         # Continue processing

Committable suggestion skipped: line range outside the PR's diff.

@dhirenmathur dhirenmathur merged commit a07007c into main Feb 8, 2025
3 of 4 checks passed
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant