feat(http): graceful drain on SIGTERM and drain log

This commit is contained in:
Голиков Maximillian Антон
2026-10-07 14:12:25 +03:00
parent 4886430b69
commit 05c12a8f39
5 changed files with 65 additions and 3 deletions
+10
View File
@@ -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()