Skip to content
Merged
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
5 changes: 5 additions & 0 deletions docs/STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@
(`ws_server.py`'s `get_or_create_otlp_session`) are all ported. Read back via `GET /api/streaming/sessions`
(the `{"data": [...]}` envelope + camelCase `SessionInfo` field shape the UI's `LiveStreamingView.tsx`
actually expects, not a guessed shape) and `GET /api/streaming/get-trace?session_id=`.
- **`Content-Encoding: gzip` on the OTLP/HTTP receiver** (`internal/api/server.go`'s `otlpRequestBody`) -
additive over Python, whose `api/otlp_routes.py` `receive_traces` reads the raw body with no
decompression. gzip is the OpenTelemetry Collector `otlphttp` exporter's default, so without it every export
from a stock collector got a 400 (dropped by the exporter as a permanent error); an unknown encoding now
gets 415 and a body that isn't valid gzip 400. Covered by `internal/api/otlp_http_test.go`.
- **OTLP/gRPC trace ingestion** (`internal/api/grpc.go`) - `:4317` by default, a `TraceServiceServer`
implementation (`go.opentelemetry.io/proto/otlp/collector/trace/v1`) sharing the exact same `SessionStore`
and conversion path (`otlp.ExportRequestToMap` → `ParseExportRequest`) as the HTTP receiver - grpc hands
Expand Down
117 changes: 117 additions & 0 deletions internal/api/otlp_http_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package api

import (
"bytes"
"compress/gzip"
"encoding/hex"
"net/http"
"net/http/httptest"
"testing"

coltracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1"
commonpb "go.opentelemetry.io/proto/otlp/common/v1"
resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
"google.golang.org/protobuf/proto"
)

func gzipBytes(t *testing.T, b []byte) []byte {
t.Helper()
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
if _, err := zw.Write(b); err != nil {
t.Fatalf("gzip write: %v", err)
}
if err := zw.Close(); err != nil {
t.Fatalf("gzip close: %v", err)
}
return buf.Bytes()
}

func otlpHTTPTestRequestProto(t *testing.T, session string) []byte {
t.Helper()
traceID, _ := hex.DecodeString("3e289017fe03ffd7c4145316d2eb3d0d")
spanID, _ := hex.DecodeString("e37fdd8f56146d31")
req := &coltracepb.ExportTraceServiceRequest{
ResourceSpans: []*tracepb.ResourceSpans{{
Resource: &resourcepb.Resource{Attributes: []*commonpb.KeyValue{
{Key: agentevalsSessionName, Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: session}}},
}},
ScopeSpans: []*tracepb.ScopeSpans{{
Scope: &commonpb.InstrumentationScope{Name: "gcp.vertex.agent"},
Spans: []*tracepb.Span{{
TraceId: traceID,
SpanId: spanID,
Name: "invoke_agent test",
StartTimeUnixNano: 1_000_000_000,
EndTimeUnixNano: 1_002_000_000,
}},
}},
}},
}
b, err := proto.Marshal(req)
if err != nil {
t.Fatalf("marshal: %v", err)
}
return b
}

func otlpHTTPTestRequestJSON(session string) []byte {
return []byte(`{"resourceSpans":[{"resource":{"attributes":[{"key":"` + agentevalsSessionName +
`","value":{"stringValue":"` + session + `"}}]},"scopeSpans":[{"scope":{"name":"gcp.vertex.agent"},` +
`"spans":[{"traceId":"3e289017fe03ffd7c4145316d2eb3d0d","spanId":"e37fdd8f56146d31",` +
`"name":"invoke_agent test","startTimeUnixNano":"1000000000","endTimeUnixNano":"1002000000"}]}]}]}`)
}

