оценка 4

This commit is contained in:
2026-10-23 16:20:43 +03:00
parent 34618bd423
commit 5300a1a1e0
18 changed files with 1861 additions and 29 deletions
@@ -0,0 +1,48 @@
package middleware
import (
"net/http"
"sync/atomic"
"mtusi2026lab3/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)
}
}