Skip to content

Conversation

@86254860
Copy link
Contributor

@86254860 86254860 commented Jan 30, 2026

Summary

  • Adopt standard .golangci.yml
  • Temporarily disable revive in .golangci.yml, because it reports 405 lint errors (e.g., missing comments on exported functions/types), which would require more effort
  • Fix goconst, gocritic, gosec, unparam and lll lint issues

Testing

  • make lint pass
  • make test pass

Summary by CodeRabbit

  • Chores

    • Enhanced code quality through stricter linting rules and consistent formatting standards.
    • Improved server reliability with HTTP request header timeout configuration.
    • Refined test security posture with restricted file permissions.
  • Style

    • Applied standardized code formatting and structure improvements across the codebase.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Jan 30, 2026

Walkthrough

This pull request applies comprehensive code quality and formatting improvements across 50+ files. The main change is a significantly expanded .golangci.yml configuration with detailed linting rules and directives. Throughout the codebase, function signatures are reformatted to multi-line format with trailing commas, and numerous hardcoded string literals are replaced with named constants. HTTP servers receive ReadHeaderTimeout: 10s configurations, and several conditional chains are refactored to switch statements. The codebase gains new constants for condition types and standardized values, along with a new MapAdapterToConditionType function. Minor semantic changes include test file permissions tightened from 0644 to 0600, improved error handling in telemetry initialization, and removal of an unused tableName parameter from an internal helper function.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested labels

refactoring, code-quality, formatting

Suggested reviewers

  • crizzo71
  • jsell-rh
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 49.28% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main changes: adopting a standard .golangci.yml and fixing lint issues across the codebase.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Copy link

@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: 1

🤖 Fix all issues with AI agents
In `@pkg/auth/authz_middleware.go`:
- Around line 49-50: The middleware (authz_middleware.go) currently returns
early on missing auth/context errors without writing a response; update the
error branches in the AuthzMiddleware handler to create and send proper HTTP
error responses (use api.E401 or api.E403 for auth failures and api.E500 for
backend errors) via api.SendError(w, r, &body) instead of returning silently,
and remove the no-op fmt.Errorf calls; apply the same change to the other
early-return branches referenced (the ones around lines 59-60 and 69-70) so
every failure path writes an appropriate error body and status.
🧹 Nitpick comments (7)
pkg/db/transactions.go (1)

14-21: Don’t discard ctx; use it when starting the transaction.
Line 14 now explicitly ignores context. Consider using BeginTx(ctx, ...) (or a context-derived session) to honor cancellation/timeouts and align with repo guidance.

