feat(http): graceful drain on SIGTERM and drain log
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user