Files
2026-11-06 19:06:21 +03:00

121 lines
4.4 KiB
Go
Executable File

// Package internal wires HTTP routes, middleware and storage into one Fiber
// application and owns the process-wide error handler.
package internal
import (
"errors"
"log/slog"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/attachments"
"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/objectstore"
"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 New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) (*fiber.App, error) {
st := store.New(pool, cfg.DBTimeout, cfg.IdempotencyTTL)
objects, err := objectstore.New(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
Bucket: cfg.S3Bucket,
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
})
if err != nil {
return nil, err
}
app := fiber.New(fiber.Config{
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
IdleTimeout: cfg.IdleTimeout,
// BodyLimit is the coarse HTTP envelope. The attachment handler and
// BindJSON enforce their own smaller budgets.
BodyLimit: cfg.HTTPBodyLimit,
// Without StreamRequestBody fasthttp buffers the entire body
// before the handler runs. Streaming lets the upload path copy in
// 32 KiB chunks and stops a 10 MiB body from becoming a per-request
// allocation even when the request is later rejected.
StreamRequestBody: true,
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()
})
healthHandler := health.NewHandler(st, sessions, objects)
healthRoutes := app.Group("/health")
healthRoutes.Get("/live", healthHandler.Live)
healthRoutes.Get("/ready", healthHandler.Ready)
authHandler := auth.NewHandler(st, sessions)
usersHandler := users.NewHandler(st, config.MaxJSONBodyBytes)
chatsHandler := chats.NewHandler(st, config.MaxJSONBodyBytes)
messagesHandler := messages.NewHandler(st, config.MaxJSONBodyBytes)
attachmentsHandler := attachments.NewHandler(
st,
objects,
attachments.NewValidator(cfg.MaxImagePixels, cfg.ImageDecodeBytes),
cfg.MaxUploadBytes,
cfg.UploadDrainLimit,
cfg.UploadTimeout,
cfg.DownloadTimeout,
cfg.UploadTempDir,
)
api := app.Group("/api/v1")
api.Post("/users", usersHandler.CreateUser)
api.Post("/auth/sessions", authHandler.CreateSession)
protected := api.Group("", auth.BearerAuth(sessions))
protected.Get("/users/me", usersHandler.GetCurrentUser)
protected.Delete("/auth/sessions/current", authHandler.RevokeSession)
protected.Get("/chats", chatsHandler.ListChats)
protected.Post("/chats", chatsHandler.CreateChat)
protected.Get("/chats/:chat_id", chatsHandler.GetChat)
protected.Get("/chats/:chat_id/messages", messagesHandler.ListMessages)
protected.Post("/chats/:chat_id/messages", messagesHandler.CreateMessage)
protected.Post("/chats/:chat_id/attachments", attachmentsHandler.Upload)
protected.Get("/attachments/:attachment_id", attachmentsHandler.Get)
protected.Get("/attachments/:attachment_id/content", attachmentsHandler.Download)
return app, nil
}
// handleError is the only writer of error responses: handlers and the store
// return *common.AppError and this function decides status, headers and body.
func handleError(c fiber.Ctx, err error) error {
if appErr, ok := errors.AsType[*common.AppError](err); ok {
if appErr.Challenge != "" {
c.Set(fiber.HeaderWWWAuthenticate, appErr.Challenge)
}
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)
}
slog.Error("unhandled request error",
"request_id", requestid.FromContext(c), "err", err)
return common.SendError(c, fiber.StatusInternalServerError,
common.ErrorCodeInternal, "Internal server error")
}