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:
2026-04-19 19:49:24 +01:00
parent 65fa936b60
commit c2c75d69c0
36 changed files with 4322 additions and 381 deletions
+34 -19
View File
@@ -52,13 +52,9 @@ func NewLRUMemoryCache(maxMemorySize, maxEntries int64) *LRUMemoryCache {
// Set adds or updates an entry in the cache
func (c *LRUMemoryCache) Set(key string, value []byte, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
// Calculate expiry time
expiresAt := time.Now().Add(ttl)
// Check if we should compress
// Compress OUTSIDE the lock — gzip is CPU-bound and pool ops are
// goroutine-safe. Result is just a byte slice, safe to hand to the
// critical section below.
compressed := false
finalValue := value
if len(value) > 1024 { // Compress if larger than 1KB
@@ -69,6 +65,10 @@ func (c *LRUMemoryCache) Set(key string, value []byte, ttl time.Duration) {
}
entrySize := int64(len(key) + len(finalValue) + 64) // 64 bytes overhead estimate
expiresAt := time.Now().Add(ttl)
c.mu.Lock()
defer c.mu.Unlock()
// Check if key exists
if existing, exists := c.entries[key]; exists {
@@ -107,34 +107,49 @@ func (c *LRUMemoryCache) Set(key string, value []byte, ttl time.Duration) {
// Get retrieves a value from the cache
func (c *LRUMemoryCache) Get(key string) ([]byte, bool) {
// Snapshot the stored bytes under the lock, then release before
// decompressing — gzip is CPU-bound and must not serialise other ops.
c.mu.Lock()
defer c.mu.Unlock()
entry, exists := c.entries[key]
if !exists {
c.mu.Unlock()
return nil, false
}
// Check if expired
// Check if expired (must use the entry's stored expiry while locked)
if time.Now().After(entry.expiresAt) {
c.removeEntry(entry)
c.mu.Unlock()
return nil, false
}
// Move to front (most recently used)
c.evictList.MoveToFront(entry.element)
// Decompress if needed
if entry.compressed {
if decompressed, err := c.decompress(entry.value); err == nil {
return decompressed, true
}
// If decompression fails, remove the entry
c.removeEntry(entry)
return nil, false
if !entry.compressed {
// Uncompressed payload is immutable once stored, safe to return directly.
value := entry.value
c.mu.Unlock()
return value, true
}
return entry.value, true
// Snapshot compressed bytes locally, drop lock, then decompress.
compressedBytes := entry.value
c.mu.Unlock()
decompressed, err := c.decompress(compressedBytes)
if err == nil {
return decompressed, true
}
// Decompression failed — re-acquire lock to remove the bad entry,
// but only if it still exists and still points at the same payload.
c.mu.Lock()
if cur, ok := c.entries[key]; ok && cur == entry {
c.removeEntry(cur)
}
c.mu.Unlock()
return nil, false
}
// Delete removes an entry from the cache