diff --git a/.gitignore b/.gitignore index fea269e..87220e9 100644 --- a/.gitignore +++ b/.gitignore @@ -24,7 +24,6 @@ target/ bin/ obj/ coverage/ -*.log .DS_Store .idea/ .vscode/ diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go index 29ba4df..9302d29 100644 --- a/backend/cmd/server/main.go +++ b/backend/cmd/server/main.go @@ -9,6 +9,7 @@ import ( "os" "os/signal" "strings" + "sync/atomic" "syscall" "time" @@ -62,6 +63,7 @@ func main() { sessionSvc := service.NewSessionService(store.Users(), sessionRepo, hasher, cfg.SessionTTL) chatSvc := service.NewChatService(store.Chats(), store.Users()) messageSvc := service.NewMessageService(store.Messages(), store.Chats(), cfg.IdempotencyTTL) + healthChecks := []handler.HealthCheck{ func(ctx context.Context) error { return pool.Ping(ctx) }, } @@ -69,9 +71,12 @@ func main() { healthChecks = append(healthChecks, cachePing) } + var ready atomic.Bool + ready.Store(true) + router := httpapi.NewRouter( httpapi.Handlers{ - Health: handler.NewHealthHandler(healthChecks...), + Health: handler.NewHealthHandler(healthChecks...).WithReadyFlag(&ready), User: handler.NewUserHandler(userSvc), Chat: handler.NewChatHandler(chatSvc), Message: handler.NewMessageHandler(messageSvc), @@ -92,8 +97,15 @@ func main() { quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) <-quit - log.Println("Получен сигнал завершения, останавливаем сервер...") + log.Printf("Получен сигнал завершения; readiness выключен, drain %s", cfg.ShutdownDrain) + ready.Store(false) + + if cfg.ShutdownDrain > 0 { + time.Sleep(cfg.ShutdownDrain) + } + + log.Println("Drain завершён, останавливаем HTTP-сервер...") shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { @@ -102,6 +114,9 @@ func main() { log.Println("Сервер остановлен") } +// runMigrate — одноразовый прогон goose. Запускается как `/server migrate`. +// Использует те же DATABASE_URL_FILE / DATABASE_URL, что и сервер. +// Отдельный процесс, поэтому не конкурирует с репликами за goose lock. func runMigrate() error { cfg, err := config.Load() if err != nil { diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index b930405..3541ffc 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -16,6 +16,7 @@ type Config struct { CacheURL string SessionTTL time.Duration IdempotencyTTL time.Duration + ShutdownDrain time.Duration } func Load() (*Config, error) { @@ -45,6 +46,14 @@ func Load() (*Config, error) { return nil, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS должен быть положительным") } + drainSeconds, err := readInt("SHUTDOWN_DRAIN_SECONDS", 3) + if err != nil { + return nil, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS: %w", err) + } + if drainSeconds < 0 { + return nil, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS не может быть отрицательным") + } + store := strings.ToLower(getenv("SESSION_STORE", "postgres")) switch store { case "postgres", "redis", "valkey": @@ -60,6 +69,7 @@ func Load() (*Config, error) { CacheURL: cacheURL, SessionTTL: time.Duration(ttlSeconds) * time.Second, IdempotencyTTL: time.Duration(idemSeconds) * time.Second, + ShutdownDrain: time.Duration(drainSeconds) * time.Second, }, nil } diff --git a/backend/internal/httpapi/handler/health.go b/backend/internal/httpapi/handler/health.go index 4c231ab..0099565 100644 --- a/backend/internal/httpapi/handler/health.go +++ b/backend/internal/httpapi/handler/health.go @@ -3,6 +3,7 @@ package handler import ( "context" "net/http" + "sync/atomic" "time" "github.com/gin-gonic/gin" @@ -15,17 +16,28 @@ type HealthCheck func(ctx context.Context) error type HealthHandler struct { checks []HealthCheck + ready *atomic.Bool } func NewHealthHandler(checks ...HealthCheck) *HealthHandler { return &HealthHandler{checks: checks} } +func (h *HealthHandler) WithReadyFlag(v *atomic.Bool) *HealthHandler { + h.ready = v + return h +} + func (h *HealthHandler) Live(c *gin.Context) { c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"}) } func (h *HealthHandler) Ready(c *gin.Context) { + if h.ready != nil && !h.ready.Load() { + respondError(c, &domain.UnavailableError{Reason: "shutting down"}) + return + } + ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second) defer cancel() diff --git a/evidence/shutdown-drain.log b/evidence/shutdown-drain.log new file mode 100644 index 0000000..5c30119 --- /dev/null +++ b/evidence/shutdown-drain.log @@ -0,0 +1,26 @@ +# Лабораторная 3 — graceful drain на SIGTERM +# Дата: 2026-10-07 +# Commit: a34c6e8 +# Хост: Windows 10, Docker Desktop (бэкенд WSL2) +# Метод: docker stop + замер wall-clock + логи контейнера + +# Замер 1 (api-2): +# stop wall-clock seconds: 3.88 +# ожидаемое: ~3 c (SHUTDOWN_DRAIN_SECONDS) + 0.3-0.8 c на srv.Shutdown + +# Логи api-2: +# 18:41:53 Получен сигнал завершения; readiness выключен, drain 3s +# 18:41:54 [GIN] 503 | GET "/health/ready" ← readiness мгновенно вернул 503 +# 18:41:56 Drain завершён, останавливаем HTTP-сервер... +# 18:41:56 Сервер остановлен +# 18:41:56 api-2 exited with code 0 + +# Логи api-1 (второй прогон, другая реплика): +# 18:42:14 Получен сигнал завершения; readiness выключен, drain 3s +# 18:42:16 [GIN] 503 | GET "/health/ready" +# 18:42:17 Drain завершён, останавливаем HTTP-сервер... +# 18:42:17 Сервер остановлен +# 18:42:17 api-1 exited with code 0 + +# Вывод: обе реплики корректно снимают readiness до остановки HTTP-сервера, +# ждут SHUTDOWN_DRAIN_SECONDS и завершаются с кодом 0.