Skip to content

Use repo api token for webhooks and set repositories when available#686

Merged
myakove merged 2 commits intomainfrom
set-repositories-use-repo-api-take2
Mar 7, 2025
Merged

Use repo api token for webhooks and set repositories when available#686
myakove merged 2 commits intomainfrom
set-repositories-use-repo-api-take2

Conversation

@myakove
Copy link
Copy Markdown
Collaborator

@myakove myakove commented Mar 7, 2025

Summary by CodeRabbit

  • Refactor
    • Enhanced GitHub integration to dynamically select optimal API credentials.
    • Improved logging and error handling for repository operations with additional user context.
    • Enabled concurrent processing for webhook events, increasing overall reliability and traceability.
    • Updated function signatures for better clarity and consistency in parameters.

@myakove-bot
Copy link
Copy Markdown
Collaborator

Report bugs in Issues

The following are automatically added:

  • Add reviewers from OWNER file (in the root of the repository) under reviewers section.
  • Set PR size label.
  • New issue is created for the PR. (Closed when PR is merged/closed)
  • Run pre-commit if .pre-commit-config.yaml exists in the repo.

Available user actions:

  • To mark PR as WIP comment /wip to the PR, To remove it from the PR comment /wip cancel to the PR.
  • To block merging of PR comment /hold, To un-block merging of PR comment /hold cancel.
  • To mark PR as verified comment /verified to the PR, to un-verify comment /verified cancel to the PR.
    verified label removed on each new commit push.
  • To cherry pick a merged PR comment /cherry-pick <target branch to cherry-pick to> in the PR.
    • Multiple target branches can be cherry-picked, separated by spaces. (/cherry-pick branch1 branch2)
    • Cherry-pick will be started when PR is merged
  • To build and push container image command /build-and-push-container in the PR (tag will be the PR number).
    • You can add extra args to the Podman build command
      • Example: /build-and-push-container --build-arg OPENSHIFT_PYTHON_WRAPPER_COMMIT=<commit_hash>
  • To add a label by comment use /<label name>, to remove, use /<label name> cancel
  • To assign reviewers based on OWNERS file use /assign-reviewers
  • To check if PR can be merged use /check-can-merge
  • to assign reviewer to PR use /assign-reviewer @<reviewer>
Supported /retest check runs
  • /retest tox: Retest tox
  • /retest build-container: Retest build-container
  • /retest python-module-install: Retest python-module-install
  • /retest pre-commit: Retest pre-commit
  • /retest all: Retest all
Supported labels
  • hold
  • verified
  • wip
  • lgtm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 7, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes update the GitHub webhook handling components. The ProcessGithubWehook class now initializes using a function that returns the GitHub API, token, and API user with improved error logging. Related utility functions and methods in repository settings, helper, and webhook modules have their signatures updated to accept API user information or an APIs dictionary. Type annotations have been revised and concurrency introduced for API retrieval, ensuring that log messages now include API user context for clearer traceability.

Changes

File Change Summary
webhook_server_container/libs/github_api.py Updated the __init__ and prepare_log_prefix methods in the ProcessGithubWehook class to retrieve GitHub API credentials using get_api_with_highest_rate_limit with enhanced error handling and logging.
webhook_server_container/utils/github_repository_settings.py Modified function signatures in multiple methods (e.g., set_branch_protection, set_repository_settings, set_repository_labels, etc.) to include api_user or an apis_dict parameter; added a new get_repository_api method.
webhook_server_container/utils/helpers.py Revised type annotations from Dict/Tuple to dict/tuple; updated the logic in get_value_from_dicts and modified get_api_with_highest_rate_limit to return an additional string (_api_user); adjusted types in get_future_results.
webhook_server_container/utils/webhook.py Changed the process_github_webhook signature to accept an apis_dict (removing the direct github_api parameter); implemented concurrent API retrieval in create_webhook and updated error logging to include API user context; added a new get_repository_api method.
webhook_server_container/tests/conftest.py Reordered import statements for clarity and modified the mock return value in the process_github_webhook fixture to include an additional parameter.

Possibly related PRs

  • Use repo api token for webhooks and set repositories when available #686: The changes in the main PR and the retrieved PR are related as both modify the __init__ method of the ProcessGithubWehook class in github_api.py, specifically in how the GitHub API and token are initialized and handled.
  • Add approved status check #608: The changes in the main PR are related to the modifications in the ProcessGithubWehook class, specifically in the __init__ method, which is also part of the same class that underwent significant changes in the retrieved PR, indicating a direct connection in their functionality.
  • Do not run regctl in container #600: The changes in the main PR are related to the modifications in the ProcessGithubWehook class within the webhook_server_container/libs/github_api.py file, specifically in the __init__ method, which is also present in the retrieved PR's changes to the same class.

