Files
LocalAI/core/http/middleware/compress_test.go
mudler's LocalAI [bot] ff299df453 perf(http): gzip responses, cache hashed assets, bound the trace endpoints (#11056)
Three measured HTTP-layer regressions on a live deployment, fixed together
because they all shape the bytes on the wire.

1. No compression. The server sent no Content-Encoding regardless of what
   the client asked for, confirmed with curl straight at 127.0.0.1:8080 so
   it was not an ingress artefact. Adds gzip middleware, on by default and
   configurable via LOCALAI_DISABLE_HTTP_COMPRESSION and
   LOCALAI_HTTP_COMPRESSION_MIN_LENGTH (default 1024 bytes so tiny bodies
   are not wastefully wrapped). Streaming routes are skipped explicitly:
   an SSE Accept header, a WebSocket upgrade, and the completion / SSE /
   log-tail path prefixes, because whether a completion request streams is
   decided by the request body, which the middleware runs too early to see.
   Already-compressed formats (woff2, png, mp4, ...) are skipped too; gzip
   made those marginally larger. Measured over the embedded React build:
   JS+CSS 2815 KB raw to 808 KB gzipped (3.48x).

2. No cache headers on content-hashed assets. Vite hashes the filenames,
   so a given /assets/ URL can never change content, yet they shipped with
   no Cache-Control, ETag or Last-Modified, and the browser re-fetched the
   whole bundle on every navigation with no conditional request available.
   /assets/* now carries public, max-age=31536000, immutable. index.html
   stays no-cache so a deploy is picked up, and the unhashed locale JSONs
   get a short TTL rather than the immutable one.

3. Unbounded trace endpoints. /api/traces returned 21,033,606 bytes in
   4.65s and /api/backend-traces 3,471,682 bytes in 1.50s, and the admin
   UI polls both every few seconds. The ring buffer holds up to 1024
   entries, each embedding full input_text payloads. Both list endpoints
   now take limit / offset / full, default to 50 entries, and strip the
   heavy fields (request and response bodies plus headers for API traces,
   body and data for backend traces) unless full=true. Every trace gets a
   process-lifetime ID and GET /api/traces/{id} and
   /api/backend-traces/{id} serve the full record, which is what the UI
   fetches when a row is expanded. The list body stays a JSON array;
   paging metadata rides in X-Total-Count, X-Trace-Offset and
   X-Trace-Limit. Reproducing the live shape in a test, the polled payload
   goes from 21,131,097 bytes to 7,201 bytes.


Assisted-by: Claude:claude-opus-4-8 [Claude Code]

Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
2026-07-22 22:51:25 +02:00

117 lines
3.4 KiB
Go

package middleware_test
import (
"bytes"
"compress/gzip"
"io"
"net/http"
"net/http/httptest"
"strings"
"github.com/labstack/echo/v4"
"github.com/mudler/LocalAI/core/http/middleware"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Compression middleware", func() {
var e *echo.Echo
// A payload comfortably above the minimum-length threshold and highly
// repetitive, so a real gzip pass shrinks it dramatically.
body := strings.Repeat("localai compresses this json payload. ", 400)
BeforeEach(func() {
e = echo.New()
e.Use(middleware.Compression(middleware.DefaultCompressionMinLength))
handler := func(c echo.Context) error {
return c.String(http.StatusOK, body)
}
e.GET("/assets/bundle.js", handler)
e.GET("/api/traces", handler)
e.GET("/v1/chat/completions", handler)
e.GET("/api/agents/demo/sse", handler)
e.GET("/api/tiny", func(c echo.Context) error {
return c.String(http.StatusOK, "ok")
})
e.GET("/assets/font.woff2", handler)
})
get := func(path string, headers map[string]string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Header.Set("Accept-Encoding", "gzip")
for k, v := range headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
return rec
}
It("gzips a compressible static asset response", func() {
rec := get("/assets/bundle.js", nil)
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(rec.Header().Get("Content-Encoding")).To(Equal("gzip"))
Expect(rec.Body.Len()).To(BeNumerically("<", len(body)/2))
zr, err := gzip.NewReader(bytes.NewReader(rec.Body.Bytes()))
Expect(err).ToNot(HaveOccurred())
decoded, err := io.ReadAll(zr)
Expect(err).ToNot(HaveOccurred())
Expect(string(decoded)).To(Equal(body))
})
It("gzips JSON API responses", func() {
rec := get("/api/traces", nil)
Expect(rec.Header().Get("Content-Encoding")).To(Equal("gzip"))
Expect(rec.Body.Len()).To(BeNumerically("<", len(body)))
})
It("does not compress streaming completion endpoints", func() {
rec := get("/v1/chat/completions", nil)
Expect(rec.Code).To(Equal(http.StatusOK))
Expect(rec.Header().Get("Content-Encoding")).To(BeEmpty())
Expect(rec.Body.String()).To(Equal(body))
})
It("does not compress SSE bridges", func() {
rec := get("/api/agents/demo/sse", nil)
Expect(rec.Header().Get("Content-Encoding")).To(BeEmpty())
Expect(rec.Body.String()).To(Equal(body))
})
It("does not compress a request that asks for an event stream", func() {
rec := get("/api/traces", map[string]string{"Accept": "text/event-stream"})
Expect(rec.Header().Get("Content-Encoding")).To(BeEmpty())
Expect(rec.Body.String()).To(Equal(body))
})
It("does not compress responses below the minimum length", func() {
rec := get("/api/tiny", nil)
Expect(rec.Header().Get("Content-Encoding")).To(BeEmpty())
Expect(rec.Body.String()).To(Equal("ok"))
})
It("does not re-compress formats that are already compressed", func() {
rec := get("/assets/font.woff2", nil)
Expect(rec.Header().Get("Content-Encoding")).To(BeEmpty())
Expect(rec.Body.String()).To(Equal(body))
})
It("leaves the body untouched when the client does not accept gzip", func() {
req := httptest.NewRequest(http.MethodGet, "/assets/bundle.js", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
Expect(rec.Header().Get("Content-Encoding")).To(BeEmpty())
Expect(rec.Body.String()).To(Equal(body))
})
})