mirror of
https://github.com/lukaszraczylo/graphql-monitoring-proxy.git
synced 2026-10-20 06:28:13 +00:00
perf+coverage: optimisation pass + coverage push to ≥70%
Performance / resource usage: - circuit_breaker_metrics: fix data race on failCounters map (RWMutex + double-checked locking) - server.go: drop user_id and op_name metric labels (Prometheus cardinality bound); de-duplicate extractUserInfo - graphql.go: gate runtime.ReadMemStats per-request behind ENABLE_ALLOCATION_TRACKING flag (default off) - graphql.go: collapse two-pass AST scan into single pass; lower-case once - sanitization.go: cache compiled redaction regexes per pattern via sync.Map; hoist inner constants to pkg vars - proxy.go: hoist connection/timeout substrings to pkg vars; sentinel errors for static error paths; drop dead Headers map alloc - metrics_aggregator.go: log-field allocation guarded by Logger.IsLevelEnabled - logging/logger.go: add IsLevelEnabled helper - lru_cache.go: 16-shard sharding, FNV-1a routing (concurrent throughput +22%) - cache/memory/lru_memory_cache.go: gzip compress/decompress moved outside mu.Lock - rps_tracker.go: RWMutex+uint64 -> atomic.Uint64 - retry_budget.go: drop unused mutex - api.go: bannedUsersIDs map+RWMutex -> sync.Map (+ snapshot/replace helpers) - tracing/tracing.go: pkg-level constSpanAttrs, copy-then-append in StartSpanWithAttributes - admin_dashboard.go: handleStatsWebSocket reuses bytes.Buffer + json.Encoder per connection Build / runtime: - Makefile: -ldflags="-s -w" -trimpath, CGO_ENABLED=0 for build (=1 for test recipes) - Dockerfile + Dockerfile.goreleaser: ENV GOMEMLIMIT=512MiB - main.go: blank import go.uber.org/automaxprocs (cgroup-aware GOMAXPROCS) - main.go: PPROF_PORT env var wires net/http/pprof on 127.0.0.1 only with full server timeouts - README.md: env-var docs + metric-label docs updated; cardinality note Test coverage push (per package): - main 51.2% -> 74.7% - cache 66.3% -> 93.7% - cache/redis 45.5% -> 98.2% - tracing 66.7% -> 72.9% - (cache/memory 91.6%, logging 91.9%, monitoring 77.6%, pkg/pools 100% unchanged) New test files: coverage_micro_test, coverage_extras_test, server_handlers_test, api_health_test, admin_dashboard_cluster_test, metrics_aggregator_test, concerns_test, cache/cache_coverage_test, cache/redis/redis_coverage_test, tracing/tracing_coverage_test. Bug fix: connection_resilience_test.go TestIntegratedHealthManagement.health_manager_startup was sync.Once-coupled to InitializeBackendHealth and panicked when another test (e.g. via parseConfig) had already triggered Once. Use NewBackendHealthManager directly.
This commit is contained in:
@@ -31,6 +31,19 @@ var (
|
||||
ErrCircuitOpen = errors.New("circuit breaker is open")
|
||||
)
|
||||
|
||||
// Sentinel errors for the proxy request retry path. Grouped here so callers
|
||||
// can use errors.Is for comparison instead of brittle string matching.
|
||||
// Message text MUST match the historical fmt.Errorf strings — tests and
|
||||
// callers may assert on .Error().
|
||||
var (
|
||||
// errFiberCtxNilDuringRetry — fiber context dropped while retrying.
|
||||
errFiberCtxNilDuringRetry = errors.New("fiber context became nil during retry")
|
||||
// errFiberRespNil — fiber response object became nil mid-request.
|
||||
errFiberRespNil = errors.New("fiber response became nil")
|
||||
// errFiberCtxNil — fiber context was nil before the request started.
|
||||
errFiberCtxNil = errors.New("fiber context is nil")
|
||||
)
|
||||
|
||||
// Default values for circuit breaker
|
||||
const (
|
||||
defaultMaxRequestsInHalfOpen = 10 // Default maximum requests in half-open state
|
||||
@@ -42,6 +55,30 @@ var (
|
||||
cbMutex sync.RWMutex
|
||||
)
|
||||
|
||||
// Package-level substring tables used by isConnectionError / isTimeoutError.
|
||||
// Hoisted to avoid per-call slice allocations on the hot path. All entries
|
||||
// must be lower-case; callers lower-case the error string once before matching.
|
||||
var (
|
||||
connectionErrorSubstrings = []string{
|
||||
"connection refused",
|
||||
"connection reset",
|
||||
"no route to host",
|
||||
"network is unreachable",
|
||||
"broken pipe",
|
||||
"connection closed",
|
||||
"eof",
|
||||
"no such host",
|
||||
"dial tcp",
|
||||
"dial udp",
|
||||
}
|
||||
|
||||
timeoutErrorSubstrings = []string{
|
||||
"timeout",
|
||||
"deadline exceeded",
|
||||
"context deadline exceeded",
|
||||
}
|
||||
)
|
||||
|
||||
// safeUint32 converts an int to uint32 safely, handling negative values and values exceeding uint32 max
|
||||
func safeUint32(value int) uint32 {
|
||||
// Handle negative values
|
||||
@@ -351,7 +388,7 @@ func performProxyRequest(c *fiber.Ctx, proxyURL string) error {
|
||||
return &CoalescedResponse{
|
||||
Body: c.Response().Body(),
|
||||
StatusCode: c.Response().StatusCode(),
|
||||
Headers: make(map[string]string),
|
||||
// Headers intentionally left nil; not populated or read anywhere.
|
||||
}, nil
|
||||
})
|
||||
|
||||
@@ -449,7 +486,7 @@ func performProxyRequestWithRetries(c *fiber.Ctx, proxyURL string) error {
|
||||
func executeProxyAttempt(c *fiber.Ctx, proxyURL string) error {
|
||||
// Additional safety check inside retry loop
|
||||
if c == nil {
|
||||
return retry.Unrecoverable(fmt.Errorf("fiber context became nil during retry"))
|
||||
return retry.Unrecoverable(errFiberCtxNilDuringRetry)
|
||||
}
|
||||
|
||||
// Get connection pool manager for stats tracking
|
||||
@@ -486,7 +523,7 @@ func executeProxyAttempt(c *fiber.Ctx, proxyURL string) error {
|
||||
|
||||
// Safety check before accessing response (c is already validated at function entry)
|
||||
if c.Response() == nil {
|
||||
return retry.Unrecoverable(fmt.Errorf("fiber response became nil"))
|
||||
return retry.Unrecoverable(errFiberRespNil)
|
||||
}
|
||||
|
||||
// Check status code and determine retry strategy
|
||||
@@ -518,7 +555,7 @@ func executeProxyAttempt(c *fiber.Ctx, proxyURL string) error {
|
||||
func performProxyRequestWithEnhancedRetries(c *fiber.Ctx, proxyURL string, backendUnhealthy bool) error {
|
||||
// Safety check for nil context
|
||||
if c == nil {
|
||||
return fmt.Errorf("fiber context is nil")
|
||||
return errFiberCtxNil
|
||||
}
|
||||
|
||||
var attempts uint
|
||||
@@ -620,20 +657,7 @@ func isConnectionError(err error) bool {
|
||||
}
|
||||
|
||||
errStr := strings.ToLower(err.Error())
|
||||
connectionErrors := []string{
|
||||
"connection refused",
|
||||
"connection reset",
|
||||
"no route to host",
|
||||
"network is unreachable",
|
||||
"broken pipe",
|
||||
"connection closed",
|
||||
"eof",
|
||||
"no such host",
|
||||
"dial tcp",
|
||||
"dial udp",
|
||||
}
|
||||
|
||||
for _, connErr := range connectionErrors {
|
||||
for _, connErr := range connectionErrorSubstrings {
|
||||
if strings.Contains(errStr, connErr) {
|
||||
return true
|
||||
}
|
||||
@@ -648,9 +672,12 @@ func isTimeoutError(err error) bool {
|
||||
return false
|
||||
}
|
||||
errStr := strings.ToLower(err.Error())
|
||||
return strings.Contains(errStr, "timeout") ||
|
||||
strings.Contains(errStr, "deadline exceeded") ||
|
||||
strings.Contains(errStr, "context deadline exceeded")
|
||||
for _, tErr := range timeoutErrorSubstrings {
|
||||
if strings.Contains(errStr, tErr) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isRetryableStatusCode determines if an HTTP status code should trigger a retry
|
||||
|
||||
Reference in New Issue
Block a user