forked from mtusi2026/mtusi2026lab2
111 lines
2.2 KiB
Go
111 lines
2.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"io"
|
|
"runtime"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
|
)
|
|
|
|
func BodyLimit(maxBytes int64) echo.MiddlewareFunc {
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
if !methodHasBody(c.Request().Method) {
|
|
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"
|
|
}
|