Добавить X-Instance-Id, задержку drain при SIGTERM и отдельный запуск миграций

This commit is contained in:
2026-11-02 16:58:11 +03:00
parent 5b9f377783
commit 7fa8881eb3
21 changed files with 389 additions and 64 deletions
+73 -10
View File
@@ -25,6 +25,22 @@ type Config struct {
DatabaseURL string
SessionStoreURL string
SessionTTL time.Duration
// DrainDelay is how long a stopping process keeps serving with readiness
// already off, so the load balancer can take it out of rotation before
// the listener closes. It must exceed the balancer's detection time.
DrainDelay time.Duration
IdempotencyTTL time.Duration
DBMaxConns int32
// DebugAddr enables the internal expvar listener; empty disables it.
DebugAddr string
}
// Migrate is the configuration of the one-shot migration command, which
// needs the database only.
type Migrate struct {
Env string
LogLevel slog.Level
DatabaseURL string
}
// Lookup reads one variable, reporting whether it was set; os.LookupEnv
@@ -40,6 +56,9 @@ func Load(lookup Lookup) (Config, error) {
ShutdownTimeout: 8 * time.Second,
MaxBodyBytes: 64 * 1024,
SessionTTL: time.Hour,
DrainDelay: 2 * time.Second,
IdempotencyTTL: 24 * time.Hour,
DBMaxConns: 10,
}
if v, ok := lookup("APP_HOST"); ok {
if strings.TrimSpace(v) == "" {
@@ -54,15 +73,9 @@ func Load(lookup Lookup) (Config, error) {
}
cfg.Port = port
}
if v, ok := lookup("APP_ENV"); ok && strings.TrimSpace(v) != "" {
cfg.Env = v
}
if v, ok := lookup("APP_LOG_LEVEL"); ok {
var level slog.Level
if err := level.UnmarshalText([]byte(v)); err != nil {
return Config{}, fmt.Errorf("APP_LOG_LEVEL must be debug, info, warn or error, got %q", v)
}
cfg.LogLevel = level
var err error
if cfg.Env, cfg.LogLevel, err = logging(lookup, cfg.Env, cfg.LogLevel); err != nil {
return Config{}, err
}
if v, ok := lookup("APP_SHUTDOWN_TIMEOUT"); ok {
d, err := time.ParseDuration(v)
@@ -85,7 +98,33 @@ func Load(lookup Lookup) (Config, error) {
}
cfg.SessionTTL = time.Duration(n) * time.Second
}
var err error
if v, ok := lookup("APP_DRAIN_DELAY"); ok {
d, err := time.ParseDuration(v)
if err != nil || d < 0 {
return Config{}, fmt.Errorf("APP_DRAIN_DELAY must be a non-negative duration such as 2s, got %q", v)
}
cfg.DrainDelay = d
}
if v, ok := lookup("IDEMPOTENCY_TTL_SECONDS"); ok {
n, err := strconv.ParseUint(v, 10, 32)
if err != nil || n == 0 {
return Config{}, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS must be a positive whole number of seconds, got %q", v)
}
cfg.IdempotencyTTL = time.Duration(n) * time.Second
}
if v, ok := lookup("DB_MAX_CONNS"); ok {
n, err := strconv.ParseInt(v, 10, 32)
if err != nil || n < 1 || n > 1000 {
return Config{}, fmt.Errorf("DB_MAX_CONNS must be an integer between 1 and 1000, got %q", v)
}
cfg.DBMaxConns = int32(n)
}
if v, ok := lookup("APP_DEBUG_ADDR"); ok && v != "" {
if _, _, err := net.SplitHostPort(v); err != nil {
return Config{}, fmt.Errorf("APP_DEBUG_ADDR must be host:port such as :9090, got %q", v)
}
cfg.DebugAddr = v
}
if cfg.DatabaseURL, err = secret(lookup, "DATABASE_URL_FILE"); err != nil {
return Config{}, err
}
@@ -95,6 +134,30 @@ func Load(lookup Lookup) (Config, error) {
return cfg, nil
}
func LoadMigrate(lookup Lookup) (Migrate, error) {
cfg := Migrate{Env: "lab", LogLevel: slog.LevelInfo}
var err error
if cfg.Env, cfg.LogLevel, err = logging(lookup, cfg.Env, cfg.LogLevel); err != nil {
return Migrate{}, err
}
if cfg.DatabaseURL, err = secret(lookup, "DATABASE_URL_FILE"); err != nil {
return Migrate{}, err
}
return cfg, nil
}
func logging(lookup Lookup, env string, level slog.Level) (string, slog.Level, error) {
if v, ok := lookup("APP_ENV"); ok && strings.TrimSpace(v) != "" {
env = v
}
if v, ok := lookup("APP_LOG_LEVEL"); ok {
if err := level.UnmarshalText([]byte(v)); err != nil {
return "", 0, fmt.Errorf("APP_LOG_LEVEL must be debug, info, warn or error, got %q", v)
}
}
return env, level, nil
}
// secret reads the file named by the variable; surrounding whitespace,
// including the trailing newline editors add, is dropped.
func secret(lookup Lookup, key string) (string, error) {
+50 -8
View File
@@ -65,6 +65,9 @@ func TestDefaults(t *testing.T) {
if cfg.SessionTTL != time.Hour {
t.Fatalf("SessionTTL = %v, want 1h", cfg.SessionTTL)
}
if cfg.DrainDelay != 2*time.Second || cfg.IdempotencyTTL != 24*time.Hour || cfg.DBMaxConns != 10 || cfg.DebugAddr != "" {
t.Fatalf("lab3 defaults = drain %v, key ttl %v, pool %d, debug %q", cfg.DrainDelay, cfg.IdempotencyTTL, cfg.DBMaxConns, cfg.DebugAddr)
}
}
func TestSecretFilesAreRequiredAndNeverEchoed(t *testing.T) {
@@ -92,13 +95,17 @@ func TestSecretFilesAreRequiredAndNeverEchoed(t *testing.T) {
func TestOverrides(t *testing.T) {
cfg, err := config.Load(env(required(t, map[string]string{
"APP_HOST": "127.0.0.1",
"APP_PORT": "9090",
"APP_ENV": "dev",
"APP_LOG_LEVEL": "debug",
"APP_SHUTDOWN_TIMEOUT": "3s",
"APP_MAX_BODY_BYTES": "1024",
"SESSION_TTL_SECONDS": "300",
"APP_HOST": "127.0.0.1",
"APP_PORT": "9090",
"APP_ENV": "dev",
"APP_LOG_LEVEL": "debug",
"APP_SHUTDOWN_TIMEOUT": "3s",
"APP_MAX_BODY_BYTES": "1024",
"SESSION_TTL_SECONDS": "300",
"APP_DRAIN_DELAY": "0s",
"IDEMPOTENCY_TTL_SECONDS": "60",
"DB_MAX_CONNS": "25",
"APP_DEBUG_ADDR": ":9090",
})))
if err != nil {
t.Fatalf("Load error: %v", err)
@@ -109,6 +116,9 @@ func TestOverrides(t *testing.T) {
if cfg.ShutdownTimeout != 3*time.Second || cfg.MaxBodyBytes != 1024 || cfg.SessionTTL != 5*time.Minute {
t.Fatalf("cfg = %+v", cfg)
}
if cfg.DrainDelay != 0 || cfg.IdempotencyTTL != time.Minute || cfg.DBMaxConns != 25 || cfg.DebugAddr != ":9090" {
t.Fatalf("lab3 overrides = drain %v, key ttl %v, pool %d, debug %q", cfg.DrainDelay, cfg.IdempotencyTTL, cfg.DBMaxConns, cfg.DebugAddr)
}
}
func TestInvalidValuesAreReported(t *testing.T) {
@@ -126,10 +136,42 @@ func TestInvalidValuesAreReported(t *testing.T) {
"ttl negative": {"SESSION_TTL_SECONDS": "-5"},
"ttl text": {"SESSION_TTL_SECONDS": "hour"},
"ttl fraction": {"SESSION_TTL_SECONDS": "1.5"},
"drain negative": {"APP_DRAIN_DELAY": "-1s"},
"drain text": {"APP_DRAIN_DELAY": "abc"},
"key ttl zero": {"IDEMPOTENCY_TTL_SECONDS": "0"},
"key ttl text": {"IDEMPOTENCY_TTL_SECONDS": "day"},
"pool zero": {"DB_MAX_CONNS": "0"},
"pool too big": {"DB_MAX_CONNS": "1001"},
"pool text": {"DB_MAX_CONNS": "many"},
"debug addr": {"APP_DEBUG_ADDR": "nonsense"},
}
for name, values := range cases {
if _, err := config.Load(env(required(t, values))); err == nil {
_, err := config.Load(env(required(t, values)))
if err == nil {
t.Errorf("%s: want error", name)
continue
}
for key := range values {
if !strings.Contains(err.Error(), key) {
t.Errorf("%s: error %q does not name %s", name, err, key)
}
}
}
}
func TestLoadMigrateNeedsOnlyTheDatabaseURL(t *testing.T) {
cfg, err := config.LoadMigrate(env(map[string]string{
"DATABASE_URL_FILE": secretFile(t, databaseURL+"\n"),
"APP_ENV": "dev",
"APP_LOG_LEVEL": "warn",
}))
if err != nil {
t.Fatalf("LoadMigrate error: %v", err)
}
if cfg.DatabaseURL != databaseURL || cfg.Env != "dev" || cfg.LogLevel != slog.LevelWarn {
t.Fatalf("cfg = %+v", cfg)
}
if _, err := config.LoadMigrate(env(map[string]string{})); err == nil || !strings.Contains(err.Error(), "DATABASE_URL_FILE") {
t.Fatalf("missing database url: err = %v", err)
}
}
+4 -3
View File
@@ -20,8 +20,9 @@ const (
)
// NewEngine builds an engine whose every response, including routing
// failures and panics, carries X-Request-Id and the contract error body.
func NewEngine(log *slog.Logger, maxBodyBytes int64) *gin.Engine {
// failures and panics, carries X-Instance-Id, X-Request-Id and the contract
// error body.
func NewEngine(log *slog.Logger, maxBodyBytes int64, instanceID string) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
e := gin.New()
// Redirects would answer with text/plain and without a request id.
@@ -29,7 +30,7 @@ func NewEngine(log *slog.Logger, maxBodyBytes int64) *gin.Engine {
e.RedirectFixedPath = false
e.HandleMethodNotAllowed = true
e.Use(requestID(log), accessLog(), recovery(), bodyLimit(maxBodyBytes))
e.Use(instance(instanceID), requestID(log), accessLog(), recovery(), bodyLimit(maxBodyBytes))
e.NoRoute(func(c *gin.Context) { Error(c, apperr.NotFound("route not found")) })
e.NoMethod(func(c *gin.Context) { Fail(c, http.StatusMethodNotAllowed, "invalid_request", "method not allowed") })
return e
+22 -1
View File
@@ -33,6 +33,8 @@ type payload struct {
Count int `json:"count"`
}
const testInstance = "0123456789abcdef"
func newEngine(t *testing.T, logs *bytes.Buffer) *gin.Engine {
t.Helper()
return newEngineAt(t, logs, slog.LevelDebug)
@@ -44,7 +46,7 @@ func newEngineAt(t *testing.T, logs *bytes.Buffer, level slog.Level) *gin.Engine
logs = &bytes.Buffer{}
}
log := slog.New(slog.NewJSONHandler(logs, &slog.HandlerOptions{Level: level}))
e := httpx.NewEngine(log, 64)
e := httpx.NewEngine(log, 64, testInstance)
e.GET("/ok", func(c *gin.Context) { httpx.JSON(c, http.StatusOK, gin.H{"text": "<a&b>"}) })
e.GET("/panic", func(c *gin.Context) { panic("secret detail") })
e.GET("/fail", func(c *gin.Context) { httpx.Error(c, errors.New("db password leaked")) })
@@ -106,6 +108,25 @@ func assertError(t *testing.T, rec *httptest.ResponseRecorder, eb errorBody, sta
}
}
// The balancer spreads one client's requests over the replicas; the header
// is how a client tells which process answered, so no response may lack it.
func TestEveryResponseCarriesInstanceID(t *testing.T) {
e := newEngine(t, nil)
for _, r := range []struct{ method, path string }{
{http.MethodGet, "/ok"},
{http.MethodGet, "/missing"},
{http.MethodDelete, "/ok"},
{http.MethodGet, "/panic"},
{http.MethodGet, "/fail"},
{http.MethodPost, "/decode"},
} {
rec, _ := do(t, e, r.method, r.path, "", nil)
if got := rec.Header().Get("X-Instance-Id"); got != testInstance {
t.Errorf("%s %s (status %d): X-Instance-Id = %q, want %q", r.method, r.path, rec.Code, got, testInstance)
}
}
}
func TestUnknownRouteIsJSON404(t *testing.T) {
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/nope", "", nil)
assertError(t, rec, eb, http.StatusNotFound, "not_found")
+9
View File
@@ -13,6 +13,15 @@ import (
"github.com/gin-gonic/gin"
)
// instance names the process that answered, so a client behind the load
// balancer can tell the replicas apart.
func instance(id string) gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("X-Instance-Id", id)
c.Next()
}
}
// requestID assigns a fresh identifier to every request.
//
// An incoming X-Request-Id is deliberately not reused. This service is
+11
View File
@@ -7,6 +7,8 @@
package ident
import (
"crypto/rand"
"encoding/hex"
"errors"
"time"
@@ -25,6 +27,15 @@ func New() uuid.UUID {
return id
}
// NewAlias names one server process for X-Instance-Id. It is random rather
// than the hostname, so the header reveals nothing about the infrastructure,
// and a restarted process gets a new one.
func NewAlias() string {
var raw [8]byte
_, _ = rand.Read(raw[:]) // crypto/rand.Read never returns an error since Go 1.24.
return hex.EncodeToString(raw[:])
}
// TimeOf extracts the creation time carried by a UUIDv7 as UTC with
// millisecond precision.
func TimeOf(id uuid.UUID) time.Time {
+12
View File
@@ -2,6 +2,7 @@ package ident_test
import (
"bytes"
"regexp"
"testing"
"time"
@@ -70,3 +71,14 @@ func TestParseRejectsNonCanonicalForms(t *testing.T) {
}
}
}
func TestNewAliasIs16HexAndRandom(t *testing.T) {
a, b := ident.NewAlias(), ident.NewAlias()
hex16 := regexp.MustCompile(`^[0-9a-f]{16}$`)
if !hex16.MatchString(a) || !hex16.MatchString(b) {
t.Fatalf("aliases %q, %q are not 16 lowercase hex characters", a, b)
}
if a == b {
t.Fatalf("two aliases are equal: %q", a)
}
}
+5 -5
View File
@@ -1,8 +1,9 @@
// Package postgres opens the connection pool and applies the schema.
//
// Pool size and server-side timeouts are constants rather than settings: they
// bound how long one request can hold a connection, and the request deadline
// of the API is chosen against them.
// Server-side timeouts are constants rather than settings: they bound how
// long one request can hold a connection, and the request deadline of the API
// is chosen against them. The pool size is a setting, because the scaling
// study varies it.
package postgres
import (
@@ -27,7 +28,6 @@ import (
)
const (
maxConns = 10
connectTimeout = time.Second
statementTimeout = 5 * time.Second
idleInTxTimeout = 10 * time.Second
@@ -35,7 +35,7 @@ const (
const codeUniqueViolation = "23505"
func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
func NewPool(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, fmt.Errorf("parse database url: %w", err)
+14 -1
View File
@@ -184,8 +184,21 @@ func TestClassifyMarksUnreachableDatabaseAsUnavailable(t *testing.T) {
}
}
// The pool size is an experiment variable of the scaling study, so it is
// passed in rather than fixed.
func TestNewPoolUsesTheRequestedSize(t *testing.T) {
pool, err := postgres.NewPool(context.Background(), db.DSN, 3)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if got := pool.Config().MaxConns; got != 3 {
t.Fatalf("MaxConns = %d, want 3", got)
}
}
func TestClassifyRealConnectFailure(t *testing.T) {
_, err := postgres.NewPool(context.Background(), "postgres://u:p@127.0.0.1:1/db?connect_timeout=1")
_, err := postgres.NewPool(context.Background(), "postgres://u:p@127.0.0.1:1/db?connect_timeout=1", 1)
if err == nil {
t.Fatal("NewPool to a closed port must fail")
}