Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Compress API responses for clients that accept gzip

rcourtman205df735c7b3
diff --git a/pkg/server/gzip_middleware.go b/pkg/server/gzip_middleware.go
new file mode 100644
index 0000000000..a800a08539
--- /dev/null
+++ b/pkg/server/gzip_middleware.go
@@ -0,0 +1,178 @@
+package server
+
+import (
+ "compress/gzip"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+ "sync"
+)
+
+// gzipMinContentLength skips compression for responses that declare a body
+// too small for gzip to pay for its own header and CPU cost. Responses with
+// no declared Content-Length (e.g. streamed JSON) are still compressed.
+const gzipMinContentLength = 1024
+
+var gzipWriterPool = sync.Pool{
+ New: func() any {
+ // BestSpeed keeps CPU cost low on multi-megabyte state payloads while
+ // still collapsing repetitive monitoring JSON by roughly an order of
+ // magnitude.
+ gw, _ := gzip.NewWriterLevel(io.Discard, gzip.BestSpeed)
+ return gw
+ },
+}
+
+// gzipCompressibleContentTypes lists the response types worth compressing.
+// Everything else (images, fonts, event streams, already-compressed archives)
+// passes through untouched. text/event-stream is deliberately absent: SSE
+// responses flush per event and must not be re-buffered by a compressor.
+var gzipCompressibleContentTypes = []string{
+ "application/json",
+ "application/javascript",
+ "text/javascript",
+ "text/html",
+ "text/css",
+ "text/plain",
+ "image/svg+xml",
+}
+
+// withGzip compresses eligible responses for clients that advertise gzip
+// support. WebSocket upgrades and Range requests bypass the wrapper entirely
+// 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") {
+ next.ServeHTTP(w, r)
+ return
+ }
+ if !acceptsGzip(r) || r.Header.Get("Range") != "" {
+ // Both variants must carry Vary so a shared cache never serves a
+ // compressed body to a client that cannot decode it.
+ w.Header().Add("Vary", "Accept-Encoding")
+ next.ServeHTTP(w, r)
+ return
+ }
+
+ gw := &gzipResponseWriter{ResponseWriter: w}
+ defer gw.close()
+ next.ServeHTTP(gw, r)
+ })
+}
+
+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
+ }
+ encoding = encoding[:idx]
+ }
+ if strings.EqualFold(strings.TrimSpace(encoding), "gzip") {
+ return true
+ }
+ }
+ return false
+}
+
+// gzipResponseWriter defers the compress-or-not decision to the first write,
+// when the handler has set its response headers. It implements http.Flusher
+// (SSE and other streaming handlers rely on it) and exposes Unwrap for
+// http.ResponseController.
+type gzipResponseWriter struct {
+ http.ResponseWriter
+ gz *gzip.Writer
+ compressing bool
+ decided bool
+}
+
+func (w *gzipResponseWriter) decide(status int) {
+ if w.decided {
+ return
+ }
+ w.decided = true
+
+ header := w.Header()
+ header.Add("Vary", "Accept-Encoding")
+
+ if status == http.StatusNoContent || status == http.StatusNotModified {
+ return
+ }
+ if header.Get("Content-Encoding") != "" {
+ return
+ }
+ if lengthValue := header.Get("Content-Length"); lengthValue != "" {
+ if length, err := strconv.ParseInt(lengthValue, 10, 64); err == nil && length < gzipMinContentLength {
+ return
+ }
+ }
+ contentType := header.Get("Content-Type")
+ if idx := strings.IndexByte(contentType, ';'); idx >= 0 {
+ contentType = contentType[:idx]
+ }
+ contentType = strings.ToLower(strings.TrimSpace(contentType))
+ compressible := false
+ for _, candidate := range gzipCompressibleContentTypes {
+ if contentType == candidate {
+ compressible = true
+ break
+ }
+ }
+ if !compressible {
+ return
+ }
+
+ // The compressed size is unknown, so any declared length is stale.
+ header.Del("Content-Length")
+ header.Set("Content-Encoding", "gzip")
+ w.compressing = true
+}
+
+func (w *gzipResponseWriter) WriteHeader(status int) {
+ w.decide(status)
+ w.ResponseWriter.WriteHeader(status)
+}
+
+func (w *gzipResponseWriter) Write(data []byte) (int, error) {
+ if !w.decided {
+ w.decide(http.StatusOK)
+ }
+ if !w.compressing {
+ return w.ResponseWriter.Write(data)
+ }
+ if w.gz == nil {
+ gz := gzipWriterPool.Get().(*gzip.Writer)
+ gz.Reset(w.ResponseWriter)
+ w.gz = gz
+ }
+ return w.gz.Write(data)
+}
+
+func (w *gzipResponseWriter) Flush() {
+ if w.gz != nil {
+ if err := w.gz.Flush(); err != nil {
+ return
+ }
+ }
+ if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
+ flusher.Flush()
+ }
+}
+
+func (w *gzipResponseWriter) Unwrap() http.ResponseWriter {
+ return w.ResponseWriter
+}
+
+func (w *gzipResponseWriter) close() {
+ if w.gz == nil {
+ return
+ }
+ _ = w.gz.Close()
+ w.gz.Reset(io.Discard)
+ gzipWriterPool.Put(w.gz)
+ w.gz = nil
+}
diff --git a/pkg/server/gzip_middleware_test.go b/pkg/server/gzip_middleware_test.go
new file mode 100644
index 0000000000..6def93aafe
--- /dev/null
+++ b/pkg/server/gzip_middleware_test.go
@@ -0,0 +1,213 @@
+package server
+
+import (
+ "compress/gzip"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+func gunzipBody(t *testing.T, body io.Reader) string {
+ t.Helper()
+ reader, err := gzip.NewReader(body)
+ if err != nil {
+ t.Fatalf("gzip.NewReader: %v", err)
+ }
+ defer reader.Close()
+ decoded, err := io.ReadAll(reader)
+ if err != nil {
+ t.Fatalf("read gzip body: %v", err)
+ }
+ return string(decoded)
+}
+
+func TestWithGzipCompressesJSONForAcceptingClients(t *testing.T) {
+ payload := `{"resources":[` + strings.Repeat(`{"id":"vm-1","cpu":0.5},`, 200) + `{"id":"vm-last"}]}`
+ handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(payload))
+ }))
+
+ 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 got := rec.Header().Get("Vary"); !strings.Contains(got, "Accept-Encoding") {
+ t.Fatalf("Vary = %q, want Accept-Encoding", got)
+ }
+ if rec.Body.Len() >= len(payload) {
+ t.Fatalf("compressed body (%d bytes) not smaller than payload (%d bytes)", rec.Body.Len(), len(payload))
+ }
+ if decoded := gunzipBody(t, rec.Body); decoded != payload {
+ t.Fatalf("decompressed body does not match payload")
+ }
+}
+
+func TestWithGzipPassesThroughWithoutAcceptEncoding(t *testing.T) {
+ payload := strings.Repeat("plain body ", 500)
+ handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(payload))
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/api/state", nil)
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+
+ if got := rec.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("Content-Encoding = %q, want empty", got)
+ }
+ if got := rec.Header().Get("Vary"); !strings.Contains(got, "Accept-Encoding") {
+ t.Fatalf("Vary = %q, want Accept-Encoding on the identity variant too", got)
+ }
+ if rec.Body.String() != payload {
+ t.Fatalf("body was modified without client opt-in")
+ }
+}
+
+func TestWithGzipRespectsZeroQualityOptOut(t *testing.T) {
+ handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(strings.Repeat("x", 4096)))
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/api/state", nil)
+ req.Header.Set("Accept-Encoding", "gzip;q=0")
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+
+ if got := rec.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("Content-Encoding = %q, want empty for q=0 opt-out", got)
+ }
+}
+
+func TestWithGzipSkipsEventStreams(t *testing.T) {
+ handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ _, _ = w.Write([]byte("data: {\"tick\":1}\n\n"))
+ if _, ok := w.(http.Flusher); !ok {
+ t.Errorf("wrapped writer does not implement http.Flusher")
+ }
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/api/ai/chat/stream", nil)
+ req.Header.Set("Accept-Encoding", "gzip")
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+
+ if got := rec.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("Content-Encoding = %q, want empty for SSE", got)
+ }
+ if !strings.HasPrefix(rec.Body.String(), "data:") {
+ t.Fatalf("SSE body altered: %q", rec.Body.String())
+ }
+}
+
+func TestWithGzipSkipsWebSocketUpgrades(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, "/ws", nil)
+ req.Header.Set("Accept-Encoding", "gzip")
+ req.Header.Set("Connection", "Upgrade")
+ req.Header.Set("Upgrade", "websocket")
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+
+ if sawWrappedWriter {
+ t.Fatalf("websocket upgrade request received the gzip wrapper; hijacking would fail")
+ }
+}
+
+func TestWithGzipSkipsSmallDeclaredBodies(t *testing.T) {
+ payload := `{"status":"ok"}`
+ handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Length", "15")
+ _, _ = w.Write([]byte(payload))
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/api/health", nil)
+ req.Header.Set("Accept-Encoding", "gzip")
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+
+ if got := rec.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("Content-Encoding = %q, want empty for tiny declared body", got)
+ }
+ if rec.Body.String() != payload {
+ t.Fatalf("small body altered: %q", rec.Body.String())
+ }
+}
+
+func TestWithGzipSkipsNonCompressibleContentTypes(t *testing.T) {
+ handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "image/png")
+ _, _ = w.Write([]byte(strings.Repeat("binary", 1024)))
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/logo.png", nil)
+ req.Header.Set("Accept-Encoding", "gzip")
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+
+ if got := rec.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("Content-Encoding = %q, want empty for image/png", got)
+ }
+}
+
+func TestWithGzipPreservesStatusAndEmptyBodies(t *testing.T) {
+ handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusNoContent)
+ }))
+
+ req := httptest.NewRequest(http.MethodDelete, "/api/thing", nil)
+ req.Header.Set("Accept-Encoding", "gzip")
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusNoContent {
+ t.Fatalf("status = %d, want 204", rec.Code)
+ }
+ if got := rec.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("Content-Encoding = %q, want empty for 204", got)
+ }
+ if rec.Body.Len() != 0 {
+ t.Fatalf("204 grew a %d-byte body", rec.Body.Len())
+ }
+}
+
+func TestWithGzipDropsStaleContentLengthWhenCompressing(t *testing.T) {
+ payload := strings.Repeat(`{"k":"v"}`, 1024)
+ handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Length", strconv.Itoa(len(payload)))
+ _, _ = w.Write([]byte(payload))
+ }))
+
+ 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 got := rec.Header().Get("Content-Length"); got != "" {
+ t.Fatalf("stale Content-Length %q survived compression", got)
+ }
+ if decoded := gunzipBody(t, rec.Body); decoded != payload {
+ t.Fatalf("decompressed body does not match payload")
+ }
+}
diff --git a/pkg/server/server.go b/pkg/server/server.go
index 75051b64ad..2269670347 100644
--- a/pkg/server/server.go
+++ b/pkg/server/server.go
@@ -656,7 +656,7 @@ func Run(ctx context.Context, version string) error {
// Create HTTP server with unified configuration
srv := &http.Server{
Addr: mainAddr,
- Handler: router.Handler(),
+ Handler: withGzip(router.Handler()),
ReadHeaderTimeout: 15 * time.Second,
WriteTimeout: 0, // Disabled to support SSE/streaming
IdleTimeout: 120 * time.Second,