Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Harden large-estate response and polling limits
rcourtmana682af0b7b49
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 9b584e3fc9..079b8c93d4 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -2564,6 +2564,13 @@ Agent` secondary handoff against the live setup wizard instead of relying## Current State+### Monitoring task limits do not change lifecycle authority++The monitoring-owned process-wide scheduled-task limiter may bound host and+availability-agent poll execution across tenants. It does not change lifecycle+journal hydration, report admission, token binding, removal tombstones, or+re-enrollment authority in `internal/monitoring/monitor.go`.+### Retained Patrol objectives do not expand agent lifecycle authorityThe shared `internal/api` retained-objective endpoints can queue read-onlydiff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex a9ee5a9627..8f23acdbb9 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -677,6 +677,15 @@ cleanup so readers cannot retain orphaned runtime or alert projections.lazy current-state broadcast path and let the hub resolve tenant-awarefrontend state after coalescing; monitor callsites must not build or retainfull frontend-state snapshots for supersedable broadcast signals.+ Mock mode is the narrow exception to the no-subscriber fast path:+ `GetState()` owns lazy fixture alert-snapshot initialization, so the ticker+ must preserve that maintenance call before its subscriber early-exit while+ production monitors continue to skip the snapshot build.+ `POLL_TASK_WORKERS` is a process-wide scheduled-task concurrency ceiling,+ not a per-monitor pool size. Each monitor may own one queue dispatcher, but+ all dispatchers must acquire the shared bounded limiter before executing a+ task so tenant creation and monitor reload cannot multiply the configured+ value into independent worker herds.14. Add or change Proxmox-side LXC Docker detection or inventory through`internal/monitoring/docker_detection.go`,`internal/monitoring/monitor_pve_guest_poll.go`,@@ -1056,6 +1065,15 @@ cleanup so readers cannot retain orphaned runtime or alert projections.## Current State+### Poll task concurrency remains bounded across tenants++Without an override, each monitor retains the established client-derived+worker clamp of one through ten. With `POLL_TASK_WORKERS`, monitor queues use+one dispatcher apiece and share a single process limiter capped at 128 active+tasks. A large tenant count therefore adds only one blocked dispatcher per+monitor rather than another full override-sized goroutine pool, while a single+large tenant can still fill the configured I/O concurrency budget.+### Large Proxmox generations preserve reachability under bounded enrichmentThe efficient PVE poll reserves a fixed tail of the scheduler deadline anddiff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 788f2d7d07..1d0843c7a9 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -142,6 +142,8 @@ start a goroutine, timer, or notification lifecycle per target.108. `frontend-modern/src/utils/__tests__/workloads.test.ts`109. `frontend-modern/src/utils/searchQuery.ts`110. `frontend-modern/src/utils/__tests__/searchQuery.test.ts`+111. `pkg/server/gzip_middleware.go`+112. `pkg/server/gzip_middleware_test.go`## Shared Boundaries@@ -196,6 +198,13 @@ change may globally weaken the Task 03 lifecycle-state idempotency invariant.1. Add performance budgets through SLO or contract tests2. Add query-plan guardrails for DB-backed hot paths3. Optimize hot paths only when backed by benchmarks or proven query issues+ Main-listener response compression belongs to+ `pkg/server/gzip_middleware.go`. Negotiation must combine every+ `Accept-Encoding` field line, honor strict RFC qvalues and explicit gzip+ exclusions, and bypass token-valid WebSocket upgrades before wrapping the+ response writer. Once a successful response advertises gzip, explicit+ empty bodies must still emit a valid empty gzip member. Regression proof+ lives in `pkg/server/gzip_middleware_test.go`.WebSocket state refreshes on monitor, agent-report, and alert mutation hotpaths must enqueue coalesced current-state invalidations instead of buildingfull frontend-state payloads at every signal. The hub owns delayed@@ -997,6 +1006,17 @@ without contention or cross-delivery.## Current State+### Large API responses negotiate gzip without corrupting edge cases++The main listener compresses eligible JSON and frontend text assets for+clients that accept gzip. Negotiation combines repeated header fields,+supports wildcard acceptance, applies strict three-digit qvalue parsing, and+lets explicit gzip exclusions override wildcards. WebSocket token lists and+range requests bypass the wrapper. Explicit empty 200 responses carry a valid+empty gzip stream whenever `Content-Encoding: gzip` is committed, while+204/304, SSE, already encoded, small declared, and binary responses stay on+their identity paths.+### Libvirt workload projection stays bounded and allocation-localThe Linux host collector performs one domain-list call and one bulk `domstats`diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex 282bb50f73..238cd930b1 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -6396,7 +6396,8 @@"frontend-modern/src/utils/workloadsSummaryCache.ts","internal/api/router_bench_test.go","internal/api/slo.go",- "internal/api/slo_bench_test.go"+ "internal/api/slo_bench_test.go",+ "pkg/server/gzip_middleware.go"],"verification": {"allow_same_subsystem_tests": false,@@ -6430,10 +6431,24 @@"internal/api/slo_bench_test.go","pkg/metrics/store_bench_test.go","pkg/metrics/store_query_plan_test.go",- "pkg/metrics/store_slo_test.go"+ "pkg/metrics/store_slo_test.go",+ "pkg/server/gzip_middleware_test.go"],"require_explicit_path_policy_coverage": true,"path_policies": [+ {+ "id": "main-listener-response-compression",+ "label": "main-listener response compression proof",+ "match_prefixes": [],+ "match_files": [+ "pkg/server/gzip_middleware.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "pkg/server/gzip_middleware_test.go"+ ]+ },{"id": "metrics-store-hot-paths","label": "metrics store hot-path proof",diff --git a/internal/monitoring/availability_probe_agent_test.go b/internal/monitoring/availability_probe_agent_test.goindex aef4f4aa19..7c277abe18 100644--- a/internal/monitoring/availability_probe_agent_test.go+++ b/internal/monitoring/availability_probe_agent_test.go@@ -1,6 +1,8 @@package monitoringimport (+ "context"+ "sync""testing""time"@@ -13,6 +15,48 @@ import ("github.com/rcourtman/pulse-go-rewrite/pkg/tlsutil")+func TestPollTaskWorkerLimiterCapsAvailabilityAgentWorkAcrossTenants(t *testing.T) {+ const (+ limit = 4+ tenants = 12+ )+ limiter := newPollTaskWorkerLimiter(limit)+ ctx := context.Background()+ entered := make(chan int, tenants)+ release := make(chan struct{})++ var wg sync.WaitGroup+ for tenant := 0; tenant < tenants; tenant++ {+ wg.Add(1)+ go func(tenant int) {+ defer wg.Done()+ if !limiter.acquire(ctx) {+ t.Errorf("tenant %d failed to acquire limiter", tenant)+ return+ }+ defer limiter.release()+ entered <- tenant+ <-release+ }(tenant)+ }++ for i := 0; i < limit; i++ {+ select {+ case <-entered:+ case <-time.After(time.Second):+ t.Fatalf("only %d of %d process-wide slots became available", i, limit)+ }+ }+ select {+ case tenant := <-entered:+ t.Fatalf("tenant %d exceeded the process-wide limit of %d", tenant, limit)+ case <-time.After(25 * time.Millisecond):+ }++ close(release)+ wg.Wait()+}+func newProbeAgentTestMonitor(t *testing.T, targets ...config.AvailabilityTarget) *Monitor {t.Helper()persistence := config.NewConfigPersistence(t.TempDir())diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex 1e1724ebcb..f606b98f2a 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -1368,6 +1368,22 @@ func TestMonitoringRuntimeAvoidsLegacyMockPartialHelpers(t *testing.T) {}}+func TestBroadcastTickerRefreshesMockAlertsBeforeSubscriberEarlyExit(t *testing.T) {+ data, err := os.ReadFile("monitor.go")+ if err != nil {+ t.Fatalf("read monitor.go: %v", err)+ }+ source := string(data)+ mockRefresh := strings.Index(source, "if mock.IsMockEnabled() {\n\t\t\t\t_ = m.GetState()")+ subscriberGate := strings.Index(source, "if !currentStateBroadcasterHasSubscribers(wsHub, m.GetOrgID())")+ if mockRefresh < 0 {+ t.Fatal("broadcast ticker must preserve GetState's lazy mock alert snapshot refresh")+ }+ if subscriberGate < 0 || mockRefresh > subscriberGate {+ t.Fatal("mock alert snapshot refresh must run before the no-subscriber early exit")+ }+}+func TestMockOwnedUnifiedMetricSyncDefersToCanonicalSamplerInMockMode(t *testing.T) {previous := mock.IsMockEnabled()mustSetMockEnabled(t, true)diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 5fe7988e50..aed225a92c 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -2046,6 +2046,12 @@ func (m *Monitor) Start(ctx context.Context, wsHub *websocket.Hub) {case <-broadcastTicker.C:// Broadcast current state regardless of polling status+ // GetState lazily initializes the mock alert snapshot. Preserve that+ // fixture maintenance even when no browser is subscribed; production+ // monitors still avoid the full snapshot build on this fast path.+ if mock.IsMockEnabled() {+ _ = m.GetState()+ }if !currentStateBroadcasterHasSubscribers(wsHub, m.GetOrgID()) {continue}@@ -2129,26 +2135,78 @@ func (m *Monitor) startTaskWorkers(ctx context.Context, workers int) {if m.taskQueue == nil {return}+ if limiter := processPollTaskWorkerLimiter(); limiter != nil {+ // A monitor owns one dispatcher, while the process-wide limiter owns+ // actual task concurrency. This prevents the override from multiplying+ // into a full worker pool for every tenant.+ go m.dispatchTaskWorkers(ctx, limiter)+ return+ }workers = resolveTaskWorkerCount(workers)for i := 0; i < workers; i++ {go m.taskWorker(ctx, i)}}-// resolveTaskWorkerCount applies the default clamp of [1, 10] to the-// client-derived worker count. POLL_TASK_WORKERS overrides both the count and-// the cap for estates whose instance count outgrows the default pool; the-// override is bounded at 128 so a typo cannot fork an unbounded goroutine-// herd against the monitored APIs. Workers are I/O-bound, so the override-// spends sockets against monitored hosts, not local CPU.-func resolveTaskWorkerCount(workers int) int {- if override := parseNonNegativeIntEnv("POLL_TASK_WORKERS", 0); override > 0 {- if override > 128 {- override = 128+const maxPollTaskWorkers = 128++type pollTaskWorkerLimiter struct {+ slots chan struct{}+}++func newPollTaskWorkerLimiter(limit int) *pollTaskWorkerLimiter {+ if limit < 1 {+ limit = 1+ }+ return &pollTaskWorkerLimiter{slots: make(chan struct{}, limit)}+}++func (l *pollTaskWorkerLimiter) acquire(ctx context.Context) bool {+ select {+ case l.slots <- struct{}{}:+ return true+ case <-ctx.Done():+ return false+ }+}++func (l *pollTaskWorkerLimiter) release() {+ <-l.slots+}++var (+ processPollTaskWorkerLimiterOnce sync.Once+ processPollTaskWorkerLimit *pollTaskWorkerLimiter+)++func processPollTaskWorkerLimiter() *pollTaskWorkerLimiter {+ processPollTaskWorkerLimiterOnce.Do(func() {+ override := pollTaskWorkerOverride()+ if override == 0 {+ return}+ processPollTaskWorkerLimit = newPollTaskWorkerLimiter(override)log.Info().Int("workers", override).- Msg("Poll task worker count overridden by POLL_TASK_WORKERS")+ Msg("Poll task worker count overridden process-wide by POLL_TASK_WORKERS")+ })+ return processPollTaskWorkerLimit+}++func pollTaskWorkerOverride() int {+ override := parseNonNegativeIntEnv("POLL_TASK_WORKERS", 0)+ if override > maxPollTaskWorkers {+ return maxPollTaskWorkers+ }+ return override+}++// resolveTaskWorkerCount applies the default clamp of [1, 10] to the+// client-derived worker count. POLL_TASK_WORKERS is reported here for+// diagnostics and tests; startTaskWorkers routes that override through the+// process-wide limiter instead of starting this many workers per monitor.+func resolveTaskWorkerCount(workers int) int {+ if override := pollTaskWorkerOverride(); override > 0 {return override}if workers < 1 {@@ -2160,6 +2218,26 @@ func resolveTaskWorkerCount(workers int) int {return workers}+func (m *Monitor) dispatchTaskWorkers(ctx context.Context, limiter *pollTaskWorkerLimiter) {+ defer recoverFromPanic("taskWorkerDispatcher")++ for {+ task, ok := m.taskQueue.WaitNext(ctx)+ if !ok {+ return+ }+ if !limiter.acquire(ctx) {+ return+ }++ go func() {+ defer limiter.release()+ defer recoverFromPanic(fmt.Sprintf("taskWorker-%s-%s", task.InstanceType, task.InstanceName))+ m.executeAndRescheduleTask(ctx, task)+ }()+ }+}+func (m *Monitor) taskWorker(ctx context.Context, id int) {defer recoverFromPanic(fmt.Sprintf("taskWorker-%d", id))@@ -2175,13 +2253,16 @@ func (m *Monitor) taskWorker(ctx context.Context, id int) {return}- m.executeScheduledTask(ctx, task)-- m.rescheduleTask(task)- m.updateQueueDepthMetric()+ m.executeAndRescheduleTask(ctx, task)}}+func (m *Monitor) executeAndRescheduleTask(ctx context.Context, task ScheduledTask) {+ m.executeScheduledTask(ctx, task)+ m.rescheduleTask(task)+ m.updateQueueDepthMetric()+}+func derivePollTimeout(cfg *config.Config) time.Duration {timeout := defaultTaskTimeoutif cfg != nil && cfg.ConnectionTimeout > 0 {diff --git a/pkg/server/gzip_middleware.go b/pkg/server/gzip_middleware.goindex 4f7591704a..f4d31cf276 100644--- a/pkg/server/gzip_middleware.go+++ b/pkg/server/gzip_middleware.go@@ -7,6 +7,8 @@ import ("strconv""strings""sync"++ "github.com/gorilla/websocket")// gzipMinContentLength skips compression for responses that declare a body@@ -43,7 +45,7 @@ var gzipCompressibleContentTypes = []string{// so hijacking and byte-range semantics keep working on the original writer.func withGzip(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {+ if websocket.IsWebSocketUpgrade(r) {next.ServeHTTP(w, r)return}@@ -62,21 +64,97 @@ func withGzip(next http.Handler) http.Handler {}func acceptsGzip(r *http.Request) bool {- for _, part := range strings.Split(r.Header.Get("Accept-Encoding"), ",") {- encoding := part- if idx := strings.IndexByte(encoding, ';'); idx >= 0 {- // A quality value of 0 opts the encoding out.- params := strings.TrimSpace(encoding[idx+1:])- if strings.HasPrefix(params, "q=0") && !strings.HasPrefix(params, "q=0.") {- continue+ values := r.Header.Values("Accept-Encoding")+ if len(values) == 0 {+ return false+ }++ gzipQuality := -1+ wildcardQuality := -1+ for _, value := range values {+ for _, part := range strings.Split(value, ",") {+ encoding, quality := parseAcceptedEncoding(part)+ switch encoding {+ case "gzip":+ if quality > gzipQuality {+ gzipQuality = quality+ }+ case "*":+ if quality > wildcardQuality {+ wildcardQuality = quality+ }+ }+ }+ }++ // An explicit gzip entry overrides the wildcard, including q=0.+ if gzipQuality >= 0 {+ return gzipQuality > 0+ }+ return wildcardQuality > 0+}++// parseAcceptedEncoding returns the normalized content-coding and a quality+// value in thousandths. Invalid qvalues make that entry unacceptable. RFC+// 9110 permits at most three fractional digits and only zeroes after 1.+func parseAcceptedEncoding(part string) (string, int) {+ segments := strings.Split(part, ";")+ encoding := strings.ToLower(strings.TrimSpace(segments[0]))+ if encoding == "" {+ return "", 0+ }++ quality := 1000+ sawQuality := false+ for _, parameter := range segments[1:] {+ name, value, found := strings.Cut(parameter, "=")+ if !strings.EqualFold(strings.TrimSpace(name), "q") {+ continue+ }+ if !found || sawQuality {+ return encoding, 0+ }+ sawQuality = true+ parsed, ok := parseQualityValue(strings.TrimSpace(value))+ if !ok {+ return encoding, 0+ }+ quality = parsed+ }+ return encoding, quality+}++func parseQualityValue(value string) (int, bool) {+ whole, fraction, hasFraction := strings.Cut(value, ".")+ if len(fraction) > 3 {+ return 0, false+ }+ if hasFraction {+ for _, digit := range fraction {+ if digit < '0' || digit > '9' {+ return 0, false}- encoding = encoding[:idx]}- if strings.EqualFold(strings.TrimSpace(encoding), "gzip") {- return true+ }++ switch whole {+ case "0":+ for len(fraction) < 3 {+ fraction += "0"+ }+ if fraction == "" {+ return 0, true}+ quality, err := strconv.Atoi(fraction)+ return quality, err == nil+ case "1":+ if strings.Trim(fraction, "0") != "" {+ return 0, false+ }+ return 1000, true+ default:+ return 0, false}- return false}// gzipResponseWriter defers the compress-or-not decision to the first write,@@ -144,11 +222,7 @@ func (w *gzipResponseWriter) Write(data []byte) (int, error) {if !w.compressing {return w.ResponseWriter.Write(data)}- if w.gz == nil {- gz := gzipWriterPool.Get().(*gzip.Writer)- gz.Reset(w.ResponseWriter)- w.gz = gz- }+ w.ensureGzipWriter()return w.gz.Write(data)}@@ -161,9 +235,7 @@ func (w *gzipResponseWriter) Flush() {w.decide(http.StatusOK)}if w.compressing && w.gz == nil {- gz := gzipWriterPool.Get().(*gzip.Writer)- gz.Reset(w.ResponseWriter)- w.gz = gz+ w.ensureGzipWriter()}if w.gz != nil {if err := w.gz.Flush(); err != nil {@@ -179,7 +251,21 @@ func (w *gzipResponseWriter) Unwrap() http.ResponseWriter {return w.ResponseWriter}+func (w *gzipResponseWriter) ensureGzipWriter() {+ if w.gz != nil {+ return+ }+ gz := gzipWriterPool.Get().(*gzip.Writer)+ gz.Reset(w.ResponseWriter)+ w.gz = gz+}+func (w *gzipResponseWriter) close() {+ // WriteHeader may select gzip without a subsequent Write. Emit a complete+ // empty gzip member so Content-Encoding never describes an absent stream.+ if w.compressing && w.gz == nil {+ w.ensureGzipWriter()+ }if w.gz == nil {return}diff --git a/pkg/server/gzip_middleware_test.go b/pkg/server/gzip_middleware_test.goindex f56583e1fa..4e6c5d8d1c 100644--- a/pkg/server/gzip_middleware_test.go+++ b/pkg/server/gzip_middleware_test.go@@ -1,13 +1,19 @@package serverimport (+ "bufio""compress/gzip"+ "fmt""io"+ "net""net/http""net/http/httptest""strconv""strings""testing"++ "github.com/gorilla/websocket"+ "github.com/rcourtman/pulse-go-rewrite/internal/api")func gunzipBody(t *testing.T, body io.Reader) string {@@ -88,6 +94,36 @@ func TestWithGzipRespectsZeroQualityOptOut(t *testing.T) {}}+func TestAcceptsGzipNegotiatesAllHeaderValuesAndStrictQvalues(t *testing.T) {+ tests := []struct {+ name string+ values []string+ want bool+ }{+ {name: "zero with three fractional digits", values: []string{"gzip;q=0.000"}, want: false},+ {name: "case insensitive zero", values: []string{"gzip; Q = 0"}, want: false},+ {name: "positive fractional quality", values: []string{"br, gzip; q=0.001"}, want: true},+ {name: "wildcard permits gzip", values: []string{"identity;q=0, *;q=1"}, want: true},+ {name: "explicit gzip exclusion beats wildcard", values: []string{"*;q=1, gzip;q=0"}, want: false},+ {name: "second header line permits gzip", values: []string{"identity;q=0", "gzip"}, want: true},+ {name: "identity only", values: []string{"identity"}, want: false},+ {name: "invalid precision", values: []string{"gzip;q=0.0000"}, want: false},+ {name: "invalid value above one", values: []string{"gzip;q=1.001"}, want: false},+ {name: "missing quality value", values: []string{"gzip;q"}, want: false},+ {name: "duplicate quality parameter", values: []string{"gzip;q=0;q=1"}, want: false},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ req := httptest.NewRequest(http.MethodGet, "/api/state", nil)+ req.Header["Accept-Encoding"] = append([]string(nil), tc.values...)+ if got := acceptsGzip(req); got != tc.want {+ t.Fatalf("acceptsGzip() = %v, want %v for %q", got, tc.want, tc.values)+ }+ })+ }+}+func TestWithGzipSkipsEventStreams(t *testing.T) {handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "text/event-stream")@@ -129,6 +165,85 @@ func TestWithGzipSkipsWebSocketUpgrades(t *testing.T) {}}+func TestWithGzipSkipsTokenListWebSocketUpgrades(t *testing.T) {+ var sawWrappedWriter bool+ handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, sawWrappedWriter = w.(*gzipResponseWriter)+ w.WriteHeader(http.StatusSwitchingProtocols)+ }))++ req := httptest.NewRequest(http.MethodGet, "/api/agent/ws", nil)+ req.Header.Set("Accept-Encoding", "gzip")+ req.Header.Set("Connection", "keep-alive, Upgrade")+ req.Header.Set("Upgrade", "websocket, h2c")+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)++ if sawWrappedWriter {+ t.Fatalf("token-list websocket upgrade received the gzip wrapper; hijacking would fail")+ }+}++func TestWithGzipTokenListWebSocketHandshakeThroughAPIErrorHandler(t *testing.T) {+ upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}+ handler := withGzip(api.ErrorHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ conn, err := upgrader.Upgrade(w, r, nil)+ if err != nil {+ t.Errorf("websocket upgrade: %v", err)+ return+ }+ _ = conn.Close()+ })))+ server := httptest.NewServer(handler)+ defer server.Close()++ host := strings.TrimPrefix(server.URL, "http://")+ conn, err := net.Dial("tcp", host)+ if err != nil {+ t.Fatalf("dial test server: %v", err)+ }+ defer conn.Close()++ request, err := http.NewRequest(http.MethodGet, server.URL+"/api/agent/ws", nil)+ if err != nil {+ t.Fatalf("build request: %v", err)+ }+ if _, err := fmt.Fprintf(conn,+ "GET /api/agent/ws HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive, Upgrade\r\nUpgrade: websocket, h2c\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: MDEyMzQ1Njc4OWFiY2RlZg==\r\nAccept-Encoding: gzip\r\n\r\n",+ host,+ ); err != nil {+ t.Fatalf("write handshake: %v", err)+ }++ response, err := http.ReadResponse(bufio.NewReader(conn), request)+ if err != nil {+ t.Fatalf("read handshake: %v", err)+ }+ defer response.Body.Close()+ if response.StatusCode != http.StatusSwitchingProtocols {+ t.Fatalf("status = %d, want 101", response.StatusCode)+ }+}++func TestWithGzipExplicitEmpty200HasValidGzipBody(t *testing.T) {+ handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ }))++ req := httptest.NewRequest(http.MethodGet, "/api/state", nil)+ req.Header.Set("Accept-Encoding", "gzip")+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)++ if got := rec.Header().Get("Content-Encoding"); got != "gzip" {+ t.Fatalf("Content-Encoding = %q, want gzip", got)+ }+ if decoded := gunzipBody(t, rec.Body); decoded != "" {+ t.Fatalf("decoded empty response = %q, want empty", decoded)+ }+}+func TestWithGzipSkipsSmallDeclaredBodies(t *testing.T) {payload := `{"status":"ok"}`handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {