Skip to content

RHINENG-28312: simplify API db context handling - #2375

Open
MichaelMraka wants to merge 4 commits into
RedHatInsights:masterfrom
MichaelMraka:pr2
Open

MichaelMraka wants to merge 4 commits into
RedHatInsights:masterfrom
MichaelMraka:pr2

Conversation

@MichaelMraka

@MichaelMraka MichaelMraka commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Secure Coding Practices Checklist GitHub Link

Secure Coding Checklist

  • Input Validation
  • Output Encoding
  • Authentication and Password Management
  • Session Management
  • Access Control
  • Cryptographic Practices
  • Error Handling and Logging
  • Data Protection
  • Communication Security
  • System Configuration
  • Database Security
  • File Management
  • Memory Management
  • General Coding Practices

Summary by Sourcery

Centralize request-aware database connection handling across API and administrative handlers.

Enhancements:

  • Simplify request-scoped database access by resolving primary or read-replica connections directly from the Gin context.
  • Separate read/write database access and update API, admin, and controller handlers to use the centralized database helpers.
  • Improve controller test utilities by localizing router and context setup.

Tests:

  • Add coverage for database routing, request context propagation, and preventing direct database access from controllers.

Chores:

  • Remove the database middleware that stored connections in request context and delete the shared core testing helpers.

@MichaelMraka
MichaelMraka requested a review from a team as a code owner October 29, 2026 11:28
@sourcery-ai

sourcery-ai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Simplifies API database context handling by resolving GORM handles directly from the current request context instead of storing them in Gin middleware, while preserving read-replica routing, directing writes to the primary database, migrating all affected handlers, and adding enforcement tests.

File-Level Changes

Change Details Files
Replaced middleware-injected database handles with request-context-bound accessors.
  • Added DB for read queries with optional GET read-replica routing.
  • Added DBWriter for operations that must use the primary database.
  • Removed database setup middleware from API, admin, and test routers.
  • Migrated controllers, probes, and admin handlers to the new accessors.
manager/middlewares/db.go
manager/routes/routes.go
turnpike/admin_api.go
base/core/gintesting.go
base/core/probes.go
manager/controllers/*.go
turnpike/controllers/*.go
Added coverage to validate database selection and enforce the new access pattern.
  • Tested replica eligibility by configuration and HTTP method.
  • Verified request context propagation and primary-pool selection.
  • Added AST-based checks preventing direct database handle acquisition in handlers.
manager/middlewares/db_test.go
Improved database connectivity error handling for health/status endpoints.
  • Handled errors returned while obtaining the SQL database handle.
  • Returned service-unavailable responses when the database handle or ping is unavailable.
base/core/probes.go
manager/controllers/status.go

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="manager/middlewares/db_test.go" line_range="47" />
<code_context>
+	assert.False(t, useReadReplica(ginWithMethod(http.MethodGet)))
+
+	utils.CoreCfg.DBReadReplicaEnabled = true
+	assert.True(t, useReadReplica(ginWithMethod(http.MethodGet)))
+	assert.False(t, useReadReplica(ginWithMethod(http.MethodPost)))
+	assert.False(t, useReadReplica(ginWithMethod(http.MethodPut)))
</code_context>
<issue_to_address>
**Replica selection goes untested**

When `DB(c)` is changed to always return the primary handle while `useReadReplica` still returns true for GET requests, `TestUseReadReplica` asserts only that `useReadReplica` returns true; the database-handle tests force replica use off. If `DB(c)` always returns the primary handle, these assertions still pass and replica reads silently go to the primary.

With replica use enabled, assert that `DB(c)` returns the configured replica's pool.
</issue_to_address>

### Comment 2
<location path="base/core/probes.go" line_range="4" />
<code_context>

 import (
-	"app/base/database"
+	"app/manager/middlewares"
 	"net/http"

</code_context>
<issue_to_address>
**Core probes depend on manager middleware**

`base/core` now imports `manager/middlewares` to obtain a primary database handle, so shared probe code used by services such as the aggregator, evaluator, and listener also depends on the manager layer. This couples foundational health checks to API middleware and makes future manager-middleware dependencies leak into those services.

Move the request-scoped primary database accessor into a shared base/database layer and have the probes use it directly.
</issue_to_address>

Sourcery assessment

Approval pending. 1 finding to address first.

Blocking findings: manager/middlewares/db_test.go:47


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread manager/middlewares/db_test.go Resolved
Comment thread base/core/probes.go Resolved
@codecov-commenter

codecov-commenter commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.28571% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 60.26%. Comparing base (6d3658d) to head (13cbcbd).

Files with missing lines Patch % Lines
manager/controllers/status.go 0.00% 4 Missing ⚠️
turnpike/controllers/database.go 0.00% 3 Missing ⚠️
manager/middlewares/db.go 66.66% 1 Missing and 1 partial ⚠️
manager/controllers/system_detail.go 50.00% 1 Missing ⚠️
turnpike/controllers/admin.go 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2375      +/-   ##
==========================================
+ Coverage   60.14%   60.26%   +0.12%     
==========================================
  Files         158      157       -1     
  Lines       10161    10158       -3     
==========================================
+ Hits         6111     6122      +11     
+ Misses       3424     3410      -14     
  Partials      626      626              
Flag Coverage Δ
unittests 60.26% <84.28%> (+0.12%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

The tests lock replica selection, request context, and a ban on handlers calling database.DB directly.
… context.

Handlers no longer depend on a Gin key captured in middleware.
…in handlers.

Primary-only routes call DBWriter so status, probes, and admin SQL stay off the read replica.
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.

2 participants