Исправить замечания ревью кода: убрать повтор в AppendOnce за счёт запаса у чистки ключей, вынести MessagePayload и SameContent, принять X-Request-Id от балансировщика, упростить фоновые задачи сервера, сократить комментарии

This commit is contained in:
2026-11-04 12:19:49 +03:00
parent c9d0f73221
commit 7fbd781ca3
25 changed files with 207 additions and 247 deletions
+29 -20
View File
@@ -15,31 +15,41 @@ import (
"time"
)
// Logging selects the log format, text for dev and JSON otherwise, and the
// level.
type Logging struct {
Env string
Level slog.Level
}
func (l Logging) NewLogger() *slog.Logger {
opts := &slog.HandlerOptions{Level: l.Level}
if l.Env == "dev" {
return slog.New(slog.NewTextHandler(os.Stdout, opts))
}
return slog.New(slog.NewJSONHandler(os.Stdout, opts))
}
type Config struct {
Logging
Host string
Port int
Env string
LogLevel slog.Level
ShutdownTimeout time.Duration
MaxBodyBytes int64
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 keeps a stopping process serving with readiness off; 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 enables the internal expvar listener when set.
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
Logging
DatabaseURL string
}
@@ -51,8 +61,6 @@ func Load(lookup Lookup) (Config, error) {
cfg := Config{
Host: "0.0.0.0",
Port: 8080,
Env: "lab",
LogLevel: slog.LevelInfo,
ShutdownTimeout: 8 * time.Second,
MaxBodyBytes: 64 * 1024,
SessionTTL: time.Hour,
@@ -74,7 +82,7 @@ func Load(lookup Lookup) (Config, error) {
cfg.Port = port
}
var err error
if cfg.Env, cfg.LogLevel, err = logging(lookup, cfg.Env, cfg.LogLevel); err != nil {
if cfg.Logging, err = loadLogging(lookup); err != nil {
return Config{}, err
}
if v, ok := lookup("APP_SHUTDOWN_TIMEOUT"); ok {
@@ -135,9 +143,9 @@ func Load(lookup Lookup) (Config, error) {
}
func LoadMigrate(lookup Lookup) (Migrate, error) {
cfg := Migrate{Env: "lab", LogLevel: slog.LevelInfo}
var cfg Migrate
var err error
if cfg.Env, cfg.LogLevel, err = logging(lookup, cfg.Env, cfg.LogLevel); err != nil {
if cfg.Logging, err = loadLogging(lookup); err != nil {
return Migrate{}, err
}
if cfg.DatabaseURL, err = secret(lookup, "DATABASE_URL_FILE"); err != nil {
@@ -146,16 +154,17 @@ func LoadMigrate(lookup Lookup) (Migrate, error) {
return cfg, nil
}
func logging(lookup Lookup, env string, level slog.Level) (string, slog.Level, error) {
func loadLogging(lookup Lookup) (Logging, error) {
l := Logging{Env: "lab", Level: slog.LevelInfo}
if v, ok := lookup("APP_ENV"); ok && strings.TrimSpace(v) != "" {
env = v
l.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)
if err := l.Level.UnmarshalText([]byte(v)); err != nil {
return Logging{}, fmt.Errorf("APP_LOG_LEVEL must be debug, info, warn or error, got %q", v)
}
}
return env, level, nil
return l, nil
}
// secret reads the file named by the variable; surrounding whitespace,
+3 -3
View File
@@ -53,7 +53,7 @@ func TestDefaults(t *testing.T) {
if cfg.Addr() != "0.0.0.0:8080" {
t.Fatalf("Addr = %q", cfg.Addr())
}
if cfg.Env != "lab" || cfg.LogLevel != slog.LevelInfo {
if cfg.Env != "lab" || cfg.Level != slog.LevelInfo {
t.Fatalf("cfg = %+v", cfg)
}
if cfg.ShutdownTimeout != 8*time.Second || cfg.MaxBodyBytes != 65536 {
@@ -110,7 +110,7 @@ func TestOverrides(t *testing.T) {
if err != nil {
t.Fatalf("Load error: %v", err)
}
if cfg.Addr() != "127.0.0.1:9090" || cfg.Env != "dev" || cfg.LogLevel != slog.LevelDebug {
if cfg.Addr() != "127.0.0.1:9090" || cfg.Env != "dev" || cfg.Level != slog.LevelDebug {
t.Fatalf("cfg = %+v", cfg)
}
if cfg.ShutdownTimeout != 3*time.Second || cfg.MaxBodyBytes != 1024 || cfg.SessionTTL != 5*time.Minute {
@@ -168,7 +168,7 @@ func TestLoadMigrateNeedsOnlyTheDatabaseURL(t *testing.T) {
if err != nil {
t.Fatalf("LoadMigrate error: %v", err)
}
if cfg.DatabaseURL != databaseURL || cfg.Env != "dev" || cfg.LogLevel != slog.LevelWarn {
if cfg.DatabaseURL != databaseURL || cfg.Env != "dev" || cfg.Level != slog.LevelWarn {
t.Fatalf("cfg = %+v", cfg)
}
if _, err := config.LoadMigrate(env(map[string]string{})); err == nil || !strings.Contains(err.Error(), "DATABASE_URL_FILE") {
+16 -4
View File
@@ -193,10 +193,22 @@ func TestSuccessResponseHeadersAndEscaping(t *testing.T) {
}
}
func TestRequestIDIsGeneratedNotEchoed(t *testing.T) {
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": "client-chosen"})
if got := rec.Header().Get("X-Request-Id"); got == "" || got == "client-chosen" {
t.Fatalf("X-Request-Id = %q, want a server generated value", got)
// The balancer sets X-Request-Id on every request, overwriting what the
// client sent; the API keeps it so that one id spans both logs.
func TestRequestIDFromTheBalancerIsKept(t *testing.T) {
const fromLB = "0123456789abcdef0123456789abcdef"
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": fromLB})
if got := rec.Header().Get("X-Request-Id"); got != fromLB {
t.Fatalf("X-Request-Id = %q, want %q", got, fromLB)
}
}
func TestMalformedRequestIDIsReplaced(t *testing.T) {
for _, bad := range []string{"has space", "semi;colon", "tab\there", strings.Repeat("a", 65)} {
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": bad})
if got := rec.Header().Get("X-Request-Id"); got == "" || got == bad {
t.Errorf("X-Request-Id for %q = %q, want a generated value", bad, got)
}
}
}
+17 -13
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"log/slog"
"net/http"
"regexp"
"runtime/debug"
"time"
@@ -22,22 +23,17 @@ func instance(id string) gin.HandlerFunc {
}
}
// requestID assigns a fresh identifier to every request.
//
// An incoming X-Request-Id is deliberately not reused. This service is
// client-facing: there is no trusted upstream that could have minted the
// value, so honouring it would let any caller pick an arbitrary string that
// ends up in logs (log injection, unbounded length) or collides with another
// request and corrupts log correlation. Reusing the header is the right
// choice only when the caller is a trusted proxy or a sibling service that
// propagates one id across a chain of calls.
var requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9-]{1,64}$`)
// requestID keeps the X-Request-Id set by the load balancer, which overwrites
// any value a client sends; a malformed value is replaced, so a direct caller
// cannot inject into the logs.
func requestID(log *slog.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
var raw [16]byte
if _, err := rand.Read(raw[:]); err != nil {
panic("httpx: random source unavailable: " + err.Error())
id := c.GetHeader("X-Request-Id")
if !requestIDPattern.MatchString(id) {
id = newRequestID()
}
id := hex.EncodeToString(raw[:])
c.Set(keyRequestID, id)
c.Set(keyLogger, log)
c.Writer.Header().Set("X-Request-Id", id)
@@ -45,6 +41,14 @@ func requestID(log *slog.Logger) gin.HandlerFunc {
}
}
func newRequestID() string {
var raw [16]byte
if _, err := rand.Read(raw[:]); err != nil {
panic("httpx: random source unavailable: " + err.Error())
}
return hex.EncodeToString(raw[:])
}
// accessLog writes one line per request at a level that follows the
// outcome (2xx debug, 4xx info, 5xx error), so the ordinary log level decides
// how much traffic is recorded. Headers, query strings and bodies are never
+2 -3
View File
@@ -27,9 +27,8 @@ 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.
// NewAlias names one server process for X-Instance-Id; random rather than the
// hostname, so the header reveals nothing about the infrastructure.
func NewAlias() string {
var raw [8]byte
_, _ = rand.Read(raw[:]) // crypto/rand.Read never returns an error since Go 1.24.
+6 -8
View File
@@ -2,8 +2,7 @@
//
// 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.
// is chosen against them.
package postgres
import (
@@ -75,21 +74,20 @@ func NewPool(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, er
return pool, nil
}
// Migrate applies pending migrations and returns the versions it applied. A
// session advisory lock serialises concurrent starts, so several API
// replicas may call it at once; applied versions are recorded, which makes a
// repeated run a no-op.
// Migrate applies pending migrations and returns their versions; a session
// advisory lock makes overlapping runs wait for each other.
func Migrate(ctx context.Context, pool *pgxpool.Pool) ([]int64, error) {
db := stdlib.OpenDBFromPool(pool)
defer db.Close()
locker, err := lock.NewPostgresSessionLocker()
if err != nil {
return nil, fmt.Errorf("migration lock: %w", err)
}
db := stdlib.OpenDBFromPool(pool)
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.FS, goose.WithSessionLocker(locker))
if err != nil {
db.Close()
return nil, fmt.Errorf("load migrations: %w", err)
}
defer provider.Close()
results, err := provider.Up(ctx)
if err != nil {
return nil, fmt.Errorf("apply migrations: %w", err)
@@ -190,8 +190,6 @@ 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 {