112 lines
4.1 KiB
Go
112 lines
4.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/metric"
|
|
"go.opentelemetry.io/otel/propagation"
|
|
"go.opentelemetry.io/otel/trace"
|
|
|
|
"github.com/charawein/mtusi2026lab6/internal/telemetry"
|
|
"github.com/charawein/mtusi2026lab6/internal/transport/httputil"
|
|
)
|
|
|
|
// statusRecorder запоминает код ответа и число байт тела.
|
|
type statusRecorder struct {
|
|
http.ResponseWriter
|
|
status int
|
|
bytes int64
|
|
}
|
|
|
|
func (r *statusRecorder) WriteHeader(code int) {
|
|
r.status = code
|
|
r.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
func (r *statusRecorder) Write(b []byte) (int, error) {
|
|
n, err := r.ResponseWriter.Write(b)
|
|
r.bytes += int64(n)
|
|
return n, err
|
|
}
|
|
|
|
// Unwrap даёт http.ResponseController доступ к исходному writer.
|
|
func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
|
|
|
|
// route — шаблон маршрута ServeMux без метода ("/api/v1/chats/{chat_id}/messages").
|
|
// ServeMux записывает его в r.Pattern того же *Request, поэтому читается после
|
|
// next.ServeHTTP. Неизвестный путь не попадает в метки как сырой URL.
|
|
func route(r *http.Request) string {
|
|
p := r.Pattern
|
|
if p == "" {
|
|
return "unmatched"
|
|
}
|
|
if i := strings.IndexByte(p, ' '); i >= 0 {
|
|
p = p[i+1:]
|
|
}
|
|
return p
|
|
}
|
|
|
|
func statusClass(code int) string { return fmt.Sprintf("%dxx", code/100) }
|
|
|
|
// Telemetry — server span на запрос и метрика http.server.request.duration
|
|
// (histogram, секунды; её _count — счётчик запросов). Метки: метод, шаблон
|
|
// маршрута, код и класс ответа — без user/chat/message ID и сырого URL.
|
|
func Telemetry(next http.Handler) http.Handler {
|
|
tracer := telemetry.Tracer()
|
|
meter := telemetry.Meter()
|
|
duration, _ := meter.Float64Histogram("http.server.request.duration",
|
|
metric.WithUnit("s"), metric.WithDescription("Duration of HTTP server requests"))
|
|
inflight, _ := meter.Int64UpDownCounter("http.server.active_requests",
|
|
metric.WithUnit("{request}"), metric.WithDescription("In-flight HTTP requests"))
|
|
prop := otel.GetTextMapPropagator()
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
ctx := prop.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
|
if strings.HasPrefix(r.URL.Path, "/health/") {
|
|
// Проверки LB раз в секунду: метрики пишем, трассы нет (ParentBased).
|
|
ctx = telemetry.Unsampled(r.Context())
|
|
}
|
|
ctx, span := tracer.Start(ctx, r.Method, trace.WithSpanKind(trace.SpanKindServer),
|
|
trace.WithAttributes(
|
|
attribute.String("http.request.method", r.Method),
|
|
attribute.String("request_id", httputil.RequestIDFrom(r.Context())),
|
|
))
|
|
defer span.End()
|
|
if sc := span.SpanContext(); sc.IsSampled() {
|
|
// W3C Trace Context Level 2: клиент (и тест) получает ID трассы своего запроса.
|
|
w.Header().Set("traceresponse", "00-"+sc.TraceID().String()+"-"+sc.SpanID().String()+"-01")
|
|
}
|
|
methodAttr := attribute.String("http.request.method", r.Method)
|
|
inflight.Add(ctx, 1, metric.WithAttributes(methodAttr))
|
|
defer inflight.Add(ctx, -1, metric.WithAttributes(methodAttr))
|
|
|
|
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
|
r2 := r.WithContext(ctx)
|
|
next.ServeHTTP(rec, r2)
|
|
|
|
rt := route(r2)
|
|
span.SetName(r.Method + " " + rt)
|
|
span.SetAttributes(
|
|
attribute.String("http.route", rt),
|
|
attribute.Int("http.response.status_code", rec.status),
|
|
)
|
|
if rec.status >= 500 {
|
|
span.SetStatus(codes.Error, http.StatusText(rec.status))
|
|
}
|
|
duration.Record(ctx, time.Since(start).Seconds(), metric.WithAttributes(
|
|
methodAttr,
|
|
attribute.String("http.route", rt),
|
|
attribute.Int("http.response.status_code", rec.status),
|
|
attribute.String("http.response.status_class", statusClass(rec.status)),
|
|
))
|
|
r.Pattern = r2.Pattern // для внешних middleware (логирование)
|
|
})
|
|
}
|