Files
mtusi2026lab5/app/internal/api/http/middleware/limits.go
T

113 lines
2.4 KiB
Go

package middleware
import (
"io"
"runtime"
"slices"
"sync/atomic"
"time"
"github.com/labstack/echo/v4"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
)
// BodyLimit ограничивает тело запроса. Маршруты из exemptRoutes применяют собственный лимит.
func BodyLimit(maxBytes int64, exemptRoutes ...string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !methodHasBody(c.Request().Method) || slices.Contains(exemptRoutes, c.Path()) {
return next(c)
}
if cl := c.Request().ContentLength; cl > maxBytes {
return domain.ErrPayloadTooLarge
}
c.Request().Body = &limitedBody{
raw: c.Request().Body,
maxLeft: maxBytes,
}
return next(c)
}
}
}
type limitedBody struct {
raw io.ReadCloser
maxLeft int64
}
func (b *limitedBody) Read(p []byte) (int, error) {
if int64(len(p)) > b.maxLeft+1 {
p = p[:b.maxLeft+1]
}
n, err := b.raw.Read(p)
b.maxLeft -= int64(n)
if b.maxLeft < 0 {
return n, domain.ErrPayloadTooLarge
}
return n, err
}
func (b *limitedBody) Close() error {
return b.raw.Close()
}
func InFlight(maxInFlight int) echo.MiddlewareFunc {
sem := make(chan struct{}, maxInFlight)
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if isHealthPath(c.Request().URL.Path) {
return next(c)
}
select {
case sem <- struct{}{}:
defer func() { <-sem }()
return next(c)
default:
return domain.ErrRateLimited
}
}
}
}
func MemoryGuard(maxHeapBytes uint64, poll time.Duration) echo.MiddlewareFunc {
var sample atomic.Uint64
readOnce := func() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
if m.HeapInuse > maxHeapBytes {
runtime.GC()
runtime.ReadMemStats(&m)
}
sample.Store(m.HeapInuse)
}
readOnce()
if poll > 0 {
go func() {
t := time.NewTicker(poll)
defer t.Stop()
for range t.C {
readOnce()
}
}()
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !methodHasBody(c.Request().Method) || isHealthPath(c.Request().URL.Path) {
return next(c)
}
if sample.Load() > maxHeapBytes {
return domain.ErrUnavailable
}
return next(c)
}
}
}
func isHealthPath(path string) bool {
return path == "/health/live" || path == "/health/ready"
}