This commit is contained in:
Vladislav Kunetskiy
2026-11-05 20:33:41 +03:00
parent edc2a405ee
commit 147fed2d97
194 changed files with 10062 additions and 3831 deletions
-3
View File
@@ -81,8 +81,6 @@ func (e *Extensions) route(method, operation string, handler extensionHandler) h
slog.String("request_id", requestIDFromContext(r.Context())),
slog.String("operation", operation),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.String("user_id", userID.String()),
slog.Int("status", writer.statusCode()),
slog.Duration("duration", time.Since(started)),
)
@@ -205,7 +203,6 @@ func (e *Extensions) fail(w http.ResponseWriter, r *http.Request, err error) {
e.log.ErrorContext(r.Context(), "extension request failed",
slog.String("request_id", requestIDFromContext(r.Context())),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Any("error", err),
)
}
-1
View File
@@ -75,7 +75,6 @@ func logRejected(ctx context.Context, log *slog.Logger, r *http.Request, status
attrs := []any{
slog.String("request_id", requestIDFromContext(ctx)),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status", status),
}
+4 -1
View File
@@ -3,12 +3,15 @@ package rest
import (
"context"
"net/http"
"regexp"
"github.com/google/uuid"
)
const requestIDHeader = "X-Request-ID"
var requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
type requestIDKey struct{}
func requestIDFromContext(ctx context.Context) string {
@@ -24,7 +27,7 @@ func withRequestID(ctx context.Context, id string) context.Context {
func requestIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get(requestIDHeader)
if id == "" {
if !requestIDPattern.MatchString(id) {
id = uuid.NewString()
}
+3 -2
View File
@@ -20,7 +20,6 @@ func NewRouter(
oas.WithErrorHandler(newErrorHandler(log)),
oas.WithNotFound(newNotFoundHandler(log)),
oas.WithMethodNotAllowed(newMethodNotAllowedHandler(log)),
oas.WithMiddleware(loggingMiddleware(log)),
)
if err != nil {
return nil, err
@@ -38,7 +37,9 @@ func NewRouter(
mux.Handle("/", server)
limited := bodyLimitMiddleware(maxBodyBytes, maxUploadBytes, log, mux)
return requestIDMiddleware(
instanceIDMiddleware(InstanceID(), bodyLimitMiddleware(maxBodyBytes, maxUploadBytes, log, mux)),
instanceIDMiddleware(InstanceID(), telemetryMiddleware(log, server, mux, limited)),
), nil
}
+90
View File
@@ -0,0 +1,90 @@
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", ""
}