Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
* [BUGFIX] Ring: Fix `DoBatch` counting a key more than once when more replicas than the quorum succeed, which in rare cases could hide a write error from a key that did not reach quorum. A distributor push now always waits until every series reaches quorum, so it returns the error of a series that misses quorum, and takes as long as its slowest series to reach quorum. #7975
* [BUGFIX] Compactor: Stop downloading the parquet files and the `parquet-converter-mark.json` and `parquet-no-convert-mark.json` markers written by the parquet converter under a block's prefix. Compaction never reads them, so they only used local disk and bandwidth until the compaction job ended. #7972
* [BUGFIX] Ring: Fix shuffle-sharding subrings treating instances with a stale heartbeat as healthy when using the DynamoDB KV store. #7976
* [BUGFIX] Querier: Stop compressing query API error responses. Clients sending `Accept-Encoding`, such as the Go HTTP client which sends `gzip` by default, got compressed error responses, so the logged body of a failed query was an unreadable compressed blob. #7979

## 1.22.0 2026-11-19

Expand Down
63 changes: 45 additions & 18 deletions pkg/api/queryapi/compression.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,56 @@ const (
)

// Wrapper around http.Handler which adds suitable response compression based
// on the client's Accept-Encoding headers.
// on the client's Accept-Encoding headers. Error responses (status code 400 or
// above) are not compressed, so they stay readable wherever the response body
// is logged.
type compressedResponseWriter struct {
http.ResponseWriter
writer io.Writer
writer io.Writer
encoding string
wroteHeader bool
}

// Sends an HTTP response header with the provided status code, and enables
// the compression unless the response is an error.
func (c *compressedResponseWriter) WriteHeader(statusCode int) {
if !c.wroteHeader {
c.wroteHeader = true
if statusCode < http.StatusBadRequest {
c.startCompression()
}
}
c.ResponseWriter.WriteHeader(statusCode)
}

// Writes HTTP response content data.
func (c *compressedResponseWriter) Write(p []byte) (int, error) {
if !c.wroteHeader {
c.WriteHeader(http.StatusOK)
}
return c.writer.Write(p)
}

func (c *compressedResponseWriter) startCompression() {
switch c.encoding {
case zstdEncoding:
encoder, err := zstd.NewWriter(c.ResponseWriter)
if err != nil {
return
}
c.writer = encoder
case snappyEncoding:
c.writer = snappy.NewBufferedWriter(c.ResponseWriter)
case gzipEncoding:
c.writer = gzip.NewWriter(c.ResponseWriter)
case deflateEncoding:
c.writer = zlib.NewWriter(c.ResponseWriter)
default:
return
}
c.Header().Set(contentEncodingHeader, c.encoding)
}

