// Package internal wires HTTP routes, middleware and storage into one Fiber // application and owns the process-wide error handler. package internal import ( "errors" "time" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/chats" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/common" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/config" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/health" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/messages" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/session" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/store" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/users" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/middleware/recover" "github.com/gofiber/fiber/v3/middleware/requestid" "github.com/jackc/pgx/v5/pgxpool" ) func SignalGracefulShutdown() { health.SignalShutdown() } func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber.App { st := store.New(pool, cfg.DBTimeout, cfg.IdempotencyTTL) app := fiber.New(fiber.Config{ ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, BodyLimit: 1 * 1024 * 1024, ErrorHandler: handleError, }) app.Use(recover.New()) app.Use(requestid.New()) app.Use(func(c fiber.Ctx) error { c.Set("X-Instance-Id", cfg.InstanceID) return c.Next() }) health.RegisterRoutes(app.Group("/health"), st, sessions) api := app.Group("/api/v1") users.RegisterPublicRoutes(api, st) auth.RegisterPublicRoutes(api, st, sessions) protected := api.Group("") protected.Use(auth.BearerAuth(sessions)) auth.RegisterProtectedRoutes(protected, st, sessions) users.RegisterProtectedRoutes(protected, st) chats.RegisterProtectedRoutes(protected, st) messages.RegisterProtectedRoutes(protected, st) return app } func handleError(c fiber.Ctx, err error) error { if appErr, ok := errors.AsType[*common.AppError](err); ok { return common.SendError(c, appErr.Status, appErr.Code, appErr.Message) } if fiberErr, ok := errors.AsType[*fiber.Error](err); ok { return common.SendError(c, fiberErr.Code, common.ErrorCodeFromStatus(fiberErr.Code), fiberErr.Message) } return common.SendError(c, fiber.StatusInternalServerError, common.ErrorCodeInternal, "Internal server error") }