Suggested labels

can-be-merged, approved-rnetser

Suggested reviewers

  • rnetser
  • dbasunag

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e75a5fe and e07990e.

📒 Files selected for processing (3)
  • webhook_server_container/libs/github_api.py (2 hunks)
  • webhook_server_container/tests/conftest.py (2 hunks)
  • webhook_server_container/utils/helpers.py (8 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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
Copy Markdown

@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 (5)
webhook_server_container/utils/helpers.py (2)

30-37: Slightly more idiomatic existence checks.
While your solution is correct, you can consider using if key in primary_dict: instead of if primary_dict.get(key): to more explicitly distinguish between "value is None" vs. "key doesn't exist."

-    if primary_dict.get(key):
-        return primary_dict[key]
-    elif secondary_dict.get(key):
-        return secondary_dict[key]
-    else:
-        return return_on_none
+    if key in primary_dict:
+        return primary_dict[key]
+    elif key in secondary_dict:
+        return secondary_dict[key]
+    return return_on_none

150-151: Typographical fix suggestion.
The function name has a minor misspelling: “tokes” instead of “tokens.”

-def get_apis_and_tokes_from_config(config: Config, repository_name: str = "") -> list[tuple[github.Github, str]]:
+def get_apis_and_tokens_from_config(config: Config, repository_name: str = "") -> list[tuple[github.Github, str]]:
webhook_server_container/utils/github_repository_settings.py (3)

414-428: Add error handling for API retrieval

The code retrieves APIs in parallel but doesn't handle potential exceptions that might occur during retrieval. This could lead to missing keys in the apis_dict.

 apis: list = []
 with ThreadPoolExecutor() as executor:
     for repo, data in config.data["repositories"].items():
         apis.append(
             executor.submit(
                 get_repository_api,
-                **{"repository": repo},
+                **{"repository": repo, "config": config},
             )
         )

 for result in as_completed(apis):
-    repository, github_api, api_user = result.result()
-    apis_dict[repository] = {"api": github_api, "user": api_user}
+    try:
+        repository, github_api, api_user = result.result()
+        if github_api:
+            apis_dict[repository] = {"api": github_api, "user": api_user}
+        else:
+            logger.error(f"Failed to get API for repository {repository}")
+    except Exception as e:
+        logger.error(f"Error retrieving API for repository: {e}")

235-254: Improve clarity between repository_name and full_repository_name

The function uses two different variables for repository names, which could lead to confusion:

  1. repository_name - passed as a parameter and used to look up in the apis_dict
  2. full_repository_name - retrieved from data["name"] and used in log messages

Consider clarifying the naming or adding comments to explain the difference between these variables.

 def set_repository(
     repository_name: str, data: Dict[str, Any], default_status_checks: List[str], apis_dict: dict[str, dict[str, Any]]
 ) -> Tuple[bool, str, Callable]:
     logger = get_logger_with_params(name="github-repository-settings")
 
+    # repository_name is the key in the config, full_repository_name includes the org/repo format
     full_repository_name: str = data["name"]
     logger.info(f"Processing repository {full_repository_name}")
     protected_branches: Dict[str, Any] = data.get("protected-branches", {})
     repo_branch_protection_rules: Dict[str, Any] = data["branch_protection"]
     github_api = apis_dict[repository_name].get("api")
     api_user = apis_dict[repository_name].get("user", "")

432-433: Consider handling failures in the main execution flows

The main execution flows set_repositories_settings and set_all_in_progress_check_runs_to_queued don't have any error handling or reporting. Consider adding try/except blocks and returning appropriate exit codes if critical operations fail.

-set_repositories_settings(config_=config, apis_dict=apis_dict)
-set_all_in_progress_check_runs_to_queued(config_=config, apis_dict=apis_dict)
+try:
+    set_repositories_settings(config_=config, apis_dict=apis_dict)
+    set_all_in_progress_check_runs_to_queued(config_=config, apis_dict=apis_dict)
+    logger.info("Repository settings update completed successfully")
+except Exception as e:
+    logger.error(f"Failed to update repository settings: {e}")
+    sys.exit(1)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 61bf2a8 and e75a5fe.

📒 Files selected for processing (4)
  • webhook_server_container/libs/github_api.py (2 hunks)
  • webhook_server_container/utils/github_repository_settings.py (11 hunks)
  • webhook_server_container/utils/helpers.py (8 hunks)
  • webhook_server_container/utils/webhook.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: pre-commit
  • GitHub Check: tox
  • GitHub Check: build-container
  • GitHub Check: python-module-install
🔇 Additional comments (37)
webhook_server_container/utils/helpers.py (14)

8-8: Use of built-in type hints is good.
Switching to Any from the typing module in a Python 3.9+ context is standard.


20-21: Consistent type annotations.
Using dict[Any, Any] and an Any return value is clear and matches your usage.

Also applies to: 23-23


40-40: New function signature with optional parameter.
The addition of repository_name is well-defined and properly typed.


43-43: Initialization of repo_data.
Defining a default dict[str, Any] keeps the code robust.


55-55: Refined type annotation for function arguments.
The shift from Dict[..., ...] to the built-in dict[...] is a fine stylistic choice.


78-78: Modern union operator for type hints.
int | None is clean and readable.


83-83: Explicit tuple return type.
This clarifies the function’s possible outputs.


167-168: Augmented return type for additional context.
Including the _api_user in the returned tuple enhances traceability.


181-182: Initialization of variables.
api and token set to None by default is fine.


184-184: Graceful handling of rate_limit.
Setting it to None avoids potential uninitialized references.


188-189: Improved debug clarity.
A general message for retrieving API and token is helpful.


190-194: Conditional logging.
Appending the repository name in the debug message can prevent confusion.


207-207: Return structure expansion.
Returning (api, token, _api_user) is consistent with the earlier changes.


236-239: Extended docstring note.
The updated docstring clarifies the expected tuple shape for future results.

webhook_server_container/libs/github_api.py (4)

116-118: Introduced retrieval of api_user.
Aligns with the refactor to include API user context in logs and operations.


120-122: Defensive check on self.github_api and self.token.
Ensures referencing valid objects before proceeding.


123-126: Early return if GitHub API/token retrieval fails.
This prevents downstream null references.


207-207: Potential double re-initialization of self.log_prefix.
Review if reassigning self.log_prefix here and at line 127 is intentional. Re-setting the same variable again might cause confusion unless needed.

Do you want me to generate a quick script to search for multiple self.log_prefix assignments or do you have it covered?

webhook_server_container/utils/webhook.py (18)

1-1: Use of ThreadPoolExecutor.
Import statements look fine; concurrency can improve performance when creating hooks.


4-4: New direct import of github.
No issues, improves readability for GitHub-specific calls.


18-20: Function signature update adding apis_dict.
Refactoring to centralize API user retrieval is logical.


21-23: Dynamic retrieval of API and user.
Provides more flexibility for multi-repository scenarios.


25-26: Guard clause for missing API.
Immediate return helps avoid deeper failures.


27-27: Return message clarifies cause.
Returning the repository name aids debugging.


28-30: Additional user context in error messages.
Improves traceability when repositories are missing.


38-42: More precise exception message.
Including the api_user can pinpoint token permission issues quickly.


46-50: Immediate return on existing webhook.
Properly short-circuits redundant setup.


52-54: Logging new webhook creation.
Including events and user info is helpful.


56-57: Clear success message.
Including [API user ...] fosters consistent logging.


59-61: New helper function to get repository & user.
Automatically calls get_api_with_highest_rate_limit for concurrency.


67-68: Dictionary to store APIs per repository.
apis_dict structure is readable.


69-78: Concurrent retrieval of repository APIs.
Fetching them in parallel is efficient for large sets of repos.


79-82: Parsing future results into apis_dict.
Threaded logic looks sound.


83-83: Detailed debug logging.
Helps confirm that all repositories have assigned API credentials.


87-87: Begin loop for processing each repo.
Parallel approach for hooking each repository is consistent with the design.


91-91: Reuse of process_github_webhook.
Coherent approach to pass arguments via **.

webhook_server_container/utils/github_repository_settings.py (1)

57-86:

Details

✅ Verification successful

Verify the parameter usage in branch protection

The api_user parameter is being used as individual bypass allowances for users, teams, and apps. However, these parameters expect lists. Make sure api_user is correctly interpreted here.


🏁 Script executed:

#!/bin/bash
# Check if api_user is used as a string or list in other places in the codebase
rg -A 3 -B 3 "bypass_pull_request_allowances" --glob "*.py"

# Look for documentation or usage examples of edit_protection method
rg "edit_protection\(" --glob "*.py" -A 5 -B 5

Length of output: 2209


Verification of Branch Protection Parameter Usage

After running the search commands, we confirmed that in our code the api_user parameter is consistently used as a string which is then wrapped in a list (i.e., [api_user]) for the bypass allowances. This aligns with the API’s expectation for these parameters to be lists. No changes are needed.

Comment on lines +404 to +407
def get_repository_api(repository: str) -> tuple[str, github.Github | None, str]:
github_api, _, api_user = get_api_with_highest_rate_limit(config=config, repository_name=repository)
return repository, github_api, api_user

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing parameter in get_repository_api function

The function references a global config variable that's not passed as a parameter. This could lead to runtime errors.

-def get_repository_api(repository: str) -> tuple[str, github.Github | None, str]:
-    github_api, _, api_user = get_api_with_highest_rate_limit(config=config, repository_name=repository)
+def get_repository_api(repository: str, config: Config) -> tuple[str, github.Github | None, str]:
+    github_api, _, api_user = get_api_with_highest_rate_limit(config=config, repository_name=repository)
     return repository, github_api, api_user
📝 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
def get_repository_api(repository: str) -> tuple[str, github.Github | None, str]:
github_api, _, api_user = get_api_with_highest_rate_limit(config=config, repository_name=repository)
return repository, github_api, api_user
def get_repository_api(repository: str, config: Config) -> tuple[str, github.Github | None, str]:
github_api, _, api_user = get_api_with_highest_rate_limit(config=config, repository_name=repository)
return repository, github_api, api_user

Comment on lines +326 to 338
for repo, data in config_.data["repositories"].items():
futures.append(
executor.submit(
set_repository_check_runs_to_queued,
**{
"config_": config_,
"data": data,
"github_api": github_api,
"github_api": apis_dict[repo]["api"],
"check_runs": check_runs,
"api_user": apis_dict[repo]["user"],
},
)
)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Validate repository exists in apis_dict before accessing it

The code accesses the repository key directly in apis_dict without checking if it exists. This could lead to KeyError exceptions.

 with ThreadPoolExecutor() as executor:
     for repo, data in config_.data["repositories"].items():
+        if repo not in apis_dict:
+            logger.error(f"Repository {repo} not found in APIs dictionary. Skipping.")
+            continue
+        if "api" not in apis_dict[repo] or "user" not in apis_dict[repo]:
+            logger.error(f"Missing API or user for repository {repo}. Skipping.")
+            continue
         futures.append(
             executor.submit(
                 set_repository_check_runs_to_queued,
                 **{
                     "config_": config_,
                     "data": data,
                     "github_api": apis_dict[repo]["api"],
                     "check_runs": check_runs,
                     "api_user": apis_dict[repo]["user"],
                 },
             )
         )
📝 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
for repo, data in config_.data["repositories"].items():
futures.append(
executor.submit(
set_repository_check_runs_to_queued,
**{
"config_": config_,
"data": data,
"github_api": github_api,
"github_api": apis_dict[repo]["api"],
"check_runs": check_runs,
"api_user": apis_dict[repo]["user"],
},
)
)
with ThreadPoolExecutor() as executor:
for repo, data in config_.data["repositories"].items():
if repo not in apis_dict:
logger.error(f"Repository {repo} not found in APIs dictionary. Skipping.")
continue
if "api" not in apis_dict[repo] or "user" not in apis_dict[repo]:
logger.error(f"Missing API or user for repository {repo}. Skipping.")
continue
futures.append(
executor.submit(
set_repository_check_runs_to_queued,
**{
"config_": config_,
"data": data,
"github_api": apis_dict[repo]["api"],
"check_runs": check_runs,
"api_user": apis_dict[repo]["user"],
},
)
)

@myakove
Copy link
Copy Markdown
Collaborator Author

myakove commented Mar 7, 2025

/verified

@myakove myakove merged commit 3a31b27 into main Mar 7, 2025
@myakove myakove deleted the set-repositories-use-repo-api-take2 branch March 7, 2025 22:35
@myakove-bot
Copy link
Copy Markdown
Collaborator

New container for ghcr.io/myk-org/github-webhook-server:latest published

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants