Skip to content

refactor: extract gh client generation into gh package - #997

Merged
adityachoudhari26 merged 2 commits into
mainfrom
consolidate-gh-logic
Apr 15, 2026
Merged

adityachoudhari26 merged 2 commits into
mainfrom
consolidate-gh-logic

Conversation

@adityachoudhari26

@adityachoudhari26 adityachoudhari26 commented Apr 15, 2026 •

Copy link
Copy Markdown
Member

fixes #996

Summary by CodeRabbit

  • Refactor
    • Consolidated GitHub application authentication logic into a centralized service. This improves code maintainability and reduces duplication across internal modules without affecting end-user functionality.

Copilot AI review requested due to automatic review settings April 15, 2026 20:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Refactors the workspace-engine GitHub job agent to centralize GitHub App client creation logic into a dedicated pkg/github package (fixing #996), and updates the workflow dispatcher to use the new client factory.

Changes:

  • Replace per-agent GitHub client generation in the workflow dispatcher with pkg/github.CreateClientForInstallation.
  • Remove the legacy pkg/githubclient implementation.
  • Add pkg/github/client.go providing GitHub App JWT creation plus installation/repo-scoped client helpers.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
apps/workspace-engine/pkg/jobagents/github/workflow_dispatcher.go Switches workflow dispatch to use the new centralized GitHub client factory.
apps/workspace-engine/pkg/githubclient/githubclient.go Removes the old GitHub client/JWT/token exchange implementation.
apps/workspace-engine/pkg/github/client.go Introduces new shared GitHub App client generation and installation/repo client helpers.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +45 to +51
func appClient() (*github.Client, error) {
jwtStr, err := generateJWT()
if err != nil {
return nil, err
}
return github.NewClient(nil).WithAuthToken(jwtStr), nil
}

Copilot AI Apr 15, 2026

Copy link

Choose a reason for hiding this comment

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

github.NewClient(nil) uses the default HTTP client (no timeout). Since callers often pass a context without a deadline (e.g. async dispatch), GitHub API calls can hang indefinitely. Consider constructing a shared *http.Client with a sane Timeout and passing it into github.NewClient, and/or wrapping calls in context.WithTimeout inside this package.

Copilot uses AI. Check for mistakes.
Comment on lines +65 to +71
token, _, err := app.Apps.CreateInstallationToken(ctx, installationID, nil)
if err != nil {
return nil, fmt.Errorf("create installation token: %w", err)
}

return github.NewClient(nil).WithAuthToken(token.GetToken()), nil
}

Copilot AI Apr 15, 2026

Copy link

Choose a reason for hiding this comment

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

The installation-authenticated client is created with github.NewClient(nil) as well, inheriting http.DefaultClient without timeouts. To avoid indefinitely hung dispatches/token refreshes, pass a configured *http.Client (Timeout/Transport) into github.NewClient here too (and ideally reuse the same client as appClient).

Copilot uses AI. Check for mistakes.
@coderabbitai

coderabbitai Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@adityachoudhari26 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 50 minutes and 40 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 50 minutes and 40 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c70327d0-1178-4dfd-9d5a-33502cb8a384

📥 Commits

Reviewing files that changed from the base of the PR and between e093928 and fce9035.

📒 Files selected for processing (1)
  • apps/workspace-engine/pkg/github/client.go
📝 Walkthrough

Walkthrough

A refactoring that consolidates GitHub App authentication logic from scattered locations (githubclient package and workflow_dispatcher.go) into a centralized github/client.go module with two public functions: one for creating clients for known installations by ID, and another for discovering installations from repository references.

Changes

