forked from mtusi2026/mtusi2026lab3
174 lines
4.7 KiB
Go
174 lines
4.7 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
nethttp "net/http"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
|
)
|
|
|
|
type Deps struct {
|
|
Config *config.Config
|
|
Logger *slog.Logger
|
|
Store store.Store
|
|
Auth service.AuthService
|
|
Users service.UsersService
|
|
Chats service.ChatsService
|
|
Messages service.MessagesService
|
|
|
|
Ready func(ctx context.Context) error
|
|
}
|
|
|
|
type Server struct {
|
|
e *echo.Echo
|
|
cfg config.HTTP
|
|
logger *slog.Logger
|
|
shutting atomic.Bool
|
|
ready func(ctx context.Context) error
|
|
}
|
|
|
|
func NewServer(d Deps) *Server {
|
|
s := &Server{
|
|
e: echo.New(),
|
|
cfg: d.Config.HTTP,
|
|
logger: d.Logger,
|
|
ready: d.Ready,
|
|
}
|
|
|
|
s.e.HideBanner = true
|
|
s.e.HidePort = true
|
|
s.e.HTTPErrorHandler = s.httpErrorHandler
|
|
|
|
s.e.Server.ReadTimeout = time.Duration(s.cfg.ReadTimeoutMs) * time.Millisecond
|
|
s.e.Server.WriteTimeout = time.Duration(s.cfg.WriteTimeoutMs) * time.Millisecond
|
|
s.e.Server.IdleTimeout = time.Duration(s.cfg.IdleTimeoutMs) * time.Millisecond
|
|
|
|
s.e.Use(middleware.InstanceID(d.Config.InstanceID))
|
|
s.e.Use(middleware.Recover(d.Logger))
|
|
s.e.Use(middleware.RequestID())
|
|
s.e.Use(middleware.Logger(d.Logger))
|
|
s.e.Use(middleware.InFlight(d.Config.Limits.MaxInFlight))
|
|
s.e.Use(middleware.BodyLimit(d.Config.Limits.MaxBodyBytes))
|
|
s.e.Use(middleware.MemoryGuard(d.Config.Limits.MaxHeapBytes, 100*time.Millisecond))
|
|
|
|
registerRoutes(s.e, d, s.IsReady)
|
|
return s
|
|
}
|
|
|
|
func (s *Server) Start() error {
|
|
s.logger.Info("http server starting", slog.String("addr", s.cfg.Addr))
|
|
err := s.e.Start(s.cfg.Addr)
|
|
if errors.Is(err, nethttp.ErrServerClosed) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
// Drain переводит readiness в 503 и ждёт d, продолжая обслуживать запросы: за это время
|
|
// балансировщик выводит реплику, и новые запросы не попадают на закрытый listener.
|
|
func (s *Server) Drain(d time.Duration) {
|
|
s.shutting.Store(true)
|
|
s.logger.Info("http server draining", slog.Duration("for", d))
|
|
time.Sleep(d)
|
|
}
|
|
|
|
func (s *Server) Shutdown(ctx context.Context) error {
|
|
s.shutting.Store(true)
|
|
s.logger.Info("http server shutting down")
|
|
return s.e.Shutdown(ctx)
|
|
}
|
|
|
|
func (s *Server) IsReady() bool {
|
|
if s.shutting.Load() {
|
|
return false
|
|
}
|
|
if s.ready == nil {
|
|
return true
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), readyTimeout)
|
|
defer cancel()
|
|
return s.ready(ctx) == nil
|
|
}
|
|
|
|
const readyTimeout = time.Second
|
|
|
|
func (s *Server) Handler() nethttp.Handler {
|
|
return s.e
|
|
}
|
|
|
|
func (s *Server) httpErrorHandler(err error, c echo.Context) {
|
|
if c.Response().Committed {
|
|
return
|
|
}
|
|
|
|
var httpErr *echo.HTTPError
|
|
if errors.As(err, &httpErr) {
|
|
code := codeFromStatus(httpErr.Code)
|
|
msg, _ := httpErr.Message.(string)
|
|
if msg == "" || msg == nethttp.StatusText(httpErr.Code) {
|
|
msg = messageFor(httpErr.Code, code)
|
|
}
|
|
_ = c.JSON(httpErr.Code, errorBody{
|
|
Error: errorPayload{
|
|
Code: code,
|
|
Message: msg,
|
|
RequestID: c.Response().Header().Get(echo.HeaderXRequestID),
|
|
},
|
|
})
|
|
return
|
|
}
|
|
|
|
_ = WriteError(c, err)
|
|
}
|
|
|
|
var codesByStatus = map[int]string{
|
|
nethttp.StatusBadRequest: CodeInvalidRequest,
|
|
nethttp.StatusUnauthorized: CodeUnauthorized,
|
|
nethttp.StatusNotFound: CodeNotFound,
|
|
nethttp.StatusMethodNotAllowed: CodeInvalidRequest,
|
|
nethttp.StatusConflict: CodeConflict,
|
|
nethttp.StatusRequestEntityTooLarge: CodePayloadTooLarge,
|
|
nethttp.StatusUnsupportedMediaType: CodeUnsupportedMedia,
|
|
nethttp.StatusTooManyRequests: CodeRateLimited,
|
|
nethttp.StatusServiceUnavailable: CodeUnavailable,
|
|
}
|
|
|
|
func codeFromStatus(status int) string {
|
|
if c, ok := codesByStatus[status]; ok {
|
|
return c
|
|
}
|
|
return CodeInternalError
|
|
}
|
|
|
|
var messagesByStatus = map[int]string{
|
|
nethttp.StatusMethodNotAllowed: "Method not allowed",
|
|
}
|
|
|
|
func messageFor(status int, code string) string {
|
|
if m, ok := messagesByStatus[status]; ok {
|
|
return m
|
|
}
|
|
return defaultMessages[code]
|
|
}
|
|
|
|
var defaultMessages = map[string]string{
|
|
CodeInvalidRequest: "Invalid request",
|
|
CodeUnauthorized: "Identification required",
|
|
CodeNotFound: "Object not found",
|
|
CodeConflict: "Conflict",
|
|
CodePayloadTooLarge: "Request body too large",
|
|
CodeUnsupportedMedia: "Unsupported Content-Type",
|
|
CodeRateLimited: "Too many requests",
|
|
CodeUnavailable: "Service unavailable",
|
|
CodeInternalError: "Internal server error",
|
|
}
|