на оценку 4

This commit is contained in:
2026-11-22 23:33:11 +03:00
parent 20afc2c790
commit cc41f601e3
207 changed files with 22098 additions and 120 deletions
+113
View File
@@ -0,0 +1,113 @@
package middleware
import (
"context"
"errors"
"net/http"
"strings"
"mtusi2026lab7/internal/domain"
"mtusi2026lab7/internal/transport/http/response"
)
const bearerChallenge = `Bearer realm="messenger"`
const (
UserContextKey contextKey = "current_user"
sessionTokenHashKey contextKey = "session_token_hash"
)
type SessionAuthenticator interface {
Authenticate(
ctx context.Context,
token string,
) (domain.User, []byte, error)
}
func RequireAuth(
authenticator SessionAuthenticator,
next http.HandlerFunc,
) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
requestID := GetRequestID(r.Context())
token, ok := bearerToken(r.Header.Get("Authorization"))
if !ok {
writeBearerUnauthorized(w, requestID)
return
}
user, tokenHash, err := authenticator.Authenticate(
r.Context(),
token,
)
if errors.Is(err, domain.ErrNotFound) {
writeBearerUnauthorized(w, requestID)
return
}
if err != nil {
response.WriteError(
w,
http.StatusServiceUnavailable,
response.CodeUnavailable,
"service is temporarily unavailable",
requestID,
)
return
}
ctx := context.WithValue(
r.Context(),
UserContextKey,
user,
)
ctx = context.WithValue(
ctx,
sessionTokenHashKey,
tokenHash,
)
next(w, r.WithContext(ctx))
}
}
func GetCurrentUser(ctx context.Context) domain.User {
user, _ := ctx.Value(UserContextKey).(domain.User)
return user
}
func GetCurrentSessionTokenHash(ctx context.Context) []byte {
tokenHash, _ := ctx.Value(sessionTokenHashKey).([]byte)
result := make([]byte, len(tokenHash))
copy(result, tokenHash)
return result
}
func bearerToken(authorization string) (string, bool) {
parts := strings.Fields(authorization)
if len(parts) != 2 ||
!strings.EqualFold(parts[0], "Bearer") ||
parts[1] == "" {
return "", false
}
return parts[1], true
}
func writeBearerUnauthorized(
w http.ResponseWriter,
requestID string,
) {
w.Header().Set("WWW-Authenticate", bearerChallenge)
response.WriteError(
w,
http.StatusUnauthorized,
response.CodeUnauthorized,
"invalid or expired bearer token",
requestID,
)
}
@@ -0,0 +1,48 @@
package middleware
import (
"net/http"
"sync/atomic"
"mtusi2026lab7/internal/transport/http/response"
)
// AvailabilityGate lets a process reject new work before its HTTP listener is
// closed. Existing requests are still drained by http.Server.Shutdown.
type AvailabilityGate struct {
accepting atomic.Bool
}
func NewAvailabilityGate() *AvailabilityGate {
gate := &AvailabilityGate{}
gate.accepting.Store(true)
return gate
}
func (g *AvailabilityGate) BeginDrain() {
g.accepting.Store(false)
}
func (g *AvailabilityGate) IsAccepting() bool {
return g.accepting.Load()
}
func (g *AvailabilityGate) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Liveness deliberately stays available while the process drains. The
// readiness endpoint and all business traffic receive 503 immediately.
if g.IsAccepting() || r.URL.Path == "/health/live" {
next.ServeHTTP(w, r)
return
}
response.WriteError(
w,
http.StatusServiceUnavailable,
response.CodeUnavailable,
"service is draining",
GetRequestID(r.Context()),
)
})
}
@@ -0,0 +1,38 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestAvailabilityGateRejectsNewWorkWhileKeepingLiveness(t *testing.T) {
gate := NewAvailabilityGate()
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
handler := RequestID(gate.Middleware(next))
before := httptest.NewRecorder()
handler.ServeHTTP(before, httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil))
if before.Code != http.StatusNoContent {
t.Fatalf("before drain status = %d, want %d", before.Code, http.StatusNoContent)
}
gate.BeginDrain()
draining := httptest.NewRecorder()
handler.ServeHTTP(draining, httptest.NewRequest(http.MethodGet, "/health/ready", nil))
if draining.Code != http.StatusServiceUnavailable {
t.Fatalf("ready while draining status = %d, want %d", draining.Code, http.StatusServiceUnavailable)
}
if draining.Header().Get("X-Request-Id") == "" {
t.Fatal("draining response is missing X-Request-Id")
}
live := httptest.NewRecorder()
handler.ServeHTTP(live, httptest.NewRequest(http.MethodGet, "/health/live", nil))
if live.Code != http.StatusNoContent {
t.Fatalf("live while draining status = %d, want %d", live.Code, http.StatusNoContent)
}
}
@@ -0,0 +1,15 @@
package middleware
import "net/http"
const InstanceIDHeader = "X-Instance-Id"
// InstanceID identifies the process that actually produced the response.
// It must wrap recovery and routing so even errors, health checks and 404/405
// responses carry the same stable process identifier.
func InstanceID(instanceID string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(InstanceIDHeader, instanceID)
next.ServeHTTP(w, r)
})
}
@@ -0,0 +1,50 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestInstanceIDOnSuccessfulAndNotFoundResponses(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("GET /ok", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
handler := InstanceID("api-01", mux)
for _, test := range []struct {
path string
wantStatus int
}{
{path: "/ok", wantStatus: http.StatusNoContent},
{path: "/missing", wantStatus: http.StatusNotFound},
} {
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
if recorder.Code != test.wantStatus {
t.Fatalf("%s: got status %d, want %d", test.path, recorder.Code, test.wantStatus)
}
if got := recorder.Header().Get(InstanceIDHeader); got != "api-01" {
t.Fatalf("%s: got instance ID %q, want api-01", test.path, got)
}
}
}
func TestInstanceIDSurvivesRecoveredPanic(t *testing.T) {
panicking := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
panic("test panic")
})
handler := InstanceID("api-panic", Recovery(panicking))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/panic", nil))
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("got status %d, want 500", recorder.Code)
}
if got := recorder.Header().Get(InstanceIDHeader); got != "api-panic" {
t.Fatalf("got instance ID %q, want api-panic", got)
}
}
@@ -0,0 +1,106 @@
package middleware
import (
"fmt"
"net/http"
"strconv"
"strings"
"time"
apptelemetry "mtusi2026lab7/internal/telemetry"
"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"
)
type responseWriterInterceptor struct {
http.ResponseWriter
statusCode int
}
func (w *responseWriterInterceptor) WriteHeader(code int) {
w.statusCode = code
w.ResponseWriter.WriteHeader(code)
}
func Observability(runtime *apptelemetry.Runtime, next http.Handler) (http.Handler, error) {
requests, err := runtime.Meter.Int64Counter(
"messenger.http.server.requests",
metric.WithDescription("Number of completed HTTP requests"),
metric.WithUnit("{request}"),
)
if err != nil {
return nil, fmt.Errorf("create HTTP request counter: %w", err)
}
duration, err := runtime.Meter.Float64Histogram(
"messenger.http.server.duration",
metric.WithDescription("HTTP server request duration"),
metric.WithUnit("s"),
)
if err != nil {
return nil, fmt.Errorf("create HTTP duration histogram: %w", err)
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/health/") {
next.ServeHTTP(w, r)
return
}
start := time.Now()
parent := otel.GetTextMapPropagator().Extract(
r.Context(),
propagation.HeaderCarrier(r.Header),
)
ctx, span := runtime.Tracer.Start(
parent,
r.Method+" HTTP request",
trace.WithSpanKind(trace.SpanKindServer),
trace.WithAttributes(attribute.String("http.request.method", r.Method)),
)
defer span.End()
interceptor := &responseWriterInterceptor{
ResponseWriter: w,
statusCode: http.StatusOK,
}
observedRequest := r.WithContext(ctx)
next.ServeHTTP(interceptor, observedRequest)
route := observedRequest.Pattern
if route == "" {
route = "unmatched"
}
statusClass := strconv.Itoa(interceptor.statusCode/100) + "xx"
elapsed := time.Since(start)
labels := metric.WithAttributes(
attribute.String("method", r.Method),
attribute.String("route", route),
attribute.String("status_class", statusClass),
)
requests.Add(ctx, 1, labels)
duration.Record(ctx, elapsed.Seconds(), labels)
span.SetName(r.Method + " " + route)
span.SetAttributes(
attribute.String("http.route", route),
attribute.Int("http.response.status_code", interceptor.statusCode),
)
if interceptor.statusCode >= http.StatusInternalServerError {
span.SetStatus(codes.Error, "server error")
} else {
span.SetStatus(codes.Ok, "")
}
runtime.Logger.Info(ctx, "http_request_completed", apptelemetry.Fields{
"method": r.Method,
"route": route,
"status_code": interceptor.statusCode,
"status_class": statusClass,
"duration_ms": float64(elapsed.Microseconds()) / 1000,
"request_id": GetRequestID(ctx),
})
}), nil
}
@@ -0,0 +1,28 @@
package middleware
import (
"net/http"
"mtusi2026lab7/internal/transport/http/response"
)
// Recovery перехватывает панику и возвращает клиенту валидный JSON 500
func Recovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
reqID := GetRequestID(r.Context())
//из контракта: не раскрывать stack trace и внутренности
response.WriteError(
w,
http.StatusInternalServerError,
response.CodeInternalError,
"internal server error",
reqID,
)
}
}()
next.ServeHTTP(w, r)
})
}
@@ -0,0 +1,35 @@
package middleware
import (
"context"
"net/http"
"github.com/google/uuid"
)
type contextKey string
const RequestIDKey contextKey = "request_id"
// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа
func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqID := r.Header.Get("X-Request-Id")
if reqID == "" {
reqID = uuid.NewString()
}
w.Header().Set("X-Request-Id", reqID)
ctx := context.WithValue(r.Context(), RequestIDKey, reqID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// GetRequestID достает ID запроса из контекста
func GetRequestID(ctx context.Context) string {
if val, ok := ctx.Value(RequestIDKey).(string); ok {
return val
}
return uuid.NewString()
}