// Closes the compressedResponseWriter and ensures to flush all data before.
func (c *compressedResponseWriter) Close() {
if zstdWriter, ok := c.writer.(*zstd.Encoder); ok {
Expand All @@ -52,25 +91,13 @@ func (c *compressedResponseWriter) Close() {
}

// Constructs a new compressedResponseWriter based on client request headers.
// The compression starts with the response header.
func newCompressedResponseWriter(writer http.ResponseWriter, req *http.Request) *compressedResponseWriter {
encodings := strings.SplitSeq(req.Header.Get(acceptEncodingHeader), ",")
for encoding := range encodings {
switch strings.TrimSpace(encoding) {
case zstdEncoding:
encoder, err := zstd.NewWriter(writer)
if err == nil {
writer.Header().Set(contentEncodingHeader, zstdEncoding)
return &compressedResponseWriter{ResponseWriter: writer, writer: encoder}
}
case snappyEncoding:
writer.Header().Set(contentEncodingHeader, snappyEncoding)
return &compressedResponseWriter{ResponseWriter: writer, writer: snappy.NewBufferedWriter(writer)}
case gzipEncoding:
writer.Header().Set(contentEncodingHeader, gzipEncoding)
return &compressedResponseWriter{ResponseWriter: writer, writer: gzip.NewWriter(writer)}
case deflateEncoding:
writer.Header().Set(contentEncodingHeader, deflateEncoding)
return &compressedResponseWriter{ResponseWriter: writer, writer: zlib.NewWriter(writer)}
switch encoding = strings.TrimSpace(encoding); encoding {
case zstdEncoding, snappyEncoding, gzipEncoding, deflateEncoding:
return &compressedResponseWriter{ResponseWriter: writer, writer: writer, encoding: encoding}
}
}
return &compressedResponseWriter{ResponseWriter: writer, writer: writer}
Expand Down
35 changes: 35 additions & 0 deletions pkg/api/queryapi/compression_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,38 @@ func TestCompressionHandler_ServeHTTP(t *testing.T) {
decompressed := decompress(t, gzipEncoding, rec.Body.Bytes())
require.Equal(t, []byte("hello"), decompressed)
}

func TestCompressionHandler_ShouldNotCompressErrorResponses(t *testing.T) {
for _, tc := range []struct {
statusCode int
expectCompressed bool
}{
{statusCode: http.StatusOK, expectCompressed: true},
{statusCode: http.StatusBadRequest, expectCompressed: false},
{statusCode: http.StatusInternalServerError, expectCompressed: false},
} {
t.Run(http.StatusText(tc.statusCode), func(t *testing.T) {
payload := []byte(`{"status":"error","error":"something went wrong"}`)
handler := CompressionHandler{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(tc.statusCode)
_, err := w.Write(payload)
require.NoError(t, err)
})}

rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(acceptEncodingHeader, gzipEncoding)

handler.ServeHTTP(rec, req)

require.Equal(t, tc.statusCode, rec.Code)
if tc.expectCompressed {
require.Equal(t, gzipEncoding, rec.Header().Get(contentEncodingHeader))
require.Equal(t, payload, decompress(t, gzipEncoding, rec.Body.Bytes()))
} else {
require.Empty(t, rec.Header().Get(contentEncodingHeader))
require.Equal(t, payload, rec.Body.Bytes())
}
})
}
}
29 changes: 29 additions & 0 deletions pkg/api/queryapi/query_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,35 @@ func Test_InvalidCodec(t *testing.T) {
require.Equal(t, http.StatusNotAcceptable, rec.Code)
}

func Test_ErrorResponseIsNotCompressed(t *testing.T) {
engine := engine2.New(
promql.EngineOpts{
MaxSamples: 100,
Timeout: time.Second * 2,
},
engine2.ThanosEngineConfig{Enabled: false},
prometheus.NewRegistry())

queryAPI := NewQueryAPI(engine, &mockSampleAndChunkQueryable{}, querier.StatsRenderer, log.NewNopLogger(), []v1.Codec{v1.JSONCodec{}}, regexp.MustCompile(".*"), stats.PhaseTrackerConfig{})
router := mux.NewRouter()
router.Path("/api/v1/query").Methods("POST").Handler(queryAPI.Wrap(queryAPI.InstantQueryHandler))

req := httptest.NewRequest(http.MethodPost, "/api/v1/query?query=test&time=invalid", nil)
req.Header.Set(acceptEncodingHeader, gzipEncoding)
ctx := context.Background()
_, ctx = stats.ContextWithEmptyStats(ctx)
req = req.WithContext(user.InjectOrgID(ctx, "user1"))

rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.GreaterOrEqual(t, rec.Code, http.StatusBadRequest)

// The error must be readable as is, for example when the response body is logged.
require.Empty(t, rec.Header().Get(contentEncodingHeader))
require.Contains(t, rec.Body.String(), `"status":"error"`)
require.Contains(t, rec.Body.String(), `invalid parameter \"time\"`)
}

func Test_CustomAPI_StatsRenderer(t *testing.T) {
engine := engine2.New(
promql.EngineOpts{
Expand Down