| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package otelhttp |
| 5 |
|
| 6 |
import ( |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"net/http" |
| 10 |
"net/http/httptest" |
| 11 |
"strconv" |
| 12 |
"strings" |
| 13 |
"testing" |
| 14 |
"time" |
| 15 |
|
| 16 |
"github.com/stretchr/testify/assert" |
| 17 |
"github.com/stretchr/testify/require" |
| 18 |
"go.opentelemetry.io/otel/attribute" |
| 19 |
"go.opentelemetry.io/otel/codes" |
| 20 |
"go.opentelemetry.io/otel/propagation" |
| 21 |
"go.opentelemetry.io/otel/sdk/instrumentation" |
| 22 |
sdkmetric "go.opentelemetry.io/otel/sdk/metric" |
| 23 |
"go.opentelemetry.io/otel/sdk/metric/metricdata" |
| 24 |
"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest" |
| 25 |
sdktrace "go.opentelemetry.io/otel/sdk/trace" |
| 26 |
"go.opentelemetry.io/otel/sdk/trace/tracetest" |
| 27 |
"go.opentelemetry.io/otel/trace" |
| 28 |
) |
| 29 |
|
| 30 |
func TestHandler(t *testing.T) { |
| 31 |
testCases := []struct { |
| 32 |
name string |
| 33 |
handler func(*testing.T) http.Handler |
| 34 |
requestBody io.Reader |
| 35 |
expectedStatusCode int |
| 36 |
}{ |
| 37 |
{ |
| 38 |
name: "implements flusher", |
| 39 |
handler: func(t *testing.T) http.Handler { |
| 40 |
return NewHandler( |
| 41 |
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 42 |
assert.Implements(t, (*http.Flusher)(nil), w) |
| 43 |
|
| 44 |
w.(http.Flusher).Flush() |
| 45 |
_, _ = io.WriteString(w, "Hello, world!\n") |
| 46 |
}), "test_handler", |
| 47 |
) |
| 48 |
}, |
| 49 |
expectedStatusCode: http.StatusOK, |
| 50 |
}, |
| 51 |
{ |
| 52 |
name: "succeeds", |
| 53 |
handler: func(t *testing.T) http.Handler { |
| 54 |
return NewHandler( |
| 55 |
http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { |
| 56 |
assert.NotNil(t, r.Body) |
| 57 |
|
| 58 |
b, err := io.ReadAll(r.Body) |
| 59 |
assert.NoError(t, err) |
| 60 |
assert.Equal(t, "hello world", string(b)) |
| 61 |
}), "test_handler", |
| 62 |
) |
| 63 |
}, |
| 64 |
requestBody: strings.NewReader("hello world"), |
| 65 |
expectedStatusCode: http.StatusOK, |
| 66 |
}, |
| 67 |
{ |
| 68 |
name: "succeeds with a nil body", |
| 69 |
handler: func(t *testing.T) http.Handler { |
| 70 |
return NewHandler( |
| 71 |
http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { |
| 72 |
assert.Nil(t, r.Body) |
| 73 |
}), "test_handler", |
| 74 |
) |
| 75 |
}, |
| 76 |
expectedStatusCode: http.StatusOK, |
| 77 |
}, |
| 78 |
{ |
| 79 |
name: "succeeds with an http.NoBody", |
| 80 |
handler: func(t *testing.T) http.Handler { |
| 81 |
return NewHandler( |
| 82 |
http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { |
| 83 |
assert.Equal(t, http.NoBody, r.Body) |
| 84 |
}), "test_handler", |
| 85 |
) |
| 86 |
}, |
| 87 |
requestBody: http.NoBody, |
| 88 |
expectedStatusCode: http.StatusOK, |
| 89 |
}, |
| 90 |
} |
| 91 |
for _, tc := range testCases { |
| 92 |
t.Run(tc.name, func(t *testing.T) { |
| 93 |
r, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://localhost/", tc.requestBody) |
| 94 |
require.NoError(t, err) |
| 95 |
|
| 96 |
rr := httptest.NewRecorder() |
| 97 |
tc.handler(t).ServeHTTP(rr, r) |
| 98 |
assert.Equal(t, tc.expectedStatusCode, rr.Result().StatusCode) |
| 99 |
}) |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
func TestHandlerBasics(t *testing.T) { |
| 104 |
t.Setenv("OTEL_METRICS_EXEMPLAR_FILTER", "always_off") |
| 105 |
rr := httptest.NewRecorder() |
| 106 |
|
| 107 |
spanRecorder := tracetest.NewSpanRecorder() |
| 108 |
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(spanRecorder)) |
| 109 |
|
| 110 |
reader := sdkmetric.NewManualReader() |
| 111 |
meterProvider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)) |
| 112 |
|
| 113 |
h := NewHandler( |
| 114 |
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 115 |
l, _ := LabelerFromContext(r.Context()) |
| 116 |
l.Add(attribute.String("test", "attribute")) |
| 117 |
|
| 118 |
if _, err := io.WriteString(w, "hello world"); err != nil { |
| 119 |
t.Fatal(err) |
| 120 |
} |
| 121 |
}), "test_handler", |
| 122 |
WithTracerProvider(provider), |
| 123 |
WithMeterProvider(meterProvider), |
| 124 |
WithPropagators(propagation.TraceContext{}), |
| 125 |
) |
| 126 |
|
| 127 |
// set a custom start time 10 minutes in the past. |
| 128 |
startTime := time.Now().Add(-10 * time.Minute) |
| 129 |
ctx := ContextWithStartTime(t.Context(), startTime) |
| 130 |
|
| 131 |
r := httptest.NewRequestWithContext(ctx, http.MethodGet, "/test", strings.NewReader("foo")) |
| 132 |
r.Pattern = "/test" |
| 133 |
h.ServeHTTP(rr, r) |
| 134 |
|
| 135 |
rm := metricdata.ResourceMetrics{} |
| 136 |
err := reader.Collect(t.Context(), &rm) |
| 137 |
require.NoError(t, err) |
| 138 |
require.Len(t, rm.ScopeMetrics, 1) |
| 139 |
attrs := attribute.NewSet( |
| 140 |
attribute.String("http.request.method", "GET"), |
| 141 |
attribute.String("http.route", "/test"), |
| 142 |
attribute.Int64("http.response.status_code", 200), |
| 143 |
attribute.String("network.protocol.name", "http"), |
| 144 |
attribute.String("network.protocol.version", fmt.Sprintf("1.%d", r.ProtoMinor)), |
| 145 |
attribute.String("server.address", r.Host), |
| 146 |
attribute.String("url.scheme", "http"), |
| 147 |
attribute.String("test", "attribute"), |
| 148 |
) |
| 149 |
assertScopeMetrics(t, rm.ScopeMetrics[0], attrs) |
| 150 |
|
| 151 |
if got, expected := rr.Result().StatusCode, http.StatusOK; got != expected { |
| 152 |
t.Fatalf("got %d, expected %d", got, expected) |
| 153 |
} |
| 154 |
|
| 155 |
spans := spanRecorder.Ended() |
| 156 |
if got, expected := len(spans), 1; got != expected { |
| 157 |
t.Fatalf("got %d spans, expected %d", got, expected) |
| 158 |
} |
| 159 |
if !spans[0].SpanContext().IsValid() { |
| 160 |
t.Fatalf("invalid span created: %#v", spans[0].SpanContext()) |
| 161 |
} |
| 162 |
|
| 163 |
d, err := io.ReadAll(rr.Result().Body) |
| 164 |
if err != nil { |
| 165 |
t.Fatal(err) |
| 166 |
} |
| 167 |
if got, expected := string(d), "hello world"; got != expected { |
| 168 |
t.Fatalf("got %q, expected %q", got, expected) |
| 169 |
} |
| 170 |
assert.Equal(t, startTime, spans[0].StartTime()) |
| 171 |
} |
| 172 |
|
| 173 |
func assertScopeMetrics(t *testing.T, sm metricdata.ScopeMetrics, attrs attribute.Set) { |
| 174 |
assert.Equal(t, instrumentation.Scope{ |
| 175 |
Name: "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp", |
| 176 |
Version: Version, |
| 177 |
}, sm.Scope) |
| 178 |
|
| 179 |
require.Len(t, sm.Metrics, 3) |
| 180 |
|
| 181 |
want := metricdata.ScopeMetrics{ |
| 182 |
Scope: instrumentation.Scope{ |
| 183 |
Name: ScopeName, |
| 184 |
Version: Version, |
| 185 |
}, |
| 186 |
Metrics: []metricdata.Metrics{ |
| 187 |
{ |
| 188 |
Name: "http.server.request.body.size", |
| 189 |
Description: "Size of HTTP server request bodies.", |
| 190 |
Unit: "By", |
| 191 |
Data: metricdata.Histogram[int64]{ |
| 192 |
Temporality: metricdata.CumulativeTemporality, |
| 193 |
DataPoints: []metricdata.HistogramDataPoint[int64]{ |
| 194 |
{ |
| 195 |
Attributes: attrs, |
| 196 |
}, |
| 197 |
}, |
| 198 |
}, |
| 199 |
}, |
| 200 |
{ |
| 201 |
Name: "http.server.response.body.size", |
| 202 |
Description: "Size of HTTP server response bodies.", |
| 203 |
Unit: "By", |
| 204 |
Data: metricdata.Histogram[int64]{ |
| 205 |
Temporality: metricdata.CumulativeTemporality, |
| 206 |
DataPoints: []metricdata.HistogramDataPoint[int64]{ |
| 207 |
{ |
| 208 |
Attributes: attrs, |
| 209 |
}, |
| 210 |
}, |
| 211 |
}, |
| 212 |
}, |
| 213 |
{ |
| 214 |
Name: "http.server.request.duration", |
| 215 |
Description: "Duration of HTTP server requests.", |
| 216 |
Unit: "s", |
| 217 |
Data: metricdata.Histogram[float64]{ |
| 218 |
Temporality: metricdata.CumulativeTemporality, |
| 219 |
DataPoints: []metricdata.HistogramDataPoint[float64]{ |
| 220 |
{ |
| 221 |
Attributes: attrs, |
| 222 |
}, |
| 223 |
}, |
| 224 |
}, |
| 225 |
}, |
| 226 |
}, |
| 227 |
} |
| 228 |
metricdatatest.AssertEqual(t, want, sm, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue(), metricdatatest.IgnoreExemplars()) |
| 229 |
|
| 230 |
// verify that the custom start time, which is 10 minutes in the past, is respected. |
| 231 |
assert.GreaterOrEqual(t, sm.Metrics[2].Data.(metricdata.Histogram[float64]).DataPoints[0].Sum, float64(10*time.Minute/time.Second)) |
| 232 |
} |
| 233 |
|
| 234 |
func TestHandlerEmittedAttributes(t *testing.T) { |
| 235 |
testCases := []struct { |
| 236 |
name string |
| 237 |
handler func(http.ResponseWriter, *http.Request) |
| 238 |
attributes []attribute.KeyValue |
| 239 |
}{ |
| 240 |
{ |
| 241 |
name: "With a success handler", |
| 242 |
handler: func(w http.ResponseWriter, _ *http.Request) { |
| 243 |
w.WriteHeader(http.StatusOK) |
| 244 |
}, |
| 245 |
attributes: []attribute.KeyValue{ |
| 246 |
attribute.Int("http.response.status_code", http.StatusOK), |
| 247 |
}, |
| 248 |
}, |
| 249 |
{ |
| 250 |
name: "With a failing handler", |
| 251 |
handler: func(w http.ResponseWriter, _ *http.Request) { |
| 252 |
w.WriteHeader(http.StatusBadRequest) |
| 253 |
}, |
| 254 |
attributes: []attribute.KeyValue{ |
| 255 |
attribute.Int("http.response.status_code", http.StatusBadRequest), |
| 256 |
}, |
| 257 |
}, |
| 258 |
{ |
| 259 |
name: "With an empty handler", |
| 260 |
handler: func(http.ResponseWriter, *http.Request) { |
| 261 |
}, |
| 262 |
attributes: []attribute.KeyValue{ |
| 263 |
attribute.Int("http.response.status_code", http.StatusOK), |
| 264 |
}, |
| 265 |
}, |
| 266 |
{ |
| 267 |
name: "With persisting initial failing status in handler with multiple WriteHeader calls", |
| 268 |
handler: func(w http.ResponseWriter, _ *http.Request) { |
| 269 |
w.WriteHeader(http.StatusInternalServerError) |
| 270 |
w.WriteHeader(http.StatusOK) |
| 271 |
}, |
| 272 |
attributes: []attribute.KeyValue{ |
| 273 |
attribute.Int("http.response.status_code", http.StatusInternalServerError), |
| 274 |
}, |
| 275 |
}, |
| 276 |
} |
| 277 |
for _, tc := range testCases { |
| 278 |
t.Run(tc.name, func(t *testing.T) { |
| 279 |
sr := tracetest.NewSpanRecorder() |
| 280 |
provider := sdktrace.NewTracerProvider() |
| 281 |
provider.RegisterSpanProcessor(sr) |
| 282 |
h := NewHandler( |
| 283 |
http.HandlerFunc(tc.handler), "test_handler", |
| 284 |
WithTracerProvider(provider), |
| 285 |
) |
| 286 |
|
| 287 |
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", http.NoBody)) |
| 288 |
|
| 289 |
require.Len(t, sr.Ended(), 1, "should emit a span") |
| 290 |
attrs := sr.Ended()[0].Attributes() |
| 291 |
|
| 292 |
for _, a := range tc.attributes { |
| 293 |
assert.Contains(t, attrs, a) |
| 294 |
} |
| 295 |
}) |
| 296 |
} |
| 297 |
} |
| 298 |
|
| 299 |
type respWriteHeaderCounter struct { |
| 300 |
http.ResponseWriter |
| 301 |
|
| 302 |
headersWritten []int |
| 303 |
} |
| 304 |
|
| 305 |
func (rw *respWriteHeaderCounter) WriteHeader(statusCode int) { |
| 306 |
rw.headersWritten = append(rw.headersWritten, statusCode) |
| 307 |
rw.ResponseWriter.WriteHeader(statusCode) |
| 308 |
} |
| 309 |
|
| 310 |
func (rw *respWriteHeaderCounter) Flush() { |
| 311 |
if f, ok := rw.ResponseWriter.(http.Flusher); ok { |
| 312 |
f.Flush() |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
func TestHandlerPropagateWriteHeaderCalls(t *testing.T) { |
| 317 |
testCases := []struct { |
| 318 |
name string |
| 319 |
handler func(http.ResponseWriter, *http.Request) |
| 320 |
expectHeadersWritten []int |
| 321 |
}{ |
| 322 |
{ |
| 323 |
name: "With a success handler", |
| 324 |
handler: func(w http.ResponseWriter, _ *http.Request) { |
| 325 |
w.WriteHeader(http.StatusOK) |
| 326 |
}, |
| 327 |
expectHeadersWritten: []int{http.StatusOK}, |
| 328 |
}, |
| 329 |
{ |
| 330 |
name: "With a failing handler", |
| 331 |
handler: func(w http.ResponseWriter, _ *http.Request) { |
| 332 |
w.WriteHeader(http.StatusBadRequest) |
| 333 |
}, |
| 334 |
expectHeadersWritten: []int{http.StatusBadRequest}, |
| 335 |
}, |
| 336 |
{ |
| 337 |
name: "With an empty handler", |
| 338 |
handler: func(http.ResponseWriter, *http.Request) { |
| 339 |
}, |
| 340 |
|
| 341 |
expectHeadersWritten: nil, |
| 342 |
}, |
| 343 |
{ |
| 344 |
name: "With calling WriteHeader twice", |
| 345 |
handler: func(w http.ResponseWriter, _ *http.Request) { |
| 346 |
w.WriteHeader(http.StatusInternalServerError) |
| 347 |
w.WriteHeader(http.StatusOK) |
| 348 |
}, |
| 349 |
expectHeadersWritten: []int{http.StatusInternalServerError, http.StatusOK}, |
| 350 |
}, |
| 351 |
{ |
| 352 |
name: "When writing the header indirectly through body write", |
| 353 |
handler: func(w http.ResponseWriter, _ *http.Request) { |
| 354 |
_, _ = w.Write([]byte("hello")) |
| 355 |
}, |
| 356 |
expectHeadersWritten: []int{http.StatusOK}, |
| 357 |
}, |
| 358 |
{ |
| 359 |
name: "With a header already written when writing the body", |
| 360 |
handler: func(w http.ResponseWriter, _ *http.Request) { |
| 361 |
w.WriteHeader(http.StatusBadRequest) |
| 362 |
_, _ = w.Write([]byte("hello")) |
| 363 |
}, |
| 364 |
expectHeadersWritten: []int{http.StatusBadRequest}, |
| 365 |
}, |
| 366 |
{ |
| 367 |
name: "When writing the header indirectly through flush", |
| 368 |
handler: func(w http.ResponseWriter, _ *http.Request) { |
| 369 |
f := w.(http.Flusher) |
| 370 |
f.Flush() |
| 371 |
}, |
| 372 |
expectHeadersWritten: []int{http.StatusOK}, |
| 373 |
}, |
| 374 |
{ |
| 375 |
name: "With a header already written when flushing", |
| 376 |
handler: func(w http.ResponseWriter, _ *http.Request) { |
| 377 |
w.WriteHeader(http.StatusBadRequest) |
| 378 |
f := w.(http.Flusher) |
| 379 |
f.Flush() |
| 380 |
}, |
| 381 |
expectHeadersWritten: []int{http.StatusBadRequest}, |
| 382 |
}, |
| 383 |
} |
| 384 |
|
| 385 |
for _, tc := range testCases { |
| 386 |
t.Run(tc.name, func(t *testing.T) { |
| 387 |
sr := tracetest.NewSpanRecorder() |
| 388 |
provider := sdktrace.NewTracerProvider() |
| 389 |
provider.RegisterSpanProcessor(sr) |
| 390 |
h := NewHandler( |
| 391 |
http.HandlerFunc(tc.handler), "test_handler", |
| 392 |
WithTracerProvider(provider), |
| 393 |
) |
| 394 |
|
| 395 |
recorder := httptest.NewRecorder() |
| 396 |
rw := &respWriteHeaderCounter{ResponseWriter: recorder} |
| 397 |
h.ServeHTTP(rw, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", http.NoBody)) |
| 398 |
require.Equal(t, tc.expectHeadersWritten, rw.headersWritten, "should propagate all WriteHeader calls to underlying ResponseWriter") |
| 399 |
}) |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
func TestHandlerRequestWithTraceContext(t *testing.T) { |
| 404 |
rr := httptest.NewRecorder() |
| 405 |
|
| 406 |
h := NewHandler( |
| 407 |
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 408 |
_, err := w.Write([]byte("hello world")) |
| 409 |
assert.NoError(t, err) |
| 410 |
}), "test_handler") |
| 411 |
|
| 412 |
r, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://localhost/", http.NoBody) |
| 413 |
require.NoError(t, err) |
| 414 |
|
| 415 |
spanRecorder := tracetest.NewSpanRecorder() |
| 416 |
provider := sdktrace.NewTracerProvider( |
| 417 |
sdktrace.WithSpanProcessor(spanRecorder), |
| 418 |
) |
| 419 |
tracer := provider.Tracer("") |
| 420 |
ctx, span := tracer.Start(t.Context(), "test_request") |
| 421 |
r = r.WithContext(ctx) |
| 422 |
|
| 423 |
h.ServeHTTP(rr, r) |
| 424 |
assert.Equal(t, http.StatusOK, rr.Result().StatusCode) |
| 425 |
|
| 426 |
span.End() |
| 427 |
|
| 428 |
spans := spanRecorder.Ended() |
| 429 |
require.Len(t, spans, 2) |
| 430 |
|
| 431 |
assert.Equal(t, "test_handler", spans[0].Name()) |
| 432 |
assert.Equal(t, "test_request", spans[1].Name()) |
| 433 |
assert.NotEmpty(t, spans[0].Parent().SpanID()) |
| 434 |
assert.Equal(t, spans[1].SpanContext().SpanID(), spans[0].Parent().SpanID()) |
| 435 |
} |
| 436 |
|
| 437 |
func TestWithSpanNameFormatter(t *testing.T) { |
| 438 |
for _, tt := range []struct { |
| 439 |
name string |
| 440 |
|
| 441 |
formatter func(operation string, r *http.Request) string |
| 442 |
wantSpanName string |
| 443 |
}{ |
| 444 |
{ |
| 445 |
name: "with the default span name formatter", |
| 446 |
wantSpanName: "test_handler", |
| 447 |
}, |
| 448 |
{ |
| 449 |
name: "with a custom span name formatter", |
| 450 |
formatter: func(_ string, r *http.Request) string { |
| 451 |
return fmt.Sprintf("%s %s", r.Method, r.URL.Path) |
| 452 |
}, |
| 453 |
wantSpanName: "GET /foo/123", |
| 454 |
}, |
| 455 |
{ |
| 456 |
name: "with a custom span name formatter using the pattern", |
| 457 |
formatter: func(_ string, r *http.Request) string { |
| 458 |
return fmt.Sprintf("%s %s", r.Method, r.Pattern) |
| 459 |
}, |
| 460 |
wantSpanName: "GET /foo/{id}", |
| 461 |
}, |
| 462 |
} { |
| 463 |
t.Run(tt.name, func(t *testing.T) { |
| 464 |
spanRecorder := tracetest.NewSpanRecorder() |
| 465 |
provider := sdktrace.NewTracerProvider( |
| 466 |
sdktrace.WithSpanProcessor(spanRecorder), |
| 467 |
) |
| 468 |
|
| 469 |
opts := []Option{ |
| 470 |
WithTracerProvider(provider), |
| 471 |
} |
| 472 |
if tt.formatter != nil { |
| 473 |
opts = append(opts, WithSpanNameFormatter(tt.formatter)) |
| 474 |
} |
| 475 |
|
| 476 |
mux := http.NewServeMux() |
| 477 |
mux.Handle("/foo/{id}", http.HandlerFunc(func(http.ResponseWriter, *http.Request) { |
| 478 |
// Nothing to do here |
| 479 |
})) |
| 480 |
h := NewHandler(mux, "test_handler", opts...) |
| 481 |
|
| 482 |
r, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://localhost/foo/123", http.NoBody) |
| 483 |
require.NoError(t, err) |
| 484 |
|
| 485 |
rr := httptest.NewRecorder() |
| 486 |
h.ServeHTTP(rr, r) |
| 487 |
assert.Equal(t, http.StatusOK, rr.Result().StatusCode) |
| 488 |
|
| 489 |
assert.NoError(t, spanRecorder.ForceFlush(t.Context())) |
| 490 |
spans := spanRecorder.Ended() |
| 491 |
assert.Len(t, spans, 1) |
| 492 |
assert.Equal(t, tt.wantSpanName, spans[0].Name()) |
| 493 |
}) |
| 494 |
} |
| 495 |
} |
| 496 |
|
| 497 |
func TestWithPublicEndpointFn(t *testing.T) { |
| 498 |
remoteSpan := trace.SpanContextConfig{ |
| 499 |
TraceID: trace.TraceID{0x01}, |
| 500 |
SpanID: trace.SpanID{0x01}, |
| 501 |
TraceFlags: trace.FlagsSampled, |
| 502 |
Remote: true, |
| 503 |
} |
| 504 |
prop := propagation.TraceContext{} |
| 505 |
|
| 506 |
for _, tt := range []struct { |
| 507 |
name string |
| 508 |
fn func(*http.Request) bool |
| 509 |
handlerAssert func(*testing.T, trace.SpanContext) |
| 510 |
spansAssert func(*testing.T, trace.SpanContext, []sdktrace.ReadOnlySpan) |
| 511 |
}{ |
| 512 |
{ |
| 513 |
name: "with the method returning true", |
| 514 |
fn: func(*http.Request) bool { |
| 515 |
return true |
| 516 |
}, |
| 517 |
handlerAssert: func(t *testing.T, sc trace.SpanContext) { |
| 518 |
// Should be with new root trace. |
| 519 |
assert.True(t, sc.IsValid()) |
| 520 |
assert.False(t, sc.IsRemote()) |
| 521 |
assert.NotEqual(t, remoteSpan.TraceID, sc.TraceID()) |
| 522 |
}, |
| 523 |
spansAssert: func(t *testing.T, sc trace.SpanContext, spans []sdktrace.ReadOnlySpan) { |
| 524 |
require.Len(t, spans, 1) |
| 525 |
require.Len(t, spans[0].Links(), 1, "should contain link") |
| 526 |
require.True(t, sc.Equal(spans[0].Links()[0].SpanContext), "should link incoming span context") |
| 527 |
}, |
| 528 |
}, |
| 529 |
{ |
| 530 |
name: "with the method returning false", |
| 531 |
fn: func(*http.Request) bool { |
| 532 |
return false |
| 533 |
}, |
| 534 |
handlerAssert: func(t *testing.T, sc trace.SpanContext) { |
| 535 |
// Should have remote span as parent |
| 536 |
assert.True(t, sc.IsValid()) |
| 537 |
assert.False(t, sc.IsRemote()) |
| 538 |
assert.Equal(t, remoteSpan.TraceID, sc.TraceID()) |
| 539 |
}, |
| 540 |
spansAssert: func(t *testing.T, _ trace.SpanContext, spans []sdktrace.ReadOnlySpan) { |
| 541 |
require.Len(t, spans, 1) |
| 542 |
require.Empty(t, spans[0].Links(), "should not contain link") |
| 543 |
}, |
| 544 |
}, |
| 545 |
} { |
| 546 |
t.Run(tt.name, func(t *testing.T) { |
| 547 |
spanRecorder := tracetest.NewSpanRecorder() |
| 548 |
provider := sdktrace.NewTracerProvider( |
| 549 |
sdktrace.WithSpanProcessor(spanRecorder), |
| 550 |
) |
| 551 |
|
| 552 |
h := NewHandler( |
| 553 |
http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { |
| 554 |
s := trace.SpanFromContext(r.Context()) |
| 555 |
tt.handlerAssert(t, s.SpanContext()) |
| 556 |
}), "test_handler", |
| 557 |
WithPublicEndpointFn(tt.fn), |
| 558 |
WithPropagators(prop), |
| 559 |
WithTracerProvider(provider), |
| 560 |
) |
| 561 |
|
| 562 |
r, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://localhost/", http.NoBody) |
| 563 |
require.NoError(t, err) |
| 564 |
|
| 565 |
sc := trace.NewSpanContext(remoteSpan) |
| 566 |
ctx := trace.ContextWithSpanContext(t.Context(), sc) |
| 567 |
prop.Inject(ctx, propagation.HeaderCarrier(r.Header)) |
| 568 |
|
| 569 |
rr := httptest.NewRecorder() |
| 570 |
h.ServeHTTP(rr, r) |
| 571 |
assert.Equal(t, http.StatusOK, rr.Result().StatusCode) |
| 572 |
|
| 573 |
// Recorded span should be linked with an incoming span context. |
| 574 |
assert.NoError(t, spanRecorder.ForceFlush(ctx)) |
| 575 |
spans := spanRecorder.Ended() |
| 576 |
tt.spansAssert(t, sc, spans) |
| 577 |
}) |
| 578 |
} |
| 579 |
} |
| 580 |
|
| 581 |
func TestSpanStatus(t *testing.T) { |
| 582 |
testCases := []struct { |
| 583 |
httpStatusCode int |
| 584 |
wantSpanStatus codes.Code |
| 585 |
}{ |
| 586 |
{http.StatusOK, codes.Unset}, |
| 587 |
{http.StatusBadRequest, codes.Unset}, |
| 588 |
{http.StatusInternalServerError, codes.Error}, |
| 589 |
} |
| 590 |
for _, tc := range testCases { |
| 591 |
t.Run(strconv.Itoa(tc.httpStatusCode), func(t *testing.T) { |
| 592 |
sr := tracetest.NewSpanRecorder() |
| 593 |
provider := sdktrace.NewTracerProvider() |
| 594 |
provider.RegisterSpanProcessor(sr) |
| 595 |
h := NewHandler( |
| 596 |
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 597 |
w.WriteHeader(tc.httpStatusCode) |
| 598 |
}), "test_handler", |
| 599 |
WithTracerProvider(provider), |
| 600 |
) |
| 601 |
|
| 602 |
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", http.NoBody)) |
| 603 |
|
| 604 |
require.Len(t, sr.Ended(), 1, "should emit a span") |
| 605 |
assert.Equal(t, tc.wantSpanStatus, sr.Ended()[0].Status().Code, "should only set Error status for HTTP statuses >= 500") |
| 606 |
}) |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
func TestHandlerWithMetricAttributesFn(t *testing.T) { |
| 611 |
const ( |
| 612 |
serverRequestSize = "http.server.request.size" |
| 613 |
serverResponseSize = "http.server.response.size" |
| 614 |
serverDuration = "http.server.duration" |
| 615 |
) |
| 616 |
testCases := []struct { |
| 617 |
name string |
| 618 |
fn func(r *http.Request) []attribute.KeyValue |
| 619 |
expectedAdditionalAttribute []attribute.KeyValue |
| 620 |
}{ |
| 621 |
{ |
| 622 |
name: "With a nil function", |
| 623 |
fn: nil, |
| 624 |
expectedAdditionalAttribute: []attribute.KeyValue{}, |
| 625 |
}, |
| 626 |
{ |
| 627 |
name: "With a function that returns an additional attribute", |
| 628 |
fn: func(*http.Request) []attribute.KeyValue { |
| 629 |
return []attribute.KeyValue{ |
| 630 |
attribute.String("fooKey", "fooValue"), |
| 631 |
attribute.String("barKey", "barValue"), |
| 632 |
} |
| 633 |
}, |
| 634 |
expectedAdditionalAttribute: []attribute.KeyValue{ |
| 635 |
attribute.String("fooKey", "fooValue"), |
| 636 |
attribute.String("barKey", "barValue"), |
| 637 |
}, |
| 638 |
}, |
| 639 |
} |
| 640 |
|
| 641 |
for _, tc := range testCases { |
| 642 |
reader := sdkmetric.NewManualReader() |
| 643 |
meterProvider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)) |
| 644 |
|
| 645 |
h := NewHandler( |
| 646 |
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 647 |
w.WriteHeader(http.StatusOK) |
| 648 |
}), "test_handler", |
| 649 |
WithMeterProvider(meterProvider), |
| 650 |
WithMetricAttributesFn(tc.fn), |
| 651 |
) |
| 652 |
|
| 653 |
r, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://localhost/", http.NoBody) |
| 654 |
require.NoError(t, err) |
| 655 |
rr := httptest.NewRecorder() |
| 656 |
h.ServeHTTP(rr, r) |
| 657 |
|
| 658 |
rm := metricdata.ResourceMetrics{} |
| 659 |
err = reader.Collect(t.Context(), &rm) |
| 660 |
require.NoError(t, err) |
| 661 |
require.Len(t, rm.ScopeMetrics, 1) |
| 662 |
assert.Len(t, rm.ScopeMetrics[0].Metrics, 3) |
| 663 |
|
| 664 |
// Verify that the additional attribute is present in the metrics. |
| 665 |
for _, m := range rm.ScopeMetrics[0].Metrics { |
| 666 |
switch m.Name { |
| 667 |
case serverRequestSize, serverResponseSize: |
| 668 |
d, ok := m.Data.(metricdata.Sum[int64]) |
| 669 |
assert.True(t, ok) |
| 670 |
assert.Len(t, d.DataPoints, 1) |
| 671 |
containsAttributes(t, d.DataPoints[0].Attributes, testCases[0].expectedAdditionalAttribute) |
| 672 |
case serverDuration: |
| 673 |
d, ok := m.Data.(metricdata.Histogram[float64]) |
| 674 |
assert.True(t, ok) |
| 675 |
assert.Len(t, d.DataPoints, 1) |
| 676 |
containsAttributes(t, d.DataPoints[0].Attributes, testCases[0].expectedAdditionalAttribute) |
| 677 |
} |
| 678 |
} |
| 679 |
} |
| 680 |
} |
| 681 |
|
| 682 |
func BenchmarkHandlerServeHTTP(b *testing.B) { |
| 683 |
tp := sdktrace.NewTracerProvider() |
| 684 |
mp := sdkmetric.NewMeterProvider() |
| 685 |
|
| 686 |
r, err := http.NewRequestWithContext(b.Context(), http.MethodGet, "http://localhost/", http.NoBody) |
| 687 |
require.NoError(b, err) |
| 688 |
|
| 689 |
for _, bb := range []struct { |
| 690 |
name string |
| 691 |
handler http.Handler |
| 692 |
}{ |
| 693 |
{ |
| 694 |
name: "without the otelhttp handler", |
| 695 |
handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 696 |
fmt.Fprint(w, "Hello World") |
| 697 |
}), |
| 698 |
}, |
| 699 |
{ |
| 700 |
name: "with the otelhttp handler", |
| 701 |
handler: NewHandler( |
| 702 |
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 703 |
fmt.Fprint(w, "Hello World") |
| 704 |
}), |
| 705 |
"test_handler", |
| 706 |
WithTracerProvider(tp), |
| 707 |
WithMeterProvider(mp), |
| 708 |
), |
| 709 |
}, |
| 710 |
} { |
| 711 |
b.Run(bb.name, func(b *testing.B) { |
| 712 |
rr := httptest.NewRecorder() |
| 713 |
|
| 714 |
b.ReportAllocs() |
| 715 |
b.ResetTimer() |
| 716 |
for range b.N { |
| 717 |
bb.handler.ServeHTTP(rr, r) |
| 718 |
} |
| 719 |
}) |
| 720 |
} |
| 721 |
} |