Skip to content
Closed
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
57 changes: 54 additions & 3 deletions cmd/query/app/apiv3/http_gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
package apiv3

import (
"compress/gzip"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"

"github.com/gogo/protobuf/jsonpb"
Expand Down Expand Up @@ -51,6 +53,12 @@
Tracer trace.TracerProvider
}

type chunkedGzipWriter struct {
http.ResponseWriter
gzipWriter *gzip.Writer
flusher http.Flusher
}

// RegisterRoutes registers HTTP endpoints for APIv3 into provided mux.
// The called can create a subrouter if it needs to prepend a base path.
func (h *HTTPGateway) RegisterRoutes(router *mux.Router) {
Expand All @@ -60,15 +68,58 @@
h.addRoute(router, h.getOperations, routeGetOperations).Methods(http.MethodGet)
}

// addRoute adds a new endpoint to the router with given path and handler function.
// This code is mostly copied from ../http_handler.
func (w *chunkedGzipWriter) Write(b []byte) (int, error) {
n, err := w.gzipWriter.Write(b)
if err != nil {
return n, err
}

if err := w.gzipWriter.Flush(); err != nil {
return n, err
}

Check warning on line 79 in cmd/query/app/apiv3/http_gateway.go

View check run for this annotation

Codecov / codecov/patch

cmd/query/app/apiv3/http_gateway.go#L78-L79

Added lines #L78 - L79 were not covered by tests

w.flusher.Flush()
return n, nil
}

Check warning on line 83 in cmd/query/app/apiv3/http_gateway.go

View check run for this annotation

Codecov / codecov/patch

cmd/query/app/apiv3/http_gateway.go#L82-L83

Added lines #L82 - L83 were not covered by tests

func gzipMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
}

flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}

// Set chunked transfer encoding before any writes
w.Header().Set("Transfer-Encoding", "chunked")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

chunked encoding requires each chunk to be prefixed with its size

w.Header().Set("Content-Encoding", "gzip")

Check warning on line 100 in cmd/query/app/apiv3/http_gateway.go

View check run for this annotation

Codecov / codecov/patch

cmd/query/app/apiv3/http_gateway.go#L98-L100

Added lines #L98 - L100 were not covered by tests
w.Header().Set("Vary", "Accept-Encoding")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is this?


gz := gzip.NewWriter(w)
defer gz.Close()
Comment on lines +103 to +104
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The defer gz.Close() placement could cause issues with premature closing. Since it's defined in the middleware handler function, it will execute when that function returns, not when all data has been written. This could lead to incomplete responses.

Consider either:

  1. Moving the close operation to be explicitly called after all data is written, or
  2. Implementing a Close() method on the chunkedGzipWriter struct that handles proper cleanup

This would ensure the gzip writer remains open until all data has been properly flushed and written to the response.

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.


writer := &chunkedGzipWriter{
ResponseWriter: w,
gzipWriter: gz,
flusher: flusher,
}

next.ServeHTTP(writer, r)
})
}

func (*HTTPGateway) addRoute(
router *mux.Router,
f func(http.ResponseWriter, *http.Request),
route string,
_ ...any, /* args */
) *mux.Route {
var handler http.Handler = http.HandlerFunc(f)
handler = gzipMiddleware(handler)
handler = otelhttp.WithRouteTag(route, handler)
handler = spanNameHandler(route, handler)
return router.HandleFunc(route, handler.ServeHTTP)
Expand Down
16 changes: 16 additions & 0 deletions cmd/query/app/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"bytes"
"context"
"fmt"
"io"
"net"
"net/http"
"testing"
Expand Down Expand Up @@ -915,6 +916,21 @@ func TestServerHTTP_TracesRequest(t *testing.T) {
resp, err := client.Do(req)
require.NoError(t, err)

var fullResponse bytes.Buffer

buf := make([]byte, 1024)
for {
n, err := resp.Body.Read(buf)

Comment on lines +923 to +924
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Read() operation should handle all error cases, not just EOF. Consider updating the error handling to properly catch and respond to any read errors:

n, err := resp.Body.Read(buf)
if err != nil && err != io.EOF {
    require.NoError(t, err)
    break
}

This ensures the test fails appropriately if there's a network issue or other error during response reading, rather than silently continuing.

Suggested change
n, err := resp.Body.Read(buf)
n, err := resp.Body.Read(buf)
if err != nil && err != io.EOF {
require.NoError(t, err)
break
}

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.

if n > 0 {
fullResponse.Write(buf[:n])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you concatenate the chunks you will end up with invalid JSON

}

if err == io.EOF {
break
}
}

if test.expectedTrace != "" {
assert.Len(t, exporter.GetSpans(), 1, "HTTP request was traced and span reported")
assert.Equal(t, test.expectedTrace, exporter.GetSpans()[0].Name)
Expand Down
Loading