forked from mtusi2026/mtusi2026lab3
refactor(app) agent refactoring + a little review
This commit is contained in:
@@ -19,3 +19,4 @@ node_modules
|
|||||||
evidence
|
evidence
|
||||||
.DS_Store
|
.DS_Store
|
||||||
app/tmp
|
app/tmp
|
||||||
|
app/server
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ LB_PORT=8080
|
|||||||
HAPROXY_STATS_PORT=8404
|
HAPROXY_STATS_PORT=8404
|
||||||
|
|
||||||
# Per-replica and other services' resource limits.
|
# 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_REPLICAS=2
|
||||||
API_CPU_LIMIT=0.50
|
API_CPU_LIMIT=0.50
|
||||||
API_MEM_LIMIT=256M
|
API_MEM_LIMIT=256M
|
||||||
|
|||||||
@@ -22,10 +22,8 @@
|
|||||||
- подготовлен профиль k6 для проверки rolling update под нагрузкой.
|
- подготовлен профиль k6 для проверки rolling update под нагрузкой.
|
||||||
|
|
||||||
Обязательный контракт, `lab.json` и публичные тесты не изменялись. Существующие
|
Обязательный контракт, `lab.json` и публичные тесты не изменялись. Существующие
|
||||||
неочевидные решения отмечены в коде комментариями `AGENT:`; перечень файлов
|
неочевидные решения отмечены в коде комментариями `AGENT:`; изменения и их
|
||||||
для их проверки и удаления находится в `LEFT_TO_REVIEW.md`. Новые комментарии
|
обоснование записаны в `CHANGELOG.md`.
|
||||||
`AGENT:` в этой итерации не добавлялись: изменения и их обоснование записаны в
|
|
||||||
`CHANGELOG.md`.
|
|
||||||
|
|
||||||
## 2. Запуск из чистого clone
|
## 2. Запуск из чистого clone
|
||||||
|
|
||||||
@@ -85,7 +83,7 @@ docker compose --env-file .env down -v
|
|||||||
│ HTTP :8080
|
│ HTTP :8080
|
||||||
▼
|
▼
|
||||||
HAProxy ── readiness /health/ready, retries, stats :8404, Prometheus /metrics
|
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, без публикации портов)
|
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` |
|
| `api` | бизнес-API | `deploy.replicas: ${API_REPLICAS:-2}`, `expose: 8080`, без `ports` |
|
||||||
| `migrate` | миграции | тот же образ, `MIGRATE_ONLY=true`, `restart: "no"` |
|
| `migrate` | миграции | тот же образ, `MIGRATE_ONLY=true`, `restart: "no"` |
|
||||||
| `postgres` | источник истины | named volume `pgdata`, healthcheck, версия 16.10 |
|
| `postgres` | источник истины | named volume `pgdata`, healthcheck, версия 16.10 |
|
||||||
@@ -165,7 +163,8 @@ hostname процесса. В Compose hostname уникален для конт
|
|||||||
|
|
||||||
### 3.5. HAProxy и graceful shutdown
|
### 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` не требует правки конфига;
|
`docker compose up --scale api=N` не требует правки конфига;
|
||||||
- health check: `GET /health/ready`, `inter 1s`, `fall 2` — обнаружение отказа
|
- health check: `GET /health/ready`, `inter 1s`, `fall 2` — обнаружение отказа
|
||||||
около 2 секунд (при бюджете 10 секунд);
|
около 2 секунд (при бюджете 10 секунд);
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal"
|
||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/config"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/config"
|
||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/database"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/database"
|
||||||
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/health"
|
||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -32,10 +33,7 @@ func main() {
|
|||||||
defer pool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
if cfg.MigrateOnly || cfg.RunMigrations {
|
if cfg.MigrateOnly || cfg.RunMigrations {
|
||||||
migrateCtx, cancelMigrate := context.WithTimeout(rootCtx, 60*time.Second)
|
if err = database.Migrate(cfg.DatabaseURL); err != nil {
|
||||||
err = database.Migrate(migrateCtx, pool, cfg.DatabaseURL)
|
|
||||||
cancelMigrate()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("migrations: %v", err)
|
log.Fatalf("migrations: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -68,7 +66,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("shutting down")
|
log.Printf("shutting down")
|
||||||
internal.SignalGracefulShutdown()
|
health.SignalShutdown()
|
||||||
if err = app.ShutdownWithTimeout(10 * time.Second); err != nil {
|
if err = app.ShutdownWithTimeout(10 * time.Second); err != nil {
|
||||||
log.Printf("shutdown: %v", err)
|
log.Printf("shutdown: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-13
@@ -4,6 +4,7 @@ package internal
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"log/slog"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth"
|
||||||
@@ -21,10 +22,6 @@ import (
|
|||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SignalGracefulShutdown() {
|
|
||||||
health.SignalShutdown()
|
|
||||||
}
|
|
||||||
|
|
||||||
func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber.App {
|
func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber.App {
|
||||||
st := store.New(pool, cfg.DBTimeout, cfg.IdempotencyTTL)
|
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()
|
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")
|
api := app.Group("/api/v1")
|
||||||
users.RegisterPublicRoutes(api, st)
|
api.Post("/users", usersHandler.CreateUser)
|
||||||
auth.RegisterPublicRoutes(api, st, sessions)
|
api.Post("/auth/sessions", authHandler.CreateSession)
|
||||||
|
|
||||||
protected := api.Group("")
|
protected := api.Group("", auth.BearerAuth(sessions))
|
||||||
protected.Use(auth.BearerAuth(sessions))
|
protected.Get("/users/me", usersHandler.GetCurrentUser)
|
||||||
auth.RegisterProtectedRoutes(protected, st, sessions)
|
protected.Delete("/auth/sessions/current", authHandler.RevokeSession)
|
||||||
users.RegisterProtectedRoutes(protected, st)
|
protected.Get("/chats", chatsHandler.ListChats)
|
||||||
chats.RegisterProtectedRoutes(protected, st)
|
protected.Post("/chats", chatsHandler.CreateChat)
|
||||||
messages.RegisterProtectedRoutes(protected, st)
|
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
|
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 {
|
func handleError(c fiber.Ctx, err error) error {
|
||||||
if appErr, ok := errors.AsType[*common.AppError](err); ok {
|
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)
|
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)
|
common.ErrorCodeFromStatus(fiberErr.Code), fiberErr.Message)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
slog.Error("unhandled request error",
|
||||||
|
"request_id", requestid.FromContext(c), "err", err)
|
||||||
return common.SendError(c, fiber.StatusInternalServerError,
|
return common.SendError(c, fiber.StatusInternalServerError,
|
||||||
common.ErrorCodeInternal, "Internal server error")
|
common.ErrorCodeInternal, "Internal server error")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ package auth
|
|||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
|
"log/slog"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
"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/session"
|
||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||||
"github.com/gofiber/fiber/v3"
|
"github.com/gofiber/fiber/v3"
|
||||||
"github.com/gofiber/fiber/v3/log"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -32,7 +32,7 @@ func NewHandler(st *store.Store, sessions *session.Store) *Handler {
|
|||||||
func (h *Handler) CreateSession(c fiber.Ctx) error {
|
func (h *Handler) CreateSession(c fiber.Ctx) error {
|
||||||
username, password, ok := parseBasic(c.Get(fiber.HeaderAuthorization))
|
username, password, ok := parseBasic(c.Get(fiber.HeaderAuthorization))
|
||||||
if !ok {
|
if !ok {
|
||||||
return common.SendChallenge(c, basicChallenge, "invalid credentials")
|
return common.NewChallenge(basicChallenge, "invalid credentials")
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := h.store.GetUserByUsername(c.Context(), username)
|
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
|
// therefore take different time, so username enumeration through
|
||||||
// response timing is theoretically possible. The contract only
|
// response timing is theoretically possible. The contract only
|
||||||
// requires the same 401 body and challenge.
|
// 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)
|
valid, err := VerifyPassword(user.PasswordHash, password)
|
||||||
if err != nil || !valid {
|
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)
|
token, expiresAt, err := h.sessions.Create(c.Context(), user.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Errorf("create session: %v", err)
|
slog.Error("create session", "err", err)
|
||||||
return common.SendError(c, fiber.StatusServiceUnavailable,
|
return common.Unavailable("session store unavailable")
|
||||||
common.ErrorCodeUnavailable, "session store unavailable")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.Status(fiber.StatusCreated).JSON(model.Session{
|
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 {
|
func (h *Handler) RevokeSession(c fiber.Ctx) error {
|
||||||
token, ok := common.SessionToken(c)
|
token, ok := common.SessionToken(c)
|
||||||
if !ok {
|
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 {
|
if err := h.sessions.Revoke(c.Context(), token); err != nil {
|
||||||
log.Errorf("revoke session: %v", err)
|
slog.Error("revoke session", "err", err)
|
||||||
return common.SendError(c, fiber.StatusServiceUnavailable,
|
return common.Unavailable("session store unavailable")
|
||||||
common.ErrorCodeUnavailable, "session store unavailable")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.SendStatus(fiber.StatusNoContent)
|
return c.SendStatus(fiber.StatusNoContent)
|
||||||
@@ -89,17 +87,16 @@ func BearerAuth(sessions *session.Store) fiber.Handler {
|
|||||||
scheme, token, found := strings.Cut(header, " ")
|
scheme, token, found := strings.Cut(header, " ")
|
||||||
token = strings.TrimSpace(token)
|
token = strings.TrimSpace(token)
|
||||||
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t") {
|
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)
|
userID, err := sessions.Lookup(c.Context(), token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, session.ErrNotFound) {
|
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)
|
slog.Error("session lookup", "err", err)
|
||||||
return common.SendError(c, fiber.StatusServiceUnavailable,
|
return common.Unavailable("session store unavailable")
|
||||||
common.ErrorCodeUnavailable, "session store unavailable")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Locals(common.KeyUserID, userID)
|
c.Locals(common.KeyUserID, userID)
|
||||||
|
|||||||
@@ -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)
|
|
||||||
}
|
|
||||||
@@ -26,19 +26,19 @@ func (h *Handler) CreateChat(c fiber.Ctx) error {
|
|||||||
|
|
||||||
var req CreateChatRequest
|
var req CreateChatRequest
|
||||||
if err := common.BindJSON(c, &req); err != nil {
|
if err := common.BindJSON(c, &req); err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if msg := common.ValidateChatTitle(req.Title); msg != "" {
|
if err := common.ValidateChatTitle(req.Title); err != nil {
|
||||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
return err
|
||||||
}
|
}
|
||||||
if msg := common.ValidateMemberIDs(req.MemberIDs, userID); msg != "" {
|
if err := common.ValidateMemberIDs(req.MemberIDs, userID); err != nil {
|
||||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
chat, err := h.store.CreateChat(c.Context(), req.Title, req.MemberIDs)
|
chat, err := h.store.CreateChat(c.Context(), req.Title, req.MemberIDs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.Status(fiber.StatusCreated).JSON(chat)
|
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)
|
limit, err := common.ParseLimit(c, 50)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
cursor, err := common.ParseCursor(c)
|
cursor, err := common.ParseCursor(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
if cursor != nil && cursor.ContextID != userID {
|
if cursor != nil && cursor.ContextID != userID {
|
||||||
return common.SendError(c, fiber.StatusBadRequest,
|
return common.BadRequest("bad cursor value")
|
||||||
common.ErrorCodeInvalidRequest, "bad cursor value")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
page, err := h.store.ListChats(c.Context(), userID, limit, cursor)
|
page, err := h.store.ListChats(c.Context(), userID, limit, cursor)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.JSON(page)
|
return c.JSON(page)
|
||||||
@@ -72,15 +71,14 @@ func (h *Handler) ListChats(c fiber.Ctx) error {
|
|||||||
func (h *Handler) GetChat(c fiber.Ctx) error {
|
func (h *Handler) GetChat(c fiber.Ctx) error {
|
||||||
userID := common.MustUserID(c)
|
userID := common.MustUserID(c)
|
||||||
|
|
||||||
chatID, err := uuid.Parse(c.Params("chat_id"))
|
chatID, err := common.PathUUID(c, "chat_id")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendError(c, fiber.StatusBadRequest,
|
return err
|
||||||
common.ErrorCodeInvalidRequest, "invalid chat_id format")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
chat, err := h.store.GetChatForUser(c.Context(), userID, chatID)
|
chat, err := h.store.GetChatForUser(c.Context(), userID, chatID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.JSON(chat)
|
return c.JSON(chat)
|
||||||
|
|||||||
@@ -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)
|
|
||||||
}
|
|
||||||
@@ -4,6 +4,7 @@ package common
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v3"
|
"github.com/gofiber/fiber/v3"
|
||||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
"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 {
|
type AppError struct {
|
||||||
Status int
|
Status int
|
||||||
Code string
|
Code string
|
||||||
Message string
|
Message string
|
||||||
|
Challenge string // WWW-Authenticate value, set for 401 responses
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *AppError) Error() string {
|
func (e *AppError) Error() string {
|
||||||
@@ -60,31 +64,37 @@ func NewAppError(status int, code, message string) *AppError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func BadRequest(message string) *AppError {
|
func BadRequest(message string) *AppError {
|
||||||
return NewAppError(fiber.StatusBadRequest, ErrorCodeInvalidRequest, message)
|
return NewAppError(http.StatusBadRequest, ErrorCodeInvalidRequest, message)
|
||||||
}
|
|
||||||
|
|
||||||
func Unauthorized(message string) *AppError {
|
|
||||||
return NewAppError(fiber.StatusUnauthorized, ErrorCodeUnauthorized, message)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NotFound(message string) *AppError {
|
func NotFound(message string) *AppError {
|
||||||
return NewAppError(fiber.StatusNotFound, ErrorCodeNotFound, message)
|
return NewAppError(http.StatusNotFound, ErrorCodeNotFound, message)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Conflict(message string) *AppError {
|
func Conflict(message string) *AppError {
|
||||||
return NewAppError(fiber.StatusConflict, ErrorCodeConflict, message)
|
return NewAppError(http.StatusConflict, ErrorCodeConflict, message)
|
||||||
}
|
}
|
||||||
|
|
||||||
func UnsupportedMedia(message string) *AppError {
|
func UnsupportedMedia(message string) *AppError {
|
||||||
return NewAppError(fiber.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message)
|
return NewAppError(http.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Internal() *AppError {
|
func Internal() *AppError {
|
||||||
return NewAppError(fiber.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
|
return NewAppError(http.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
|
||||||
}
|
}
|
||||||
|
|
||||||
func Unavailable(message string) *AppError {
|
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.
|
// 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 {
|
func ErrorCodeFromStatus(status int) string {
|
||||||
switch status {
|
switch status {
|
||||||
case fiber.StatusBadRequest:
|
case http.StatusBadRequest:
|
||||||
return ErrorCodeInvalidRequest
|
return ErrorCodeInvalidRequest
|
||||||
case fiber.StatusUnauthorized:
|
case http.StatusUnauthorized:
|
||||||
return ErrorCodeUnauthorized
|
return ErrorCodeUnauthorized
|
||||||
case fiber.StatusNotFound:
|
case http.StatusNotFound:
|
||||||
return ErrorCodeNotFound
|
return ErrorCodeNotFound
|
||||||
case fiber.StatusConflict:
|
case http.StatusConflict:
|
||||||
return ErrorCodeConflict
|
return ErrorCodeConflict
|
||||||
case fiber.StatusRequestEntityTooLarge:
|
case http.StatusRequestEntityTooLarge:
|
||||||
return ErrorCodePayloadTooLarge
|
return ErrorCodePayloadTooLarge
|
||||||
case fiber.StatusUnsupportedMediaType:
|
case http.StatusUnsupportedMediaType:
|
||||||
return ErrorCodeUnsupportedMedia
|
return ErrorCodeUnsupportedMedia
|
||||||
case fiber.StatusTooManyRequests:
|
case http.StatusTooManyRequests:
|
||||||
return ErrorCodeRateLimited
|
return ErrorCodeRateLimited
|
||||||
case fiber.StatusServiceUnavailable:
|
case http.StatusServiceUnavailable:
|
||||||
return ErrorCodeUnavailable
|
return ErrorCodeUnavailable
|
||||||
default:
|
default:
|
||||||
return ErrorCodeInternal
|
return ErrorCodeInternal
|
||||||
@@ -126,17 +136,3 @@ func getRequestID(c fiber.Ctx) string {
|
|||||||
func SendError(c fiber.Ctx, status int, code, message string) error {
|
func SendError(c fiber.Ctx, status int, code, message string) error {
|
||||||
return c.Status(status).JSON(NewError(code, message, getRequestID(c)))
|
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)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ func TestValidateIdempotencyKey(t *testing.T) {
|
|||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
got := ValidateIdempotencyKey(test.key) == ""
|
got := ValidateIdempotencyKey(test.key) == nil
|
||||||
if got != test.ok {
|
if got != test.ok {
|
||||||
t.Fatalf("ValidateIdempotencyKey(%q) valid = %v, want %v", test.key, got, test.ok)
|
t.Fatalf("ValidateIdempotencyKey(%q) valid = %v, want %v", test.key, got, test.ok)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,3 +27,13 @@ func SessionToken(c fiber.Ctx) (string, bool) {
|
|||||||
token, ok := c.Locals(KeySessionToken).(string)
|
token, ok := c.Locals(KeySessionToken).(string)
|
||||||
return token, ok && token != ""
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ func TestValidatePasswordRange(t *testing.T) {
|
|||||||
{"😀", false},
|
{"😀", false},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
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)
|
t.Fatalf("ValidatePassword(%q) valid=%v, want %v", tc.password, got, tc.valid)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,71 +22,71 @@ func strLenBetween(s string, min, max int) bool {
|
|||||||
return n >= min && n <= max
|
return n >= min && n <= max
|
||||||
}
|
}
|
||||||
|
|
||||||
func ValidateCreateUser(username, displayName string) string {
|
func ValidateCreateUser(username, displayName string) error {
|
||||||
if !usernameRegex.MatchString(username) {
|
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) {
|
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) {
|
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) {
|
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) {
|
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) {
|
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) {
|
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) {
|
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) {
|
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 == "" {
|
if key == "" {
|
||||||
return "Idempotency-Key header is required"
|
return BadRequest("Idempotency-Key header is required")
|
||||||
}
|
}
|
||||||
if !idempotencyKeyRegex.MatchString(key) {
|
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 {
|
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))
|
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 {
|
for _, id := range ids {
|
||||||
if seen[id] {
|
if seen[id] {
|
||||||
return "member_ids must not contain duplicates"
|
return BadRequest("member_ids must not contain duplicates")
|
||||||
}
|
}
|
||||||
|
|
||||||
seen[id] = true
|
seen[id] = true
|
||||||
@@ -105,8 +105,8 @@ func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !callerFound {
|
if !callerFound {
|
||||||
return "caller must be included in member_ids"
|
return BadRequest("caller must be included in member_ids")
|
||||||
}
|
}
|
||||||
|
|
||||||
return ""
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,72 +32,63 @@ func Load() (Config, error) {
|
|||||||
return Config{}, err
|
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{
|
cfg := Config{
|
||||||
Host: envOr("APP_HOST", "0.0.0.0"),
|
Host: envOr("APP_HOST", "0.0.0.0"),
|
||||||
Port: envOr("APP_PORT", "8080"),
|
Port: envOr("APP_PORT", "8080"),
|
||||||
InstanceID: instance,
|
InstanceID: instance,
|
||||||
DBMaxConns: 10,
|
SessionTTL: time.Duration(sessionTTL) * time.Second,
|
||||||
DBTimeout: 5 * time.Second,
|
IdempotencyTTL: time.Duration(idempotencyTTL) * time.Second,
|
||||||
RedisTimeout: 2 * time.Second,
|
DBMaxConns: int32(maxConns),
|
||||||
StartupWait: 30 * time.Second,
|
DBTimeout: 5 * time.Second,
|
||||||
RunMigrations: true,
|
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 {
|
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 {
|
if cfg.MigrateOnly, err = envBool("MIGRATE_ONLY", false); err != nil {
|
||||||
return cfg, err
|
return Config{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if value := envOr("DB_POOL_MAX_CONNS", ""); value != "" {
|
if cfg.DatabaseURL, err = secret("DATABASE_URL"); err != nil {
|
||||||
n, convErr := strconv.Atoi(value)
|
return Config{}, err
|
||||||
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 == "" {
|
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 {
|
if cfg.MigrateOnly {
|
||||||
return cfg, nil
|
return cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg.CacheURL, err = secret("CACHE_URL")
|
if cfg.CacheURL, err = secret("CACHE_URL"); err != nil {
|
||||||
if err != nil {
|
return Config{}, err
|
||||||
return cfg, err
|
|
||||||
}
|
}
|
||||||
if cfg.CacheURL == "" {
|
if cfg.CacheURL == "" {
|
||||||
cfg.CacheURL, err = secret("REDIS_URL")
|
if cfg.CacheURL, err = secret("REDIS_URL"); err != nil {
|
||||||
if err != nil {
|
return Config{}, err
|
||||||
return cfg, err
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if cfg.CacheURL == "" {
|
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" {
|
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
|
return cfg, nil
|
||||||
@@ -129,6 +120,23 @@ func envBool(name string, fallback bool) (bool, error) {
|
|||||||
return parsed, nil
|
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 {
|
func envOr(name, fallback string) string {
|
||||||
if value := os.Getenv(name); value != "" {
|
if value := os.Getenv(name); value != "" {
|
||||||
return value
|
return value
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package database
|
package database
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"embed"
|
"embed"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -11,23 +10,18 @@ import (
|
|||||||
pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
||||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
"github.com/jackc/pgx/v5/stdlib"
|
"github.com/jackc/pgx/v5/stdlib"
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed migrations/*.sql
|
//go:embed migrations/*.sql
|
||||||
var migrationFiles embed.FS
|
var migrationFiles embed.FS
|
||||||
|
|
||||||
const (
|
const migrationsTable = "schema_migrations"
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// 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")
|
source, err := iofs.New(migrationFiles, "migrations")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("load embedded migrations: %w", err)
|
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
|
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
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -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)
|
|
||||||
}
|
|
||||||
@@ -6,7 +6,6 @@ import (
|
|||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||||
"github.com/gofiber/fiber/v3"
|
"github.com/gofiber/fiber/v3"
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
@@ -24,28 +23,27 @@ type CreateMessageRequest struct {
|
|||||||
func (h *Handler) CreateMessage(c fiber.Ctx) error {
|
func (h *Handler) CreateMessage(c fiber.Ctx) error {
|
||||||
userID := common.MustUserID(c)
|
userID := common.MustUserID(c)
|
||||||
|
|
||||||
chatID, err := uuid.Parse(c.Params("chat_id"))
|
chatID, err := common.PathUUID(c, "chat_id")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendError(c, fiber.StatusBadRequest,
|
return err
|
||||||
common.ErrorCodeInvalidRequest, "invalid chat_id format")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
idempotencyKey := c.Get("Idempotency-Key")
|
idempotencyKey := c.Get("Idempotency-Key")
|
||||||
if msg := common.ValidateIdempotencyKey(idempotencyKey); msg != "" {
|
if err := common.ValidateIdempotencyKey(idempotencyKey); err != nil {
|
||||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
var req CreateMessageRequest
|
var req CreateMessageRequest
|
||||||
if err := common.BindJSON(c, &req); err != nil {
|
if err := common.BindJSON(c, &req); err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
if msg := common.ValidateMessageText(req.Text); msg != "" {
|
if err := common.ValidateMessageText(req.Text); err != nil {
|
||||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
message, err := h.store.CreateMessage(c.Context(), chatID, userID, req.Text, idempotencyKey)
|
message, err := h.store.CreateMessage(c.Context(), chatID, userID, req.Text, idempotencyKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.Status(fiber.StatusCreated).JSON(message)
|
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 {
|
func (h *Handler) ListMessages(c fiber.Ctx) error {
|
||||||
userID := common.MustUserID(c)
|
userID := common.MustUserID(c)
|
||||||
|
|
||||||
chatID, err := uuid.Parse(c.Params("chat_id"))
|
chatID, err := common.PathUUID(c, "chat_id")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendError(c, fiber.StatusBadRequest,
|
return err
|
||||||
common.ErrorCodeInvalidRequest, "invalid chat_id format")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
limit, err := common.ParseLimit(c, 50)
|
limit, err := common.ParseLimit(c, 50)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
cursor, err := common.ParseCursor(c)
|
cursor, err := common.ParseCursor(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
page, err := h.store.ListMessages(c.Context(), userID, chatID, limit, cursor)
|
page, err := h.store.ListMessages(c.Context(), userID, chatID, limit, cursor)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.JSON(page)
|
return c.JSON(page)
|
||||||
|
|||||||
@@ -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)
|
|
||||||
}
|
|
||||||
+16
-19
@@ -21,15 +21,14 @@ func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.U
|
|||||||
}
|
}
|
||||||
defer rollback(tx)
|
defer rollback(tx)
|
||||||
|
|
||||||
for _, memberID := range memberIDs {
|
var existing int
|
||||||
var exists int
|
if err = tx.QueryRow(ctx,
|
||||||
err = tx.QueryRow(ctx, `SELECT 1 FROM users WHERE id = $1`, memberID).Scan(&exists)
|
`SELECT count(*) FROM users WHERE id = ANY($1::uuid[])`,
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
memberIDs).Scan(&existing); err != nil {
|
||||||
return model.Chat{}, common.BadRequest("member_id refers to non-existent user")
|
return model.Chat{}, dbError(err)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if existing != len(memberIDs) {
|
||||||
return model.Chat{}, dbError(err)
|
return model.Chat{}, common.BadRequest("member_id refers to non-existent user")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
chat := model.Chat{
|
chat := model.Chat{
|
||||||
@@ -64,19 +63,12 @@ func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (m
|
|||||||
ctx, cancel := s.withTimeout(ctx)
|
ctx, cancel := s.withTimeout(ctx)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
chat, err := scanChat(s.pool.QueryRow(ctx, `
|
return scanChat(s.pool.QueryRow(ctx, `
|
||||||
SELECT c.id, c.title, c.created_at,
|
SELECT c.id, c.title, c.created_at,
|
||||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
|
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
|
||||||
FROM chats c
|
FROM chats c
|
||||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2
|
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2
|
||||||
WHERE c.id = $1`, chatID, userID))
|
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) {
|
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() {
|
for rows.Next() {
|
||||||
chat, scanErr := scanChat(rows)
|
chat, scanErr := scanChat(rows)
|
||||||
if scanErr != nil {
|
if scanErr != nil {
|
||||||
return nil, dbError(scanErr)
|
return nil, scanErr
|
||||||
}
|
}
|
||||||
chats = append(chats, chat)
|
chats = append(chats, chat)
|
||||||
}
|
}
|
||||||
@@ -134,11 +126,16 @@ func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, e
|
|||||||
return true, nil
|
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) {
|
func scanChat(row rowScanner) (model.Chat, error) {
|
||||||
var chat model.Chat
|
var chat model.Chat
|
||||||
var createdAt time.Time
|
var createdAt time.Time
|
||||||
if err := row.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
|
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())
|
chat.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||||
return chat, nil
|
return chat, nil
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package store
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||||
@@ -15,6 +16,8 @@ func isUniqueViolation(err error) bool {
|
|||||||
return ok && pgErr.Code == "23505"
|
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 {
|
func dbError(err error) error {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return nil
|
return nil
|
||||||
@@ -36,5 +39,6 @@ func dbError(err error) error {
|
|||||||
return common.Unavailable("database unavailable")
|
return common.Unavailable("database unavailable")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
slog.Error("unhandled database error", "err", err)
|
||||||
return common.Internal()
|
return common.Internal()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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) {
|
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)
|
isMember, err := s.IsMember(ctx, userID, chatID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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")
|
return nil, common.BadRequest("bad cursor value")
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := s.withTimeout(ctx)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
cursorTime, cursorID := cursorValues(cursor)
|
cursorTime, cursorID := cursorValues(cursor)
|
||||||
rows, err := s.pool.Query(ctx, `
|
rows, err := s.pool.Query(ctx, `
|
||||||
SELECT id, chat_id, sender_id, text, created_at
|
SELECT id, chat_id, sender_id, text, created_at
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
package users
|
package users
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"log/slog"
|
||||||
|
|
||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth"
|
||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
|
||||||
@@ -25,38 +27,34 @@ type CreateUserRequest struct {
|
|||||||
func (h *Handler) CreateUser(c fiber.Ctx) error {
|
func (h *Handler) CreateUser(c fiber.Ctx) error {
|
||||||
var req CreateUserRequest
|
var req CreateUserRequest
|
||||||
if err := common.BindJSON(c, &req); err != nil {
|
if err := common.BindJSON(c, &req); err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if msg := common.ValidateCreateUser(req.Username, req.DisplayName); msg != "" {
|
if err := common.ValidateCreateUser(req.Username, req.DisplayName); err != nil {
|
||||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
return err
|
||||||
}
|
}
|
||||||
if msg := common.ValidatePassword(req.Password); msg != "" {
|
if err := common.ValidatePassword(req.Password); err != nil {
|
||||||
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
hash, err := auth.HashPassword(req.Password)
|
hash, err := auth.HashPassword(req.Password)
|
||||||
if err != nil {
|
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)
|
user, err := h.store.CreateUser(c.Context(), req.Username, req.DisplayName, hash)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.Status(fiber.StatusCreated).JSON(user)
|
return c.Status(fiber.StatusCreated).JSON(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) GetCurrentUser(c fiber.Ctx) error {
|
func (h *Handler) GetCurrentUser(c fiber.Ctx) error {
|
||||||
userID, ok := common.UserID(c)
|
user, err := h.store.GetUserByID(c.Context(), common.MustUserID(c))
|
||||||
if !ok {
|
|
||||||
return common.SendChallenge(c, `Bearer realm="messenger"`, "authentication required")
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err := h.store.GetUserByID(c.Context(), userID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.SendAppError(c, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.JSON(user)
|
return c.JSON(user)
|
||||||
|
|||||||
@@ -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)
|
|
||||||
}
|
|
||||||
@@ -30,7 +30,8 @@ backend api
|
|||||||
option httpchk GET /health/ready
|
option httpchk GET /health/ready
|
||||||
http-check expect status 200
|
http-check expect status 200
|
||||||
default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2
|
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
|
frontend stats
|
||||||
bind *:8404
|
bind *:8404
|
||||||
|
|||||||
Reference in New Issue
Block a user