Suggested adjustment
-func newTransaction(_ context.Context, connection SessionFactory) (*transaction.Transaction, error) {
+func newTransaction(ctx context.Context, connection SessionFactory) (*transaction.Transaction, error) {
@@
-	tx, err := dbx.Begin()
+	tx, err := dbx.BeginTx(ctx, nil)

As per coding guidelines: Always retrieve database sessions from context via db.NewContext(ctx) rather than creating new GORM connections directly.

pkg/services/cluster_test.go (3)

322-331: Inconsistent use of "Ready" literal vs conditionTypeReady constant.

Line 324 uses the string literal "Ready" while conditionTypeAvailable constant is used on Line 316. For consistency and maintainability, consider using conditionTypeReady here as well.

Suggested fix
 		{
-			Type:               "Ready",
+			Type:               conditionTypeReady,
 			Status:             api.ConditionFalse,

392-408: Same inconsistency: "Ready" literal at Line 394.

This test case uses "Ready" string literal while other tests in the file use conditionTypeReady. Consider using the constant for consistency.


676-684: Inconsistent use of "Ready" literal at Line 678.

Similar to earlier instances, Line 678 uses string literal "Ready" while Line 670 uses conditionTypeAvailable. Consider using conditionTypeReady for consistency.

pkg/services/cluster.go (2)

173-179: Inconsistent use of "Available" string literal.

Line 175 uses the string literal "Available" to find the Available condition. However, pkg/services/node_pool.go uses conditionTypeAvailable constant at the equivalent location (Line 176). Consider using the constant here for consistency.

Suggested fix
 		// Find the "Available" condition
 		var availableCondition *api.AdapterCondition
 		for i := range conditions {
-			if conditions[i].Type == "Available" {
+			if conditions[i].Type == conditionTypeAvailable {
 				availableCondition = &conditions[i]
 				break
 			}

266-279: Inconsistent use of "Available" string literal at Line 269.

Similar to the issue at Line 175, this uses the string literal "Available" while node_pool.go uses conditionTypeAvailable. Using the constant ensures both files stay synchronized.

Suggested fix
 	// Find the "Available" condition
 	hasAvailableCondition := false
 	for _, cond := range conditions {
-		if cond.Type != "Available" {
+		if cond.Type != conditionTypeAvailable {
 			continue
 		}
pkg/services/status_aggregation.go (1)

70-103: Consider extracting the common adapter map building logic.

Both ComputeAvailableCondition and ComputeReadyCondition contain nearly identical code for building the adapterMap (unmarshaling conditions JSON and extracting the "Available" condition). This could be refactored into a shared helper function to reduce duplication.

♻️ Example helper extraction
// buildAdapterAvailabilityMap extracts availability info from adapter statuses
func buildAdapterAvailabilityMap(adapterStatuses api.AdapterStatusList) map[string]struct {
	available          string
	observedGeneration int32
} {
	adapterMap := make(map[string]struct {
		available          string
		observedGeneration int32
	})

	for _, adapterStatus := range adapterStatuses {
		var conditions []struct {
			Type   string `json:"type"`
			Status string `json:"status"`
		}
		if len(adapterStatus.Conditions) > 0 {
			if err := json.Unmarshal(adapterStatus.Conditions, &conditions); err == nil {
				for _, cond := range conditions {
					if cond.Type == conditionTypeAvailable {
						adapterMap[adapterStatus.Adapter] = struct {
							available          string
							observedGeneration int32
						}{
							available:          cond.Status,
							observedGeneration: adapterStatus.ObservedGeneration,
						}
						break
					}
				}
			}
		}
	}
	return adapterMap
}

Also applies to: 139-174

Comment on lines +49 to +50
// body := api.E500.Format(r, "Authentication details not present in context")
// api.SendError(w, r, &body)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Return explicit HTTP errors instead of silent early exits.
These branches return without writing a response, which yields misleading 200/empty bodies for auth failures or backend errors. Send 401/403/500 (or your standard error body) and remove the no-op fmt.Errorf calls.

🛠️ Suggested fix
-import (
-	"fmt"
-	"net/http"
-
-	"github.com/openshift-hyperfleet/hyperfleet-api/pkg/client/ocm"
-)
+import (
+	"net/http"
+
+	"github.com/openshift-hyperfleet/hyperfleet-api/pkg/client/ocm"
+)
@@
 		username := GetUsernameFromContext(ctx)
 		if username == "" {
-			_ = fmt.Errorf("authenticated username not present in request context")
-			// TODO
-			// body := api.E500.Format(r, "Authentication details not present in context")
-			// api.SendError(w, r, &body)
+			http.Error(w, "authentication details not present in context", http.StatusUnauthorized)
 			return
 		}
@@
 		if err != nil {
-			_ = fmt.Errorf("unable to make authorization request: %s", err)
-			// TODO
-			// body := api.E500.Format(r, "Unable to make authorization request")
-			// api.SendError(w, r, &body)
+			http.Error(w, "unable to make authorization request", http.StatusInternalServerError)
 			return
 		}
 
 		if allowed {
 			next.ServeHTTP(w, r)
+			return
 		}
 
-		// TODO
-		// body := api.E403.Format(r, "")
-		// api.SendError(w, r, &body)
+		http.Error(w, "forbidden", http.StatusForbidden)
 	})
 }

Also applies to: 59-60, 69-70

🤖 Prompt for AI Agents
In `@pkg/auth/authz_middleware.go` around lines 49 - 50, The middleware
(authz_middleware.go) currently returns early on missing auth/context errors
without writing a response; update the error branches in the AuthzMiddleware
handler to create and send proper HTTP error responses (use api.E401 or api.E403
for auth failures and api.E500 for backend errors) via api.SendError(w, r,
&body) instead of returning silently, and remove the no-op fmt.Errorf calls;
apply the same change to the other early-return branches referenced (the ones
around lines 59-60 and 69-70) so every failure path writes an appropriate error
body and status.

Copy link
Contributor

@ciaranRoche ciaranRoche left a comment

Choose a reason for hiding this comment

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

/lgtm

@openshift-ci
Copy link

openshift-ci bot commented Jan 30, 2026

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: ciaranRoche

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-merge-bot openshift-merge-bot bot merged commit 1c08cb2 into openshift-hyperfleet:main Jan 30, 2026
8 checks passed
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