diff --git a/.dockerignore b/.dockerignore index 10b156a..c94e763 100644 --- a/.dockerignore +++ b/.dockerignore @@ -19,3 +19,4 @@ node_modules evidence .DS_Store app/tmp +app/server diff --git a/.env.example b/.env.example index 7b0a391..5ac5780 100644 --- a/.env.example +++ b/.env.example @@ -20,6 +20,8 @@ LB_PORT=8080 HAPROXY_STATS_PORT=8404 # Per-replica and other services' resource limits. +# API_REPLICAS must stay within the 16 backend slots declared by +# server-template in infra/haproxy/haproxy.cfg. API_REPLICAS=2 API_CPU_LIMIT=0.50 API_MEM_LIMIT=256M diff --git a/REPORT.md b/REPORT.md index 88c39c8..8daf51b 100644 --- a/REPORT.md +++ b/REPORT.md @@ -22,10 +22,8 @@ - подготовлен профиль k6 для проверки rolling update под нагрузкой. Обязательный контракт, `lab.json` и публичные тесты не изменялись. Существующие -неочевидные решения отмечены в коде комментариями `AGENT:`; перечень файлов -для их проверки и удаления находится в `LEFT_TO_REVIEW.md`. Новые комментарии -`AGENT:` в этой итерации не добавлялись: изменения и их обоснование записаны в -`CHANGELOG.md`. +неочевидные решения отмечены в коде комментариями `AGENT:`; изменения и их +обоснование записаны в `CHANGELOG.md`. ## 2. Запуск из чистого clone @@ -85,7 +83,7 @@ docker compose --env-file .env down -v │ HTTP :8080 ▼ HAProxy ── readiness /health/ready, retries, stats :8404, Prometheus /metrics - │ Docker DNS, server-template api 1..4 + │ Docker DNS, server-template api 1..16 ├──────────────┐ ▼ ▼ API-1 API-2 ... API-N (Go/Fiber, без публикации портов) @@ -102,7 +100,7 @@ migrate — one-shot, RUN_MIGRATIONS / MIGRATE_ONLY | Компонент | Роль | Решение | | --- | --- | --- | -| `haproxy` | LB и публичная точка входа | `server-template api 4 api:8080 resolvers docker`; health check `/health/ready` каждые 1 с, `fall 2` | +| `haproxy` | LB и публичная точка входа | `server-template api 16 api:8080 resolvers docker`; health check `/health/ready` каждые 1 с, `fall 2` | | `api` | бизнес-API | `deploy.replicas: ${API_REPLICAS:-2}`, `expose: 8080`, без `ports` | | `migrate` | миграции | тот же образ, `MIGRATE_ONLY=true`, `restart: "no"` | | `postgres` | источник истины | named volume `pgdata`, healthcheck, версия 16.10 | @@ -165,7 +163,8 @@ hostname процесса. В Compose hostname уникален для конт ### 3.5. HAProxy и graceful shutdown -- backend discovery: Docker DNS `127.0.0.11:53`, `server-template api 4`, поэтому +- backend discovery: Docker DNS `127.0.0.11:53`, `server-template api 16` (запас + на 16 реплик — больше, чем разумный `API_REPLICAS`), поэтому `docker compose up --scale api=N` не требует правки конфига; - health check: `GET /health/ready`, `inter 1s`, `fall 2` — обнаружение отказа около 2 секунд (при бюджете 10 секунд); diff --git a/app/cmd/server/main.go b/app/cmd/server/main.go index cff545e..9ec872a 100755 --- a/app/cmd/server/main.go +++ b/app/cmd/server/main.go @@ -13,6 +13,7 @@ import ( "gitflic.ru/project/bulla-max/mtusi2026lab/internal" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/config" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/database" + "gitflic.ru/project/bulla-max/mtusi2026lab/internal/health" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/session" ) @@ -32,10 +33,7 @@ func main() { defer pool.Close() if cfg.MigrateOnly || cfg.RunMigrations { - migrateCtx, cancelMigrate := context.WithTimeout(rootCtx, 60*time.Second) - err = database.Migrate(migrateCtx, pool, cfg.DatabaseURL) - cancelMigrate() - if err != nil { + if err = database.Migrate(cfg.DatabaseURL); err != nil { log.Fatalf("migrations: %v", err) } } @@ -68,7 +66,7 @@ func main() { } log.Printf("shutting down") - internal.SignalGracefulShutdown() + health.SignalShutdown() if err = app.ShutdownWithTimeout(10 * time.Second); err != nil { log.Printf("shutdown: %v", err) } diff --git a/app/internal/app.go b/app/internal/app.go index 815e468..4d3a0c2 100755 --- a/app/internal/app.go +++ b/app/internal/app.go @@ -4,6 +4,7 @@ package internal import ( "errors" + "log/slog" "time" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth" @@ -21,10 +22,6 @@ import ( "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) @@ -43,24 +40,39 @@ func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber. return c.Next() }) - health.RegisterRoutes(app.Group("/health"), st, sessions) + healthHandler := health.NewHandler(st, sessions) + healthRoutes := app.Group("/health") + healthRoutes.Get("/live", healthHandler.Live) + healthRoutes.Get("/ready", healthHandler.Ready) + + authHandler := auth.NewHandler(st, sessions) + usersHandler := users.NewHandler(st) + chatsHandler := chats.NewHandler(st) + messagesHandler := messages.NewHandler(st) api := app.Group("/api/v1") - users.RegisterPublicRoutes(api, st) - auth.RegisterPublicRoutes(api, st, sessions) + api.Post("/users", usersHandler.CreateUser) + api.Post("/auth/sessions", authHandler.CreateSession) - 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) + 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) return app } +// 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) } @@ -69,6 +81,8 @@ func handleError(c fiber.Ctx, err error) error { 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") } diff --git a/app/internal/auth/handler.go b/app/internal/auth/handler.go index df17d5c..c0383fd 100644 --- a/app/internal/auth/handler.go +++ b/app/internal/auth/handler.go @@ -5,6 +5,7 @@ package auth import ( "encoding/base64" "errors" + "log/slog" "strings" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/common" @@ -12,7 +13,6 @@ import ( "gitflic.ru/project/bulla-max/mtusi2026lab/internal/session" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/store" "github.com/gofiber/fiber/v3" - "github.com/gofiber/fiber/v3/log" ) const ( @@ -32,7 +32,7 @@ func NewHandler(st *store.Store, sessions *session.Store) *Handler { func (h *Handler) CreateSession(c fiber.Ctx) error { username, password, ok := parseBasic(c.Get(fiber.HeaderAuthorization)) if !ok { - return common.SendChallenge(c, basicChallenge, "invalid credentials") + return common.NewChallenge(basicChallenge, "invalid credentials") } user, err := h.store.GetUserByUsername(c.Context(), username) @@ -43,21 +43,20 @@ func (h *Handler) CreateSession(c fiber.Ctx) error { // therefore take different time, so username enumeration through // response timing is theoretically possible. The contract only // requires the same 401 body and challenge. - return common.SendChallenge(c, basicChallenge, "invalid credentials") + return common.NewChallenge(basicChallenge, "invalid credentials") } - return common.SendAppError(c, err) + return err } valid, err := VerifyPassword(user.PasswordHash, password) if err != nil || !valid { - return common.SendChallenge(c, basicChallenge, "invalid credentials") + return common.NewChallenge(basicChallenge, "invalid credentials") } token, expiresAt, err := h.sessions.Create(c.Context(), user.ID) if err != nil { - log.Errorf("create session: %v", err) - return common.SendError(c, fiber.StatusServiceUnavailable, - common.ErrorCodeUnavailable, "session store unavailable") + slog.Error("create session", "err", err) + return common.Unavailable("session store unavailable") } return c.Status(fiber.StatusCreated).JSON(model.Session{ @@ -71,13 +70,12 @@ func (h *Handler) CreateSession(c fiber.Ctx) error { func (h *Handler) RevokeSession(c fiber.Ctx) error { token, ok := common.SessionToken(c) if !ok { - return common.SendChallenge(c, bearerChallenge, "authentication required") + return common.NewChallenge(bearerChallenge, "authentication required") } if err := h.sessions.Revoke(c.Context(), token); err != nil { - log.Errorf("revoke session: %v", err) - return common.SendError(c, fiber.StatusServiceUnavailable, - common.ErrorCodeUnavailable, "session store unavailable") + slog.Error("revoke session", "err", err) + return common.Unavailable("session store unavailable") } return c.SendStatus(fiber.StatusNoContent) @@ -89,17 +87,16 @@ func BearerAuth(sessions *session.Store) fiber.Handler { scheme, token, found := strings.Cut(header, " ") token = strings.TrimSpace(token) if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t") { - return common.SendChallenge(c, bearerChallenge, "authentication required") + return common.NewChallenge(bearerChallenge, "authentication required") } userID, err := sessions.Lookup(c.Context(), token) if err != nil { if errors.Is(err, session.ErrNotFound) { - return common.SendChallenge(c, bearerChallenge, "session expired or revoked") + return common.NewChallenge(bearerChallenge, "session expired or revoked") } - log.Errorf("session lookup: %v", err) - return common.SendError(c, fiber.StatusServiceUnavailable, - common.ErrorCodeUnavailable, "session store unavailable") + slog.Error("session lookup", "err", err) + return common.Unavailable("session store unavailable") } c.Locals(common.KeyUserID, userID) diff --git a/app/internal/auth/router.go b/app/internal/auth/router.go deleted file mode 100644 index f0479c6..0000000 --- a/app/internal/auth/router.go +++ /dev/null @@ -1,17 +0,0 @@ -package auth - -import ( - "gitflic.ru/project/bulla-max/mtusi2026lab/internal/session" - "gitflic.ru/project/bulla-max/mtusi2026lab/internal/store" - "github.com/gofiber/fiber/v3" -) - -func RegisterPublicRoutes(router fiber.Router, st *store.Store, sessions *session.Store) { - handler := NewHandler(st, sessions) - router.Post("/auth/sessions", handler.CreateSession) -} - -func RegisterProtectedRoutes(router fiber.Router, st *store.Store, sessions *session.Store) { - handler := NewHandler(st, sessions) - router.Delete("/auth/sessions/current", handler.RevokeSession) -} diff --git a/app/internal/chats/handler.go b/app/internal/chats/handler.go index 7722510..a791fdf 100644 --- a/app/internal/chats/handler.go +++ b/app/internal/chats/handler.go @@ -26,19 +26,19 @@ func (h *Handler) CreateChat(c fiber.Ctx) error { var req CreateChatRequest if err := common.BindJSON(c, &req); err != nil { - return common.SendAppError(c, err) + return err } - if msg := common.ValidateChatTitle(req.Title); msg != "" { - return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg) + if err := common.ValidateChatTitle(req.Title); err != nil { + return err } - if msg := common.ValidateMemberIDs(req.MemberIDs, userID); msg != "" { - return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg) + if err := common.ValidateMemberIDs(req.MemberIDs, userID); err != nil { + return err } chat, err := h.store.CreateChat(c.Context(), req.Title, req.MemberIDs) if err != nil { - return common.SendAppError(c, err) + return err } return c.Status(fiber.StatusCreated).JSON(chat) @@ -49,21 +49,20 @@ func (h *Handler) ListChats(c fiber.Ctx) error { limit, err := common.ParseLimit(c, 50) if err != nil { - return common.SendAppError(c, err) + return err } cursor, err := common.ParseCursor(c) if err != nil { - return common.SendAppError(c, err) + return err } if cursor != nil && cursor.ContextID != userID { - return common.SendError(c, fiber.StatusBadRequest, - common.ErrorCodeInvalidRequest, "bad cursor value") + return common.BadRequest("bad cursor value") } page, err := h.store.ListChats(c.Context(), userID, limit, cursor) if err != nil { - return common.SendAppError(c, err) + return err } return c.JSON(page) @@ -72,15 +71,14 @@ func (h *Handler) ListChats(c fiber.Ctx) error { func (h *Handler) GetChat(c fiber.Ctx) error { userID := common.MustUserID(c) - chatID, err := uuid.Parse(c.Params("chat_id")) + chatID, err := common.PathUUID(c, "chat_id") if err != nil { - return common.SendError(c, fiber.StatusBadRequest, - common.ErrorCodeInvalidRequest, "invalid chat_id format") + return err } chat, err := h.store.GetChatForUser(c.Context(), userID, chatID) if err != nil { - return common.SendAppError(c, err) + return err } return c.JSON(chat) diff --git a/app/internal/chats/router.go b/app/internal/chats/router.go deleted file mode 100644 index 0ada603..0000000 --- a/app/internal/chats/router.go +++ /dev/null @@ -1,13 +0,0 @@ -package chats - -import ( - "gitflic.ru/project/bulla-max/mtusi2026lab/internal/store" - "github.com/gofiber/fiber/v3" -) - -func RegisterProtectedRoutes(router fiber.Router, st *store.Store) { - handler := NewHandler(st) - router.Post("/chats", handler.CreateChat) - router.Get("/chats", handler.ListChats) - router.Get("/chats/:chat_id", handler.GetChat) -} diff --git a/app/internal/common/error.go b/app/internal/common/error.go index a7d1d69..817bad0 100644 --- a/app/internal/common/error.go +++ b/app/internal/common/error.go @@ -4,6 +4,7 @@ package common import ( "errors" + "net/http" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/middleware/requestid" @@ -41,10 +42,13 @@ func NewError(code, message, requestID string) APIErrorResponse { } } +// AppError is the single contract error type. Handlers and the store return it; +// the Fiber error handler is the only place that turns it into a response. type AppError struct { - Status int - Code string - Message string + Status int + Code string + Message string + Challenge string // WWW-Authenticate value, set for 401 responses } func (e *AppError) Error() string { @@ -60,31 +64,37 @@ func NewAppError(status int, code, message string) *AppError { } func BadRequest(message string) *AppError { - return NewAppError(fiber.StatusBadRequest, ErrorCodeInvalidRequest, message) -} - -func Unauthorized(message string) *AppError { - return NewAppError(fiber.StatusUnauthorized, ErrorCodeUnauthorized, message) + return NewAppError(http.StatusBadRequest, ErrorCodeInvalidRequest, message) } func NotFound(message string) *AppError { - return NewAppError(fiber.StatusNotFound, ErrorCodeNotFound, message) + return NewAppError(http.StatusNotFound, ErrorCodeNotFound, message) } func Conflict(message string) *AppError { - return NewAppError(fiber.StatusConflict, ErrorCodeConflict, message) + return NewAppError(http.StatusConflict, ErrorCodeConflict, message) } func UnsupportedMedia(message string) *AppError { - return NewAppError(fiber.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message) + return NewAppError(http.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message) } func Internal() *AppError { - return NewAppError(fiber.StatusInternalServerError, ErrorCodeInternal, "Internal server error") + return NewAppError(http.StatusInternalServerError, ErrorCodeInternal, "Internal server error") } func Unavailable(message string) *AppError { - return NewAppError(fiber.StatusServiceUnavailable, ErrorCodeUnavailable, message) + return NewAppError(http.StatusServiceUnavailable, ErrorCodeUnavailable, message) +} + +// NewChallenge builds the 401 that carries a WWW-Authenticate header. +func NewChallenge(challenge, message string) *AppError { + return &AppError{ + Status: http.StatusUnauthorized, + Code: ErrorCodeUnauthorized, + Message: message, + Challenge: challenge, + } } // IsCode reports whether err is an AppError with the given contract code. @@ -95,21 +105,21 @@ func IsCode(err error, code string) bool { func ErrorCodeFromStatus(status int) string { switch status { - case fiber.StatusBadRequest: + case http.StatusBadRequest: return ErrorCodeInvalidRequest - case fiber.StatusUnauthorized: + case http.StatusUnauthorized: return ErrorCodeUnauthorized - case fiber.StatusNotFound: + case http.StatusNotFound: return ErrorCodeNotFound - case fiber.StatusConflict: + case http.StatusConflict: return ErrorCodeConflict - case fiber.StatusRequestEntityTooLarge: + case http.StatusRequestEntityTooLarge: return ErrorCodePayloadTooLarge - case fiber.StatusUnsupportedMediaType: + case http.StatusUnsupportedMediaType: return ErrorCodeUnsupportedMedia - case fiber.StatusTooManyRequests: + case http.StatusTooManyRequests: return ErrorCodeRateLimited - case fiber.StatusServiceUnavailable: + case http.StatusServiceUnavailable: return ErrorCodeUnavailable default: return ErrorCodeInternal @@ -126,17 +136,3 @@ func getRequestID(c fiber.Ctx) string { func SendError(c fiber.Ctx, status int, code, message string) error { return c.Status(status).JSON(NewError(code, message, getRequestID(c))) } - -func SendAppError(c fiber.Ctx, err error) error { - if appErr, ok := errors.AsType[*AppError](err); ok { - return SendError(c, appErr.Status, appErr.Code, appErr.Message) - } - - return SendError(c, fiber.StatusInternalServerError, - ErrorCodeInternal, "Internal server error") -} - -func SendChallenge(c fiber.Ctx, challenge, message string) error { - c.Set(fiber.HeaderWWWAuthenticate, challenge) - return SendError(c, fiber.StatusUnauthorized, ErrorCodeUnauthorized, message) -} diff --git a/app/internal/common/idempotency_key_test.go b/app/internal/common/idempotency_key_test.go index 221b696..7278f23 100644 --- a/app/internal/common/idempotency_key_test.go +++ b/app/internal/common/idempotency_key_test.go @@ -21,7 +21,7 @@ func TestValidateIdempotencyKey(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - got := ValidateIdempotencyKey(test.key) == "" + got := ValidateIdempotencyKey(test.key) == nil if got != test.ok { t.Fatalf("ValidateIdempotencyKey(%q) valid = %v, want %v", test.key, got, test.ok) } diff --git a/app/internal/common/locals.go b/app/internal/common/locals.go index 0da30ef..33e7c4e 100644 --- a/app/internal/common/locals.go +++ b/app/internal/common/locals.go @@ -27,3 +27,13 @@ func SessionToken(c fiber.Ctx) (string, bool) { token, ok := c.Locals(KeySessionToken).(string) return token, ok && token != "" } + +// PathUUID parses a UUID path parameter. A malformed value is a contract +// invalid_request, not a lookup failure. +func PathUUID(c fiber.Ctx, name string) (uuid.UUID, error) { + id, err := uuid.Parse(c.Params(name)) + if err != nil { + return uuid.Nil, BadRequest("invalid " + name + " format") + } + return id, nil +} diff --git a/app/internal/common/password_test.go b/app/internal/common/password_test.go index 230b8d3..4a0a595 100644 --- a/app/internal/common/password_test.go +++ b/app/internal/common/password_test.go @@ -14,7 +14,7 @@ func TestValidatePasswordRange(t *testing.T) { {"😀", false}, } for _, tc := range cases { - if got := ValidatePassword(tc.password) == ""; got != tc.valid { + if got := ValidatePassword(tc.password) == nil; got != tc.valid { t.Fatalf("ValidatePassword(%q) valid=%v, want %v", tc.password, got, tc.valid) } } diff --git a/app/internal/common/validation.go b/app/internal/common/validation.go index c00cd6f..eb20013 100644 --- a/app/internal/common/validation.go +++ b/app/internal/common/validation.go @@ -22,71 +22,71 @@ func strLenBetween(s string, min, max int) bool { return n >= min && n <= max } -func ValidateCreateUser(username, displayName string) string { +func ValidateCreateUser(username, displayName string) error { if !usernameRegex.MatchString(username) { - return "username must match ^[a-z0-9_]{3,32}$" + return BadRequest("username must match ^[a-z0-9_]{3,32}$") } if blank(displayName) { - return "display_name must not be empty or only whitespace" + return BadRequest("display_name must not be empty or only whitespace") } if !strLenBetween(displayName, 1, 100) { - return "display_name must be between 1 and 100 Unicode code points" + return BadRequest("display_name must be between 1 and 100 Unicode code points") } - return "" + return nil } -func ValidatePassword(password string) string { +func ValidatePassword(password string) error { if blank(password) { - return "password must not be empty or only whitespace" + return BadRequest("password must not be empty or only whitespace") } if !strLenBetween(password, 12, 128) { - return "password must be between 12 and 128 Unicode code points" + return BadRequest("password must be between 12 and 128 Unicode code points") } - return "" + return nil } -func ValidateChatTitle(title string) string { +func ValidateChatTitle(title string) error { if blank(title) { - return "title must not be empty or only whitespace" + return BadRequest("title must not be empty or only whitespace") } if !strLenBetween(title, 1, 100) { - return "title must be between 1 and 100 Unicode code points" + return BadRequest("title must be between 1 and 100 Unicode code points") } - return "" + return nil } -func ValidateMessageText(text string) string { +func ValidateMessageText(text string) error { if blank(text) { - return "text must not be empty or only whitespace" + return BadRequest("text must not be empty or only whitespace") } if !strLenBetween(text, 1, 4000) { - return "text must be between 1 and 4000 Unicode code points" + return BadRequest("text must be between 1 and 4000 Unicode code points") } - return "" + return nil } -func ValidateIdempotencyKey(key string) string { +func ValidateIdempotencyKey(key string) error { if key == "" { - return "Idempotency-Key header is required" + return BadRequest("Idempotency-Key header is required") } if !idempotencyKeyRegex.MatchString(key) { - return "Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$" + return BadRequest("Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$") } - return "" + return nil } -func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string { +func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) error { if len(ids) < 1 || len(ids) > 100 { - return "member_ids must contain between 1 and 100 members" + return BadRequest("member_ids must contain between 1 and 100 members") } seen := make(map[uuid.UUID]bool, len(ids)) @@ -94,7 +94,7 @@ func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string { for _, id := range ids { if seen[id] { - return "member_ids must not contain duplicates" + return BadRequest("member_ids must not contain duplicates") } seen[id] = true @@ -105,8 +105,8 @@ func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string { } if !callerFound { - return "caller must be included in member_ids" + return BadRequest("caller must be included in member_ids") } - return "" + return nil } diff --git a/app/internal/config/config.go b/app/internal/config/config.go index 25162e7..70d2d8a 100644 --- a/app/internal/config/config.go +++ b/app/internal/config/config.go @@ -32,72 +32,63 @@ func Load() (Config, error) { return Config{}, err } + sessionTTL, err := envInt("SESSION_TTL_SECONDS", 3600, 1, 0) + if err != nil { + return Config{}, err + } + idempotencyTTL, err := envInt("IDEMPOTENCY_TTL_SECONDS", 86400, 1, 0) + if err != nil { + return Config{}, err + } + maxConns, err := envInt("DB_POOL_MAX_CONNS", 10, 1, 100) + if err != nil { + return Config{}, err + } + cfg := Config{ - Host: envOr("APP_HOST", "0.0.0.0"), - Port: envOr("APP_PORT", "8080"), - InstanceID: instance, - DBMaxConns: 10, - DBTimeout: 5 * time.Second, - RedisTimeout: 2 * time.Second, - StartupWait: 30 * time.Second, - RunMigrations: true, + Host: envOr("APP_HOST", "0.0.0.0"), + Port: envOr("APP_PORT", "8080"), + InstanceID: instance, + SessionTTL: time.Duration(sessionTTL) * time.Second, + IdempotencyTTL: time.Duration(idempotencyTTL) * time.Second, + DBMaxConns: int32(maxConns), + DBTimeout: 5 * time.Second, + RedisTimeout: 2 * time.Second, + StartupWait: 30 * time.Second, } - ttlSeconds, err := strconv.Atoi(envOr("SESSION_TTL_SECONDS", "3600")) - if err != nil || ttlSeconds < 1 { - return cfg, fmt.Errorf("SESSION_TTL_SECONDS must be a positive integer") - } - cfg.SessionTTL = time.Duration(ttlSeconds) * time.Second - - idempotencySeconds, err := strconv.Atoi(envOr("IDEMPOTENCY_TTL_SECONDS", "86400")) - if err != nil || idempotencySeconds < 1 { - return cfg, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS must be a positive integer") - } - cfg.IdempotencyTTL = time.Duration(idempotencySeconds) * time.Second - if cfg.RunMigrations, err = envBool("RUN_MIGRATIONS", true); err != nil { - return cfg, err + return Config{}, err } if cfg.MigrateOnly, err = envBool("MIGRATE_ONLY", false); err != nil { - return cfg, err + return Config{}, err } - if value := envOr("DB_POOL_MAX_CONNS", ""); value != "" { - n, convErr := strconv.Atoi(value) - if convErr != nil || n < 1 || n > 100 { - return cfg, fmt.Errorf("DB_POOL_MAX_CONNS must be an integer between 1 and 100") - } - cfg.DBMaxConns = int32(n) - } - - cfg.DatabaseURL, err = secret("DATABASE_URL") - if err != nil { - return cfg, err + if cfg.DatabaseURL, err = secret("DATABASE_URL"); err != nil { + return Config{}, err } if cfg.DatabaseURL == "" { - return cfg, fmt.Errorf("DATABASE_URL or DATABASE_URL_FILE is required") + return Config{}, fmt.Errorf("DATABASE_URL or DATABASE_URL_FILE is required") } if cfg.MigrateOnly { return cfg, nil } - cfg.CacheURL, err = secret("CACHE_URL") - if err != nil { - return cfg, err + if cfg.CacheURL, err = secret("CACHE_URL"); err != nil { + return Config{}, err } if cfg.CacheURL == "" { - cfg.CacheURL, err = secret("REDIS_URL") - if err != nil { - return cfg, err + if cfg.CacheURL, err = secret("REDIS_URL"); err != nil { + return Config{}, err } } if cfg.CacheURL == "" { - return cfg, fmt.Errorf("CACHE_URL or CACHE_URL_FILE is required") + return Config{}, fmt.Errorf("CACHE_URL or CACHE_URL_FILE is required") } if value := strings.ToLower(envOr("SESSION_STORE", "redis")); value != "redis" { - return cfg, fmt.Errorf("SESSION_STORE must be redis (got %q)", value) + return Config{}, fmt.Errorf("SESSION_STORE must be redis (got %q)", value) } return cfg, nil @@ -129,6 +120,23 @@ func envBool(name string, fallback bool) (bool, error) { return parsed, nil } +// envInt parses an integer setting; max <= 0 means "no upper bound". +func envInt(name string, fallback, min, max int) (int, error) { + value := os.Getenv(name) + if value == "" { + return fallback, nil + } + + parsed, err := strconv.Atoi(value) + if err != nil || parsed < min || (max > 0 && parsed > max) { + if max > 0 { + return 0, fmt.Errorf("%s must be an integer between %d and %d", name, min, max) + } + return 0, fmt.Errorf("%s must be an integer >= %d", name, min) + } + return parsed, nil +} + func envOr(name, fallback string) string { if value := os.Getenv(name); value != "" { return value diff --git a/app/internal/database/migrations.go b/app/internal/database/migrations.go index 16b2825..cf78d61 100644 --- a/app/internal/database/migrations.go +++ b/app/internal/database/migrations.go @@ -1,7 +1,6 @@ package database import ( - "context" "embed" "errors" "fmt" @@ -11,23 +10,18 @@ import ( pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5" "github.com/golang-migrate/migrate/v4/source/iofs" "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/stdlib" ) //go:embed migrations/*.sql var migrationFiles embed.FS -const ( - legacyMigrationLockID int64 = 728_2026 - migrationsTable = "schema_migrations" -) - -func Migrate(ctx context.Context, pool *pgxpool.Pool, databaseURL string) error { - if err := upgradeLegacyMigrationsTable(ctx, pool); err != nil { - return err - } +const migrationsTable = "schema_migrations" +// Migrate applies every pending embedded migration. golang-migrate takes its +// own advisory lock, so concurrent processes serialise instead of racing the +// schema. +func Migrate(databaseURL string) error { source, err := iofs.New(migrationFiles, "migrations") if err != nil { return fmt.Errorf("load embedded migrations: %w", err) @@ -75,81 +69,3 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool, databaseURL string) error return nil } - -// upgradeLegacyMigrationsTable replaces the table written by the previous -// in-house runner (version text, applied_at) with the golang-migrate schema -// (version bigint, dirty boolean). The data schema itself is left untouched and the -// highest applied version is carried over, so a preserved volume does not need -// to be recreated. The migration DDL is idempotent, but preserving the version -// keeps the migration history truthful. -// -// AGENT: This is a one-time compatibility bridge, not a permanent second -// migration format. It runs under the old advisory lock before golang-migrate -// creates its own lock and metadata. -func upgradeLegacyMigrationsTable(ctx context.Context, pool *pgxpool.Pool) error { - conn, err := pool.Acquire(ctx) - if err != nil { - return fmt.Errorf("acquire migration connection: %w", err) - } - defer conn.Release() - - if _, err := conn.Exec(ctx, "SELECT pg_advisory_lock($1)", legacyMigrationLockID); err != nil { - return fmt.Errorf("acquire migration lock: %w", err) - } - defer func() { - unlockCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - defer cancel() - _, _ = conn.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", legacyMigrationLockID) - }() - - var legacy bool - if err := conn.QueryRow(ctx, ` - SELECT EXISTS ( - SELECT 1 - FROM information_schema.columns - WHERE table_schema = current_schema() - AND table_name = $1 - AND column_name = 'applied_at' - )`, migrationsTable).Scan(&legacy); err != nil { - return fmt.Errorf("inspect %s: %w", migrationsTable, err) - } - if !legacy { - return nil - } - - tx, err := conn.Begin(ctx) - if err != nil { - return fmt.Errorf("begin migration table upgrade: %w", err) - } - defer func() { - rollbackCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - _ = tx.Rollback(rollbackCtx) - }() - - const upgrade = ` - DROP TABLE IF EXISTS schema_migrations_migrate_tmp; - - CREATE TABLE schema_migrations_migrate_tmp ( - version bigint NOT NULL PRIMARY KEY, - dirty boolean NOT NULL - ); - - INSERT INTO schema_migrations_migrate_tmp (version, dirty) - SELECT MAX(substring(version FROM '^[0-9]+')::bigint), false - FROM schema_migrations - WHERE version ~ '^[0-9]+' - HAVING COUNT(*) > 0; - - DROP TABLE schema_migrations; - ALTER TABLE schema_migrations_migrate_tmp RENAME TO schema_migrations;` - - if _, err := tx.Exec(ctx, upgrade); err != nil { - return fmt.Errorf("upgrade legacy %s: %w", migrationsTable, err) - } - if err := tx.Commit(ctx); err != nil { - return fmt.Errorf("commit migration table upgrade: %w", err) - } - - return nil -} diff --git a/app/internal/health/router.go b/app/internal/health/router.go deleted file mode 100644 index 87e4a59..0000000 --- a/app/internal/health/router.go +++ /dev/null @@ -1,13 +0,0 @@ -package health - -import ( - "gitflic.ru/project/bulla-max/mtusi2026lab/internal/session" - "gitflic.ru/project/bulla-max/mtusi2026lab/internal/store" - "github.com/gofiber/fiber/v3" -) - -func RegisterRoutes(router fiber.Router, st *store.Store, sessions *session.Store) { - handler := NewHandler(st, sessions) - router.Get("/live", handler.Live) - router.Get("/ready", handler.Ready) -} diff --git a/app/internal/messages/handler.go b/app/internal/messages/handler.go index c817305..470591e 100644 --- a/app/internal/messages/handler.go +++ b/app/internal/messages/handler.go @@ -6,7 +6,6 @@ import ( "gitflic.ru/project/bulla-max/mtusi2026lab/internal/common" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/store" "github.com/gofiber/fiber/v3" - "github.com/google/uuid" ) type Handler struct { @@ -24,28 +23,27 @@ type CreateMessageRequest struct { func (h *Handler) CreateMessage(c fiber.Ctx) error { userID := common.MustUserID(c) - chatID, err := uuid.Parse(c.Params("chat_id")) + chatID, err := common.PathUUID(c, "chat_id") if err != nil { - return common.SendError(c, fiber.StatusBadRequest, - common.ErrorCodeInvalidRequest, "invalid chat_id format") + return err } idempotencyKey := c.Get("Idempotency-Key") - if msg := common.ValidateIdempotencyKey(idempotencyKey); msg != "" { - return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg) + if err := common.ValidateIdempotencyKey(idempotencyKey); err != nil { + return err } var req CreateMessageRequest if err := common.BindJSON(c, &req); err != nil { - return common.SendAppError(c, err) + return err } - if msg := common.ValidateMessageText(req.Text); msg != "" { - return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg) + if err := common.ValidateMessageText(req.Text); err != nil { + return err } message, err := h.store.CreateMessage(c.Context(), chatID, userID, req.Text, idempotencyKey) if err != nil { - return common.SendAppError(c, err) + return err } return c.Status(fiber.StatusCreated).JSON(message) @@ -54,25 +52,24 @@ func (h *Handler) CreateMessage(c fiber.Ctx) error { func (h *Handler) ListMessages(c fiber.Ctx) error { userID := common.MustUserID(c) - chatID, err := uuid.Parse(c.Params("chat_id")) + chatID, err := common.PathUUID(c, "chat_id") if err != nil { - return common.SendError(c, fiber.StatusBadRequest, - common.ErrorCodeInvalidRequest, "invalid chat_id format") + return err } limit, err := common.ParseLimit(c, 50) if err != nil { - return common.SendAppError(c, err) + return err } cursor, err := common.ParseCursor(c) if err != nil { - return common.SendAppError(c, err) + return err } page, err := h.store.ListMessages(c.Context(), userID, chatID, limit, cursor) if err != nil { - return common.SendAppError(c, err) + return err } return c.JSON(page) diff --git a/app/internal/messages/router.go b/app/internal/messages/router.go deleted file mode 100644 index 64929a7..0000000 --- a/app/internal/messages/router.go +++ /dev/null @@ -1,12 +0,0 @@ -package messages - -import ( - "gitflic.ru/project/bulla-max/mtusi2026lab/internal/store" - "github.com/gofiber/fiber/v3" -) - -func RegisterProtectedRoutes(router fiber.Router, st *store.Store) { - handler := NewHandler(st) - router.Post("/chats/:chat_id/messages", handler.CreateMessage) - router.Get("/chats/:chat_id/messages", handler.ListMessages) -} diff --git a/app/internal/store/chats.go b/app/internal/store/chats.go index 0530e2d..b616d06 100644 --- a/app/internal/store/chats.go +++ b/app/internal/store/chats.go @@ -21,15 +21,14 @@ func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.U } defer rollback(tx) - for _, memberID := range memberIDs { - var exists int - err = tx.QueryRow(ctx, `SELECT 1 FROM users WHERE id = $1`, memberID).Scan(&exists) - if errors.Is(err, pgx.ErrNoRows) { - return model.Chat{}, common.BadRequest("member_id refers to non-existent user") - } - if err != nil { - return model.Chat{}, dbError(err) - } + var existing int + if err = tx.QueryRow(ctx, + `SELECT count(*) FROM users WHERE id = ANY($1::uuid[])`, + memberIDs).Scan(&existing); err != nil { + return model.Chat{}, dbError(err) + } + if existing != len(memberIDs) { + return model.Chat{}, common.BadRequest("member_id refers to non-existent user") } chat := model.Chat{ @@ -64,19 +63,12 @@ func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (m ctx, cancel := s.withTimeout(ctx) defer cancel() - chat, err := scanChat(s.pool.QueryRow(ctx, ` + return scanChat(s.pool.QueryRow(ctx, ` SELECT c.id, c.title, c.created_at, ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id) FROM chats c JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2 WHERE c.id = $1`, chatID, userID)) - if errors.Is(err, pgx.ErrNoRows) { - return model.Chat{}, common.NotFound("chat not found") - } - if err != nil { - return model.Chat{}, dbError(err) - } - return chat, nil } func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Chat], error) { @@ -101,7 +93,7 @@ func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, curs for rows.Next() { chat, scanErr := scanChat(rows) if scanErr != nil { - return nil, dbError(scanErr) + return nil, scanErr } chats = append(chats, chat) } @@ -134,11 +126,16 @@ func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, e return true, nil } +// scanChat owns the "row is missing" meaning for single-row lookups; list +// queries never see ErrNoRows. func scanChat(row rowScanner) (model.Chat, error) { var chat model.Chat var createdAt time.Time if err := row.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil { - return model.Chat{}, err + if errors.Is(err, pgx.ErrNoRows) { + return model.Chat{}, common.NotFound("chat not found") + } + return model.Chat{}, dbError(err) } chat.CreatedAt = common.RFCFormTime(createdAt.UTC()) return chat, nil diff --git a/app/internal/store/errors.go b/app/internal/store/errors.go index d4df877..237c0cc 100644 --- a/app/internal/store/errors.go +++ b/app/internal/store/errors.go @@ -3,6 +3,7 @@ package store import ( "context" "errors" + "log/slog" "net" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/common" @@ -15,6 +16,8 @@ func isUniqueViolation(err error) bool { return ok && pgErr.Code == "23505" } +// dbError maps driver failures to contract errors. Unexpected failures are +// logged with their cause so a 500 is never silent. func dbError(err error) error { if err == nil { return nil @@ -36,5 +39,6 @@ func dbError(err error) error { return common.Unavailable("database unavailable") } + slog.Error("unhandled database error", "err", err) return common.Internal() } diff --git a/app/internal/store/messages.go b/app/internal/store/messages.go index 8518e32..ed395f5 100644 --- a/app/internal/store/messages.go +++ b/app/internal/store/messages.go @@ -118,6 +118,9 @@ func (s *Store) findIdempotentMessage(ctx context.Context, senderID, chatID uuid } func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Message], error) { + ctx, cancel := s.withTimeout(ctx) + defer cancel() + isMember, err := s.IsMember(ctx, userID, chatID) if err != nil { return nil, err @@ -131,9 +134,6 @@ func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limi return nil, common.BadRequest("bad cursor value") } - ctx, cancel := s.withTimeout(ctx) - defer cancel() - cursorTime, cursorID := cursorValues(cursor) rows, err := s.pool.Query(ctx, ` SELECT id, chat_id, sender_id, text, created_at diff --git a/app/internal/users/handler.go b/app/internal/users/handler.go index 300e887..ebd8675 100644 --- a/app/internal/users/handler.go +++ b/app/internal/users/handler.go @@ -2,6 +2,8 @@ package users import ( + "log/slog" + "gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/common" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/store" @@ -25,38 +27,34 @@ type CreateUserRequest struct { func (h *Handler) CreateUser(c fiber.Ctx) error { var req CreateUserRequest if err := common.BindJSON(c, &req); err != nil { - return common.SendAppError(c, err) + return err } - if msg := common.ValidateCreateUser(req.Username, req.DisplayName); msg != "" { - return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg) + if err := common.ValidateCreateUser(req.Username, req.DisplayName); err != nil { + return err } - if msg := common.ValidatePassword(req.Password); msg != "" { - return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg) + if err := common.ValidatePassword(req.Password); err != nil { + return err } hash, err := auth.HashPassword(req.Password) if err != nil { - return common.SendAppError(c, common.Internal()) + slog.Error("hash password", "err", err) + return common.Internal() } user, err := h.store.CreateUser(c.Context(), req.Username, req.DisplayName, hash) if err != nil { - return common.SendAppError(c, err) + return err } return c.Status(fiber.StatusCreated).JSON(user) } func (h *Handler) GetCurrentUser(c fiber.Ctx) error { - userID, ok := common.UserID(c) - if !ok { - return common.SendChallenge(c, `Bearer realm="messenger"`, "authentication required") - } - - user, err := h.store.GetUserByID(c.Context(), userID) + user, err := h.store.GetUserByID(c.Context(), common.MustUserID(c)) if err != nil { - return common.SendAppError(c, err) + return err } return c.JSON(user) diff --git a/app/internal/users/router.go b/app/internal/users/router.go deleted file mode 100644 index 3a73934..0000000 --- a/app/internal/users/router.go +++ /dev/null @@ -1,16 +0,0 @@ -package users - -import ( - "gitflic.ru/project/bulla-max/mtusi2026lab/internal/store" - "github.com/gofiber/fiber/v3" -) - -func RegisterPublicRoutes(router fiber.Router, st *store.Store) { - handler := NewHandler(st) - router.Post("/users", handler.CreateUser) -} - -func RegisterProtectedRoutes(router fiber.Router, st *store.Store) { - handler := NewHandler(st) - router.Get("/users/me", handler.GetCurrentUser) -} diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg index 66f0f59..21a7062 100644 --- a/infra/haproxy/haproxy.cfg +++ b/infra/haproxy/haproxy.cfg @@ -30,7 +30,8 @@ backend api option httpchk GET /health/ready http-check expect status 200 default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 - server-template api 4 api:8080 resolvers docker init-addr last,libc,none + # 16 slots is thus the upper bound for API_REPLICAS + server-template api 16 api:8080 resolvers docker init-addr last,libc,none frontend stats bind *:8404