[management] Fix data race on ctx in HTTP metrics middleware

Merged
ML
2d ago
+9-7

Describe your changes

The HTTP metrics middleware registers a context.AfterFunc whose callback reads the local ctx (for context.Cause), while the handler reassigns ctx = req.Context() after ServeHTTP. If the request context is cancelled as the handler finishes, the callback goroutine reads ctx concurrently with that write.

go test -race -tags devcert -count=8 -run TestBrokerLimitsCallbacksPerClient ./management/internals/modules/mcpapi/ reports WARNING: DATA RACE at http_api_metrics.go:207 (write) vs :198 (read) on main.

The callback now captures the request context in its own variable, the post-ServeHTTP context uses a separate respCtx, and the AfterFunc stop function is called once the handler returns. Logging and metrics behaviour is unchanged.

Verified: the reproduction above at -count=50 shows no race, and go test -race -tags devcert ./management/server/telemetry/... ./management/internals/modules/mcpapi/... passes.

Issue ticket number and link

None, trivial race fix.

Stack

Checklist

  • Is it a bug fix
  • Is a typo/documentation fix
  • Is a feature enhancement
  • It is a refactor
  • Created tests that fail without the change (if possible)
  • I ran and tested this change locally — I did not rely on CI to find out whether it works
  • This PR has a single purpose (not a fix + refactor + feature in one)
  • This change is a trivial fix, OR it links an issue the NetBird team agreed on beforehand. Changes to the public API, gRPC protocols, functionality behavior, CLI / service flags, or new features always need that agreement first. See CONTRIBUTING.md.

By submitting this pull request, you confirm that you have read and agree to the terms of the Contributor License Agreement.

Documentation

Select exactly one:

  • I added/updated documentation for this change
  • Documentation is not needed for this change (explain why)

Internal race fix with no user-facing change.

Docs PR URL (required if "docs added" is checked)

Paste the PR link from https://github.com/netbirdio/docs here:

https://github.com/netbirdio/docs/pull/__


Generated by Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved the accuracy of HTTP request telemetry when request context changes during handling. Cancellation details and response timing are now recorded using the appropriate context.