forked from mtusi2026/mtusi2026lab6
Реализовать наблюдаемость мессенджера для ЛР 6 на четыре
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Middleware struct {
|
||||
authService *service.AuthService
|
||||
instanceID string
|
||||
}
|
||||
|
||||
func NewMiddleware(authService *service.AuthService, instanceID string) *Middleware {
|
||||
|
||||
return &Middleware{
|
||||
authService: authService,
|
||||
instanceID: instanceID,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (m *Middleware) Auth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := RequestIDFromContext(r.Context())
|
||||
|
||||
token, ok := httputils.ExtractBearerToken(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := m.authService.ValidateSession(r.Context(), token)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := WithUserID(r.Context(), userID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Middleware) RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := uuid.NewString()
|
||||
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
|
||||
ctx := WithRequestID(r.Context(), requestID)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Middleware) InstanceID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", m.instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package middleware
|
||||
|
||||
import "context"
|
||||
|
||||
// UserID
|
||||
type contextKey string
|
||||
|
||||
const userIDKey contextKey = "userID"
|
||||
|
||||
func WithUserID(ctx context.Context, userID string) context.Context {
|
||||
return context.WithValue(ctx, userIDKey, userID)
|
||||
}
|
||||
|
||||
func UserIDFromContext(ctx context.Context) string {
|
||||
userID, _ := ctx.Value(userIDKey).(string)
|
||||
return userID
|
||||
}
|
||||
|
||||
// RequestIDKey
|
||||
const requestIDKey contextKey = "requestID"
|
||||
|
||||
func RequestIDFromContext(ctx context.Context) string {
|
||||
requestID, _ := ctx.Value(requestIDKey).(string)
|
||||
return requestID
|
||||
}
|
||||
|
||||
func WithRequestID(ctx context.Context, requestID string) context.Context {
|
||||
return context.WithValue(ctx, requestIDKey, requestID)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"highload/internal/observability"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
otellog "go.opentelemetry.io/otel/log"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type responseWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *responseWriter) WriteHeader(status int) {
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *responseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
|
||||
|
||||
func (m *Middleware) Logging(next http.Handler, routeFor func(*http.Request) string) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
method := "OTHER"
|
||||
switch r.Method {
|
||||
case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodDelete, http.MethodOptions:
|
||||
method = r.Method
|
||||
}
|
||||
route := routeFor(r)
|
||||
ctx := observability.WithRequestID(r.Context(), RequestIDFromContext(r.Context()))
|
||||
health := route == "/health/live" || route == "/health/ready"
|
||||
var span trace.Span
|
||||
if !health {
|
||||
ctx = observability.W3C.Extract(ctx, propagation.HeaderCarrier(r.Header))
|
||||
ctx, span = observability.Tracer.Start(ctx, method+" "+route, trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(attribute.String("http.request.method", method), attribute.String("http.route", route)))
|
||||
defer span.End()
|
||||
}
|
||||
rw := &responseWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rw, r.WithContext(ctx))
|
||||
elapsed := time.Since(start)
|
||||
observability.ObserveHTTP(ctx, method, route, rw.status, elapsed)
|
||||
if span != nil {
|
||||
level := otellog.SeverityInfo
|
||||
span.SetAttributes(attribute.Int("http.response.status_code", rw.status))
|
||||
if rw.status >= 500 {
|
||||
span.SetStatus(codes.Error, "server_error")
|
||||
level = otellog.SeverityError
|
||||
}
|
||||
observability.Log(ctx, "http.request", level, attribute.String("method", method),
|
||||
attribute.String("route", route), attribute.Int("status", rw.status),
|
||||
attribute.Float64("duration_seconds", elapsed.Seconds()))
|
||||
}
|
||||
slog.Info("http request", "method", method, "route", route, "status", rw.status,
|
||||
"duration", elapsed, "request_id", RequestIDFromContext(ctx))
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user