ЛР 5: асинхронная обработка изображений, уровень 5

This commit is contained in:
Nurlygayanova Ekaterina
2026-11-12 20:32:55 +03:00
parent 276dbdad8a
commit 7b3eab5473
115 changed files with 8847 additions and 34 deletions
+61
View File
@@ -0,0 +1,61 @@
package middleware
import (
"context"
"errors"
"net/http"
"strings"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"github.com/labstack/echo/v4"
)
const AuthTokenKey = "auth_token"
const (
BearerChallenge = `Bearer realm="messenger"`
BasicChallenge = `Basic realm="messenger", charset="UTF-8"`
)
type Authenticator interface {
Authenticate(ctx context.Context, token string) (userID string, err error)
}
func Bearer(auth Authenticator) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
tok, ok := BearerToken(c.Request().Header.Get(echo.HeaderAuthorization))
if !ok {
return unauthorized(c, BearerChallenge, "Bearer token required")
}
userID, err := auth.Authenticate(c.Request().Context(), tok)
if err != nil {
if errors.Is(err, domain.ErrUnauthorized) {
return unauthorized(c, BearerChallenge, "Invalid or expired session")
}
return err
}
c.Set(AuthUserIDKey, userID)
c.Set(AuthTokenKey, tok)
return next(c)
}
}
}
func BearerToken(header string) (string, bool) {
scheme, tok, found := strings.Cut(header, " ")
if !found || !strings.EqualFold(scheme, "Bearer") {
return "", false
}
tok = strings.TrimSpace(tok)
return tok, tok != ""
}
func unauthorized(c echo.Context, challenge, msg string) error {
c.Response().Header().Set(echo.HeaderWWWAuthenticate, challenge)
return echo.NewHTTPError(http.StatusUnauthorized, msg)
}
func Unauthorized(c echo.Context, challenge, msg string) error {
return unauthorized(c, challenge, msg)
}
@@ -0,0 +1,42 @@
package middleware
import (
"mime"
"net/http"
"strings"
"github.com/labstack/echo/v4"
)
func ContentType() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !methodHasBody(c.Request().Method) {
return next(c)
}
if !isApplicationJSON(c.Request().Header.Get(echo.HeaderContentType)) {
return echo.NewHTTPError(http.StatusUnsupportedMediaType, "Expected Content-Type: application/json")
}
return next(c)
}
}
}
func methodHasBody(method string) bool {
switch method {
case http.MethodPost, http.MethodPut, http.MethodPatch:
return true
}
return false
}
func isApplicationJSON(ct string) bool {
if ct == "" {
return false
}
mediatype, _, err := mime.ParseMediaType(ct)
if err != nil {
return false
}
return strings.EqualFold(mediatype, "application/json")
}
@@ -0,0 +1,14 @@
package middleware
import "github.com/labstack/echo/v4"
const HeaderInstanceID = "X-Instance-Id"
func InstanceID(id string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Response().Header().Set(HeaderInstanceID, id)
return next(c)
}
}
}
+112
View File
@@ -0,0 +1,112 @@
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"
}
@@ -0,0 +1,48 @@
package middleware
import (
"log/slog"
"time"
"github.com/labstack/echo/v4"
)
const AuthUserIDKey = "caller_id"
func Logger(logger *slog.Logger) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
start := time.Now()
if err := next(c); err != nil {
c.Error(err)
}
status := c.Response().Status
rid, _ := c.Get(RequestIDKey).(string)
uid, _ := c.Get(AuthUserIDKey).(string)
attrs := []slog.Attr{
slog.String("request_id", rid),
slog.String("method", c.Request().Method),
slog.String("path", c.Request().URL.Path),
slog.Int("status", status),
slog.Int64("duration_ms", time.Since(start).Milliseconds()),
slog.String("remote_ip", c.RealIP()),
}
if uid != "" {
attrs = append(attrs, slog.String("user_id", uid))
}
level := slog.LevelInfo
switch {
case status >= 500:
level = slog.LevelError
case status >= 400:
level = slog.LevelWarn
}
logger.LogAttrs(c.Request().Context(), level, "http request", attrs...)
return nil
}
}
}
@@ -0,0 +1,32 @@
package middleware
import (
"log/slog"
"net/http"
"runtime/debug"
"github.com/labstack/echo/v4"
)
func Recover(logger *slog.Logger) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
defer func() {
r := recover()
if r == nil {
return
}
rid, _ := c.Get(RequestIDKey).(string)
logger.Error("panic recovered",
slog.String("request_id", rid),
slog.String("method", c.Request().Method),
slog.String("path", c.Request().URL.Path),
slog.Any("panic", r),
slog.String("stack", string(debug.Stack())),
)
err = echo.NewHTTPError(http.StatusInternalServerError, "Internal server error")
}()
return next(c)
}
}
}
@@ -0,0 +1,22 @@
package middleware
import (
"github.com/google/uuid"
"github.com/labstack/echo/v4"
)
const RequestIDKey = "request_id"
func RequestID() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
rid := c.Request().Header.Get(echo.HeaderXRequestID)
if rid == "" {
rid = uuid.NewString()
}
c.Response().Header().Set(echo.HeaderXRequestID, rid)
c.Set(RequestIDKey, rid)
return next(c)
}
}
}