Files
mtusi2026lab7/internal/transport/rest/telemetry.go
T
Vladislav Kunetskiy 3d216fbd50 База lab7: контракт 1.7.0 и реализация lab1–lab6
Перенесены cmd/internal/config, compose.yaml, Dockerfile, скрипты, student-tests и evidence из mtusi-messenger (master, lab6). Skeleton lab7 (openapi/infrastructure 1.7.0, trust-matrix.md, security/THREAT_MODEL.md, infra/openbao, tests/security.py) сохранён; make test-security добавлен в Makefile.
2026-11-09 13:03:49 +03:00

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", ""
}