forked from mtusi2026/mtusi2026lab2
79 lines
2.0 KiB
Go
79 lines
2.0 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
// gate ограничивает одновременную обработку запросов API: не больше inflight
|
|
// в работе и не больше queue в ожидании слота. Лишние сразу получают 503 с
|
|
// Retry-After, ждавшие дольше timeout — тоже 503. Так перегрузка превращается
|
|
// в быстрый предсказуемый отказ, а не в рост горутин, памяти и задержки.
|
|
type gate struct {
|
|
slots chan struct{} // nil — без лимита
|
|
maxQueue int64
|
|
timeout time.Duration
|
|
waiting atomic.Int64
|
|
rejected atomic.Int64
|
|
}
|
|
|
|
func newGate(inflight, queue int, timeout time.Duration) *gate {
|
|
g := &gate{maxQueue: int64(queue), timeout: timeout}
|
|
if inflight > 0 {
|
|
g.slots = make(chan struct{}, inflight)
|
|
}
|
|
return g
|
|
}
|
|
|
|
func (g *gate) middleware(reject func(http.ResponseWriter, *http.Request, error)) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if g.slots == nil {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
if !g.acquire(r) {
|
|
g.rejected.Add(1)
|
|
reject(w, r, errOverloaded)
|
|
return
|
|
}
|
|
defer func() { <-g.slots }()
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|
|
|
|
func (g *gate) acquire(r *http.Request) bool {
|
|
select {
|
|
case g.slots <- struct{}{}:
|
|
return true
|
|
default:
|
|
}
|
|
if g.waiting.Add(1) > g.maxQueue {
|
|
g.waiting.Add(-1)
|
|
return false
|
|
}
|
|
defer g.waiting.Add(-1)
|
|
timer := time.NewTimer(g.timeout)
|
|
defer timer.Stop()
|
|
select {
|
|
case g.slots <- struct{}{}:
|
|
return true
|
|
case <-timer.C:
|
|
return false
|
|
case <-r.Context().Done():
|
|
return false
|
|
}
|
|
}
|
|
|
|
type gateStats struct {
|
|
Inflight int `json:"inflight"`
|
|
Waiting int64 `json:"waiting"`
|
|
Rejected int64 `json:"rejected"`
|
|
}
|
|
|
|
func (g *gate) stats() gateStats {
|
|
return gateStats{Inflight: len(g.slots), Waiting: g.waiting.Load(), Rejected: g.rejected.Load()}
|
|
}
|