91 lines
2.9 KiB
Go
91 lines
2.9 KiB
Go
package rest
|
|
|
|
import (
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/propagation"
|
|
"go.opentelemetry.io/otel/trace"
|
|
|
|
"mtusi-messenger/internal/telemetry"
|
|
"mtusi-messenger/internal/transport/rest/internal/oas"
|
|
)
|
|
|
|
// telemetryMiddleware is the single source of HTTP spans, metrics and access
|
|
// logs. It resolves the OpenAPI template before the span is started: the
|
|
// generated ogen router does not set http.Request.Pattern for its routes.
|
|
func telemetryMiddleware(log *slog.Logger, server *oas.Server, mux *http.ServeMux, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
route, operation := resolveRoute(server, mux, r)
|
|
if strings.HasPrefix(route, "/health/") {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
|
method := normalizeMethod(r.Method)
|
|
started := time.Now()
|
|
ctx, span := otel.Tracer("messenger/http").Start(ctx, method+" "+route,
|
|
trace.WithSpanKind(trace.SpanKindServer),
|
|
trace.WithAttributes(
|
|
attribute.String("http.request.method", method),
|
|
attribute.String("http.route", route),
|
|
),
|
|
)
|
|
defer span.End()
|
|
|
|
writer := &statusWriter{ResponseWriter: w}
|
|
next.ServeHTTP(writer, r.WithContext(ctx))
|
|
|
|
status := writer.statusCode()
|
|
span.SetAttributes(attribute.Int("http.response.status_code", status))
|
|
if status >= http.StatusInternalServerError {
|
|
span.SetStatus(codes.Error, http.StatusText(status))
|
|
}
|
|
telemetry.RecordHTTP(ctx, method, route, status, time.Since(started))
|
|
|
|
attrs := []any{
|
|
slog.String("event", "http.request.completed"),
|
|
slog.String("operation", operation),
|
|
slog.String("route", route),
|
|
slog.String("method", method),
|
|
slog.Int("status", status),
|
|
slog.Duration("duration", time.Since(started)),
|
|
slog.String("request_id", requestIDFromContext(ctx)),
|
|
}
|
|
level := slog.LevelInfo
|
|
if status >= http.StatusInternalServerError {
|
|
level = slog.LevelError
|
|
} else if status >= http.StatusBadRequest {
|
|
level = slog.LevelWarn
|
|
}
|
|
log.Log(ctx, level, "http.request.completed", attrs...)
|
|
})
|
|
}
|
|
|
|
// normalizeMethod keeps the metric/span label set low-cardinality. Any method
|
|
// outside the standard set is deliberately collapsed to OTHER.
|
|
func normalizeMethod(method string) string {
|
|
switch method {
|
|
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead, http.MethodOptions:
|
|
return method
|
|
default:
|
|
return "OTHER"
|
|
}
|
|
}
|
|
|
|
func resolveRoute(server *oas.Server, mux *http.ServeMux, r *http.Request) (route, operation string) {
|
|
if route, ok := server.FindPath(r.Method, r.URL); ok {
|
|
return route.PathPattern(), route.OperationID()
|
|
}
|
|
if _, pattern := mux.Handler(r); pattern != "" && pattern != "/" {
|
|
return pattern, ""
|
|
}
|
|
return "unmatched", ""
|
|
}
|