- Admin pprof is opt-in (AdminConfig.EnablePprof) - Client spans drop the URL query string; HostFunc bounds the host label - Config.HTTP/HTTPClient/GRPC configure the Observer's instrumentation - A panic after a partial HTTP response counts as 500 - GaugeFunc, CounterFunc and RegisterDBStats panic on duplicates - Abandoned client gRPC streams are recorded as Canceled - OTEL_EXPORTER_OTLP_PROTOCOL selects the protocol when unset - Health reports are cached for 1s; hung checks are not restarted - Environment is exported as deployment.environment.name Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
8647fdf1bb
commit
c92fd9826b
21 files changed
+457
-101
No files matched your search
@@ -0,0 +1,230 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
healthpb "google.golang.org/grpc/health/grpc_health_v1"
|
||||
)
|
||||
|
||||
func TestHTTPMiddleware_PanicAfterWriteIs500(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
h := NewHTTPMiddleware(HTTPServerConfig{Metrics: m})(
|
||||
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("partial"))
|
||||
panic("boom")
|
||||
}))
|
||||
func() {
|
||||
defer func() { _ = recover() }()
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
|
||||
}()
|
||||
if !strings.Contains(scrape(t, m), `http_server_requests_total{code="500",method="GET",route="unmatched"} 1`) {
|
||||
t.Error("panic after a partial response not counted as 500")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPMiddleware_HijackAndReadFrom(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
var logs bytes.Buffer
|
||||
logger, _ := NewLogger(LogConfig{Output: &logs})
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /ws", func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, _, err := http.NewResponseController(w).Hijack()
|
||||
if err != nil {
|
||||
t.Errorf("hijack: %v", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
_, _ = conn.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n\r\n"))
|
||||
})
|
||||
mux.HandleFunc("GET /file", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.Copy(w, strings.NewReader("hello")) // goes through ReadFrom
|
||||
})
|
||||
srv := httptest.NewServer(NewHTTPMiddleware(HTTPServerConfig{Metrics: m, Logger: logger})(mux))
|
||||
defer srv.Close()
|
||||
|
||||
conn, err := net.Dial("tcp", srv.Listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
_, _ = conn.Write([]byte("GET /ws HTTP/1.1\r\nHost: x\r\n\r\n"))
|
||||
if line, _ := bufio.NewReader(conn).ReadString('\n'); !strings.Contains(line, "101") {
|
||||
t.Fatalf("hijacked response = %q", line)
|
||||
}
|
||||
|
||||
resp, err := http.Get(srv.URL + "/file")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if string(body) != "hello" {
|
||||
t.Errorf("body = %q", body)
|
||||
}
|
||||
|
||||
if !strings.Contains(scrape(t, m), `http_server_requests_total{code="101",method="GET",route="/ws"} 1`) {
|
||||
t.Errorf("hijacked request not counted as 101:\n%s", scrape(t, m))
|
||||
}
|
||||
if !strings.Contains(logs.String(), `"route":"/file","status":200`) || !strings.Contains(logs.String(), `"size":5`) {
|
||||
t.Errorf("ReadFrom size not logged: %s", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransport_HostFuncAndQueryRedaction(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
tp, exp := newTestProvider(t)
|
||||
srv := httptest.NewServer(http.NotFoundHandler())
|
||||
defer srv.Close()
|
||||
|
||||
client := &http.Client{Transport: NewHTTPTransport(nil, HTTPClientConfig{
|
||||
Metrics: m,
|
||||
TracerProvider: tp,
|
||||
HostFunc: func(*http.Request) string { return "external" },
|
||||
})}
|
||||
resp, err := client.Get(srv.URL + "/hook?token=s3cret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if !strings.Contains(scrape(t, m), `http_client_requests_total{code="404",host="external",method="GET"} 1`) {
|
||||
t.Errorf("HostFunc not applied:\n%s", scrape(t, m))
|
||||
}
|
||||
for _, a := range exp.GetSpans()[0].Attributes {
|
||||
if strings.Contains(a.Value.Emit(), "s3cret") {
|
||||
t.Errorf("query string leaked into span attribute %s=%s", a.Key, a.Value.Emit())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics_FuncCollectorsPanicOnDuplicate(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
m.GaugeFunc("depth", "Queue depth", func() float64 { return 1 })
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Error("second GaugeFunc with the same name must panic, not be ignored")
|
||||
}
|
||||
}()
|
||||
m.GaugeFunc("depth", "Queue depth", func() float64 { return 2 })
|
||||
}
|
||||
|
||||
type blockingHealth struct {
|
||||
healthpb.UnimplementedHealthServer
|
||||
}
|
||||
|
||||
func (blockingHealth) Watch(_ *healthpb.HealthCheckRequest, s healthpb.Health_WatchServer) error {
|
||||
<-s.Context().Done()
|
||||
return s.Context().Err()
|
||||
}
|
||||
|
||||
func TestGRPC_AbandonedClientStreamIsRecorded(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
client := startGRPCServer(t, blockingHealth{}, NewGRPCInterceptors(GRPCConfig{Metrics: m}))
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
if _, err := client.Watch(ctx, &healthpb.HealthCheckRequest{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cancel() // walk away without reading the stream
|
||||
|
||||
want := `grpc_client_requests_total{code="Canceled",method="Watch",service="grpc.health.v1.Health"} 1`
|
||||
for deadline := time.Now().Add(2 * time.Second); !strings.Contains(scrape(t, m), want); time.Sleep(5 * time.Millisecond) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("abandoned stream not recorded:\n%s", scrape(t, m))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGRPC_ServerPanicIsRecorded(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
ic := NewGRPCInterceptors(GRPCConfig{Metrics: m})
|
||||
func() {
|
||||
defer func() {
|
||||
if recover() != "boom" {
|
||||
t.Error("panic not re-raised")
|
||||
}
|
||||
}()
|
||||
_, _ = ic.UnaryServer(context.Background(), nil, &grpc.UnaryServerInfo{FullMethod: "/svc.S/M"},
|
||||
func(context.Context, any) (any, error) { panic("boom") })
|
||||
}()
|
||||
body := scrape(t, m)
|
||||
if !strings.Contains(body, `grpc_server_requests_total{code="Internal",method="M",service="svc.S"} 1`) ||
|
||||
!strings.Contains(body, "grpc_server_requests_in_flight 0") {
|
||||
t.Errorf("panic not recorded as Internal:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTracerConfig_ProtocolFromEnv(t *testing.T) {
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf")
|
||||
cfg := TracerConfig{Endpoint: "http://localhost:4318"}
|
||||
cfg.defaults()
|
||||
if cfg.Protocol != "http/protobuf" {
|
||||
t.Fatalf("Protocol = %q", cfg.Protocol)
|
||||
}
|
||||
exp, err := newExporter(context.Background(), cfg)
|
||||
if err != nil || exp == nil {
|
||||
t.Fatalf("exporter = %v, err = %v", exp, err)
|
||||
}
|
||||
_ = exp.Shutdown(context.Background())
|
||||
|
||||
explicit := TracerConfig{Protocol: ProtocolGRPC}
|
||||
explicit.defaults()
|
||||
if explicit.Protocol != ProtocolGRPC {
|
||||
t.Errorf("explicit Protocol overridden by env: %q", explicit.Protocol)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealth_CachesAndDoesNotStackHungChecks(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
h := NewHealth(HealthConfig{})
|
||||
h.AddReadinessCheck("db", func(context.Context) error { calls.Add(1); return nil })
|
||||
for range 5 {
|
||||
if !h.CheckReadiness(context.Background()).Healthy() {
|
||||
t.Fatal("unhealthy")
|
||||
}
|
||||
}
|
||||
if n := calls.Load(); n != 1 {
|
||||
t.Errorf("check ran %d times within the cache window, want 1", n)
|
||||
}
|
||||
|
||||
calls.Store(0)
|
||||
release := make(chan struct{})
|
||||
defer close(release)
|
||||
hung := NewHealth(HealthConfig{Timeout: 10 * time.Millisecond})
|
||||
hung.AddReadinessCheck("stuck", func(context.Context) error { calls.Add(1); <-release; return nil }) // ignores ctx
|
||||
hung.CheckReadiness(context.Background())
|
||||
hung.readyCache.reset()
|
||||
r := hung.CheckReadiness(context.Background())
|
||||
if r.Healthy() || !strings.Contains(r.Checks["stuck"].Error, "still in progress") {
|
||||
t.Errorf("report = %+v", r)
|
||||
}
|
||||
if n := calls.Load(); n != 1 {
|
||||
t.Errorf("hung check started %d times, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserver_HTTPConfigIsApplied(t *testing.T) {
|
||||
o, _, _ := newTestObserver(t, Config{HTTP: HTTPServerConfig{
|
||||
RouteFunc: func(*http.Request) string { return "/users/{id}" },
|
||||
Skip: func(r *http.Request) bool { return r.URL.Path == "/ws" },
|
||||
}})
|
||||
h := o.HTTPMiddleware(http.NotFoundHandler())
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/users/42", nil))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/ws", nil))
|
||||
|
||||
body := scrape(t, o.Metrics())
|
||||
if !strings.Contains(body, `http_server_requests_total{code="404",method="GET",route="/users/{id}"} 1`) {
|
||||
t.Errorf("RouteFunc/Skip from Config.HTTP not applied:\n%s", body)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user