Добавить 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)
}
}