Skip to content

Extract /api/ timeout-override middleware out of runServeCmd#47891

Open
raju249 wants to merge 1 commit into
fleetdm:mainfrom
raju249:33370-api-timeout-middleware-extraction
Open

Extract /api/ timeout-override middleware out of runServeCmd#47891
raju249 wants to merge 1 commit into
fleetdm:mainfrom
raju249:33370-api-timeout-middleware-extraction

Conversation

@raju249

@raju249 raju249 commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Extracts the /api/ request timeout/body-size override middleware out of runServeCmd and into apiTimeoutOverrideHandler in a new cmd/fleet/http_middleware.go. Same pattern as the prior extractions on this issue (#44929, #45343, #45583, #46166, #46421, #46517, #46742, #46830, #46893, #47151, #47562). runServeCmd drops from ~1000 to ~900 lines, and serve.go from 1475 to 1373.

The middleware is the ~100-line rootMux.HandleFunc("/api/", ...) closure that applies per-route read/write deadline overrides for endpoints that legitimately run long — synchronous script runs, large software-installer and bootstrap-package uploads, the Android enterprise signup SSE stream, and large MDM profile batch operations — and, for package-upload routes, caps the request body and threads the configured max installer size through the request context.

Behavior is preserved — the handler is moved verbatim and wired into rootMux via a single apiTimeoutOverrideHandler(apiHandler, config, logger) call, so the same routes get the same overrides and every request still falls through to apiHandler.ServeHTTP. The now-unused scripts and installersize imports drop out of serve.go.

On test scope: TestAPITimeoutOverrideHandler verifies the real decision in this middleware — that package-upload paths thread the configured max installer size into the request context (and non-upload requests keep the default) — and that the wrapped API handler is always invoked. The deadline overrides themselves go through http.ResponseController, which a unit-test ResponseRecorder doesn't support (the handler logs and proceeds, as in production), so those are exercised by booting the server rather than asserted in a unit test.

Related issue: Refs #33370

Checklist for submitter

  • Added/updated automated tests
  • QA'd all new/changed functionality manually (verified via local server boot)
  • Changes file: not applicable — internal refactor with no user-visible behavior change

Summary by CodeRabbit

  • Refactor
    • Improved timeout handling for long-running operations across the API. Script execution, file uploads, Server-Sent Event streams, and batch operations now have optimized request timeouts and body size limits.

Move the per-route request read/write deadline overrides (sync script
runs, large installer/bootstrap uploads, Android signup SSE, MDM profile
batch) into apiTimeoutOverrideHandler in a new cmd/fleet/http_middleware.go.
Behavior is unchanged; the closure is wired into rootMux via a single call.

Add a unit test covering the installer max-size context threading for
package-upload paths and that the wrapped handler is always invoked.

Refs fleetdm#33370
@raju249 raju249 requested a review from a team as a code owner June 19, 2026 03:56

@claude claude 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.

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@coderabbitai

coderabbitai Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The inline HTTP middleware closure registered at /api/ in serve.go is extracted into a standalone apiTimeoutOverrideHandler function in a new cmd/fleet/http_middleware.go file. The function accepts the downstream handler, Fleet config, and logger, then applies per-route ResponseController read/write deadline overrides and request-body limits based on request method and URL path. serve.go is updated to call this function directly and drops the scripts and installersize imports that were only required by the now-removed inline closure. A new test file verifies downstream handler invocation and correct installer-size context propagation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% 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
Title check ✅ Passed The title accurately describes the main change: extracting the /api/ timeout-override middleware out of runServeCmd into a dedicated function.
Description check ✅ Passed The description includes the related issue reference (#33370), explains the changes comprehensively, documents test coverage, and notes that no changes file is needed for this internal refactor.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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)
cmd/fleet/http_middleware_test.go (1)

21-45: ⚡ Quick win

Expand table coverage for the remaining middleware route predicates.

This test currently protects only a subset of the branch conditions in apiTimeoutOverrideHandler. Adding cases for PATCH title-package, package-token GET, and orbit package POST would make this refactor safer against predicate drift.

Suggested additions
@@
 		{
 			name:              "non-upload request leaves the default max size",
 			method:            http.MethodGet,
 			path:              "/api/latest/fleet/hosts",
 			wantInstallerSize: installersize.MaxSoftwareInstallerSize,
 		},
+		{
+			name:              "title package patch threads configured max size",
+			method:            http.MethodPatch,
+			path:              "/api/latest/fleet/software/titles/123/package",
+			wantInstallerSize: customMax,
+		},
+		{
+			name:              "package token route threads configured max size",
+			method:            http.MethodGet,
+			path:              "/api/latest/fleet/software/titles/123/package/token",
+			wantInstallerSize: customMax,
+		},
+		{
+			name:              "orbit package route threads configured max size",
+			method:            http.MethodPost,
+			path:              "/api/latest/fleet/orbit/software_install/package",
+			wantInstallerSize: customMax,
+		},
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/fleet/http_middleware_test.go` around lines 21 - 45, The table-driven
test is missing coverage for some route predicates handled by
apiTimeoutOverrideHandler. Add three new test cases to the existing table
following the same struct pattern with name, method, path, and wantInstallerSize
fields: one for PATCH title-package endpoint, one for package-token GET
endpoint, and one for orbit package POST endpoint. Each should specify the
appropriate HTTP method, route path, and expected installer size value to ensure
all branch conditions in apiTimeoutOverrideHandler are tested.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@cmd/fleet/http_middleware_test.go`:
- Around line 21-45: The table-driven test is missing coverage for some route
predicates handled by apiTimeoutOverrideHandler. Add three new test cases to the
existing table following the same struct pattern with name, method, path, and
wantInstallerSize fields: one for PATCH title-package endpoint, one for
package-token GET endpoint, and one for orbit package POST endpoint. Each should
specify the appropriate HTTP method, route path, and expected installer size
value to ensure all branch conditions in apiTimeoutOverrideHandler are tested.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3c65f18e-8048-438d-9adc-494974a50544

📥 Commits

Reviewing files that changed from the base of the PR and between c03797c and 50fbd3c.

📒 Files selected for processing (3)
  • cmd/fleet/http_middleware.go
  • cmd/fleet/http_middleware_test.go
  • cmd/fleet/serve.go

@raju249

raju249 commented Jun 19, 2026

Copy link
Copy Markdown
Contributor Author

Hello @MagnusHJensen 👋

I extracted the api handler here into its own file with a test. It reduces the size of serve.go marginally. What do you think? Mind taking a review, please?

@codecov

codecov Bot commented Jun 19, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 45.31250% with 35 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.24%. Comparing base (a43856a) to head (50fbd3c).
⚠️ Report is 22 commits behind head on main.

Files with missing lines Patch % Lines
cmd/fleet/http_middleware.go 46.03% 31 Missing and 3 partials ⚠️
cmd/fleet/serve.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main   #47891    +/-   ##
========================================
  Coverage   67.23%   67.24%            
========================================
  Files        3637     3641     +4     
  Lines      229949   230164   +215     
  Branches    11788    11788            
========================================
+ Hits       154608   154772   +164     
- Misses      61457    61489    +32     
- Partials    13884    13903    +19     
Flag Coverage Δ
backend 68.86% <45.31%> (+<0.01%) ⬆️

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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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.

1 participant