Cohort / File(s) Summary
Centralized GitHub Client Implementation
apps/workspace-engine/pkg/github/client.go
New file providing JWT generation and GitHub App authentication. Exports CreateClientForInstallation() and CreateClientForRepo() to create per-installation go-github clients via installation access tokens.
Removed Old Client Implementation
apps/workspace-engine/pkg/githubclient/githubclient.go
Deleted entire file containing duplicate GitHub App JWT generation and token exchange logic previously used for client creation.
Updated Client Usage
apps/workspace-engine/pkg/jobagents/github/workflow_dispatcher.go
Removed local GitHub authentication logic and HTTP token-exchange code; now delegates to gh.CreateClientForInstallation() from the centralized github package.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • PR #762: Implements the same GitHub App authentication flow with JWT generation and installation token exchange, consolidating duplicate client creation logic across multiple packages.
  • PR #711: Adds similar GitHub App client creation functionality in apps/.../pkg/githubclient/githubclient.go; this PR centralizes and refactors that same logic into apps/workspace-engine/pkg/github/client.go.
  • PR #680: Implements GitHub App authentication and per-installation client creation; this PR moves and consolidates similar functionality into a shared github package.

Suggested reviewers

  • jsbroks

Poem

🐰 Scattered secrets, now as one,
GitHub tokens dance and run,
From many homes to central place,
Authentication finds its grace,
Clean code hops with joyful pace! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'refactor: extract gh client generation into gh package' clearly and concisely describes the main change: moving GitHub client generation logic into a dedicated package.
Linked Issues check ✅ Passed The PR successfully consolidates GitHub client generation logic by creating new functions in the github package and removing duplicate logic from the githubclient package and workflow_dispatcher.go.
Out of Scope Changes check ✅ Passed All changes are directly related to consolidating GitHub client generation logic: new client.go file, removal of duplicate githubclient.go, and refactoring workflow_dispatcher.go to use the centralized implementation.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch consolidate-gh-logic

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
apps/workspace-engine/pkg/github/client.go (1)

76-83: Consider checking config upfront for clarity.

The current pattern calls appClient(), catches the error, then re-checks the config to determine if it was a "not configured" scenario. This duplicates the config validation logic. Checking upfront would be more explicit about the early return path.

♻️ Suggested refactor
 func CreateClientForRepo(ctx context.Context, owner, repo string) (*github.Client, error) {
+	if config.Global.GithubBotAppID == "" || config.Global.GithubBotPrivateKey == "" {
+		return nil, nil
+	}
+
 	app, err := appClient()
 	if err != nil {
-		if config.Global.GithubBotAppID == "" || config.Global.GithubBotPrivateKey == "" {
-			return nil, nil
-		}
 		return nil, err
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/workspace-engine/pkg/github/client.go` around lines 76 - 83, The code in
CreateClientForRepo calls appClient() and then inspects
config.Global.GithubBotAppID and config.Global.GithubBotPrivateKey only on
error, duplicating config validation; instead, check the config values up-front
in CreateClientForRepo (inspect config.Global.GithubBotAppID and
config.Global.GithubBotPrivateKey) and return nil,nil immediately if not
configured, then call appClient() and return its error normally—this removes the
duplicate config check and makes the early-return path explicit while keeping
appClient() usage unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/workspace-engine/pkg/github/client.go`:
- Around line 76-83: The code in CreateClientForRepo calls appClient() and then
inspects config.Global.GithubBotAppID and config.Global.GithubBotPrivateKey only
on error, duplicating config validation; instead, check the config values
up-front in CreateClientForRepo (inspect config.Global.GithubBotAppID and
config.Global.GithubBotPrivateKey) and return nil,nil immediately if not
configured, then call appClient() and return its error normally—this removes the
duplicate config check and makes the early-return path explicit while keeping
appClient() usage unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 03e00e2a-dbe9-4092-9a31-66ca1cdafe3f

📥 Commits

Reviewing files that changed from the base of the PR and between 3dc45b6 and e093928.

📒 Files selected for processing (3)
  • apps/workspace-engine/pkg/github/client.go
  • apps/workspace-engine/pkg/githubclient/githubclient.go
  • apps/workspace-engine/pkg/jobagents/github/workflow_dispatcher.go
💤 Files with no reviewable changes (1)
  • apps/workspace-engine/pkg/githubclient/githubclient.go

@adityachoudhari26
adityachoudhari26 merged commit 55b7275 into main Apr 15, 2026
8 of 9 checks passed
@adityachoudhari26
adityachoudhari26 deleted the consolidate-gh-logic branch April 15, 2026 20:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: consolidate github client generation logic into github package

2 participants