// TestOTLPTracesHandler_ContentEncoding covers the encodings a stock
// OpenTelemetry Collector sends: its otlphttp exporter gzips by default, so
// a receiver that only reads raw bodies rejects every export with a 400.
func TestOTLPTracesHandler_ContentEncoding(t *testing.T) {
cases := []struct {
name string
contentType string
encoding string
body func(t *testing.T) []byte
wantStatus int
wantSession bool
}{
{"protobuf identity", "application/x-protobuf", "",
func(t *testing.T) []byte { return otlpHTTPTestRequestProto(t, "s") }, http.StatusOK, true},
{"protobuf gzip", "application/x-protobuf", "gzip",
func(t *testing.T) []byte { return gzipBytes(t, otlpHTTPTestRequestProto(t, "s")) }, http.StatusOK, true},
{"json gzip", "application/json", "gzip",
func(t *testing.T) []byte { return gzipBytes(t, otlpHTTPTestRequestJSON("s")) }, http.StatusOK, true},
{"gzip header, uppercase", "application/x-protobuf", "GZIP",
func(t *testing.T) []byte { return gzipBytes(t, otlpHTTPTestRequestProto(t, "s")) }, http.StatusOK, true},
{"unsupported encoding", "application/x-protobuf", "br",
func(t *testing.T) []byte { return otlpHTTPTestRequestProto(t, "s") }, http.StatusUnsupportedMediaType, false},
{"gzip header, body not gzip", "application/x-protobuf", "gzip",
func(t *testing.T) []byte { return otlpHTTPTestRequestProto(t, "s") }, http.StatusBadRequest, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
store := NewSessionStore(nil)
req := httptest.NewRequest(http.MethodPost, "/v1/traces", bytes.NewReader(tc.body(t)))
req.Header.Set("Content-Type", tc.contentType)
if tc.encoding != "" {
req.Header.Set("Content-Encoding", tc.encoding)
}
rec := httptest.NewRecorder()
otlpTracesHandler(store)(rec, req)

if rec.Code != tc.wantStatus {
t.Fatalf("status = %d, want %d (body %q)", rec.Code, tc.wantStatus, rec.Body.String())
}
sessions := store.List()
if !tc.wantSession {
if len(sessions) != 0 {
t.Fatalf("got %d sessions, want 0", len(sessions))
}
return
}
if len(sessions) != 1 || sessions[0].SpanCount != 1 || sessions[0].SessionID != "s" {
t.Fatalf("sessions = %+v, want one session \"s\" with 1 span", sessions)
}
})
}
}
34 changes: 32 additions & 2 deletions internal/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
package api

import (
"compress/gzip"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -225,11 +226,18 @@ func otlpTracesHandler(store *SessionStore) http.HandlerFunc {
return
}

reqBody, status, err := otlpRequestBody(r)
if err != nil {
http.Error(w, err.Error(), status)
return
}
defer reqBody.Close()

contentType := r.Header.Get("Content-Type")
var body map[string]any

if strings.Contains(contentType, "application/x-protobuf") {
raw, err := io.ReadAll(r.Body)
raw, err := io.ReadAll(reqBody)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
Expand All @@ -240,7 +248,7 @@ func otlpTracesHandler(store *SessionStore) http.HandlerFunc {
return
}
} else {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
if err := json.NewDecoder(reqBody).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
Expand All @@ -254,6 +262,28 @@ func otlpTracesHandler(store *SessionStore) http.HandlerFunc {
}
}

// otlpRequestBody returns r's body with its Content-Encoding undone.
// Additive over Python: api/otlp_routes.py's receive_traces reads the raw
// body (request.body()/request.json()) with no decompression, so both
// implementations rejected gzip. gzip is the default of the OpenTelemetry
// Collector's otlphttp exporter, so every export from a stock collector
// failed to decode and got a 400, which the exporter treats as permanent and
// drops. The returned status is only meaningful when err is non-nil.
func otlpRequestBody(r *http.Request) (io.ReadCloser, int, error) {
switch enc := strings.ToLower(strings.TrimSpace(r.Header.Get("Content-Encoding"))); enc {
case "", "identity":
return r.Body, 0, nil
case "gzip":
zr, err := gzip.NewReader(r.Body)
if err != nil {
return nil, http.StatusBadRequest, fmt.Errorf("invalid gzip body: %w", err)
}
return zr, 0, nil
default:
return nil, http.StatusUnsupportedMediaType, fmt.Errorf("unsupported Content-Encoding %q", enc)
}
}

// sessionsHandler implements GET /api/streaming/sessions, returning the
// {"data": [...], "error": null} envelope the UI's fetchExistingSessions
// expects (LiveStreamingView.tsx reads response.data; "error" is FastAPI's
Expand Down
Loading