Исправить замечания ревью кода: убрать повтор в 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
+10 -24
View File
@@ -25,7 +25,6 @@ import (
"messenger/internal/server"
)
// keyCleanupEvery is how often each replica deletes expired Idempotency-Keys.
const keyCleanupEvery = 10 * time.Minute
func main() {
@@ -34,10 +33,9 @@ func main() {
fmt.Fprintln(os.Stderr, "configuration error:", err)
os.Exit(2)
}
// Every log line carries the alias that this process sends as
// X-Instance-Id, so a response can be matched to its replica's log.
alias := ident.NewAlias()
log := newLogger(cfg).With("instance", alias)
log := cfg.NewLogger().With("instance", alias)
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
@@ -49,8 +47,7 @@ func main() {
}
// run connects the dependencies before it listens, so the port accepts
// connections only once they answer. The schema is applied beforehand by the
// separate migrate command, once per deployment rather than by every replica.
// connections only once they answer.
func run(ctx context.Context, log *slog.Logger, cfg config.Config, alias string) error {
pool, err := postgres.NewPool(ctx, cfg.DatabaseURL, cfg.DBMaxConns)
if err != nil {
@@ -88,12 +85,8 @@ func run(ctx context.Context, log *slog.Logger, cfg config.Config, alias string)
publishDebugVars(alias, pool)
}
// The background work ends with the server: on a signal, and also when
// the server fails, so the deferred Wait cannot block the exit.
var background sync.WaitGroup
defer background.Wait() // before the deferred pool.Close
ctx, cancel := context.WithCancel(ctx)
defer cancel() // before Wait
var background sync.WaitGroup
background.Go(func() { chat.RunKeyCleanup(ctx, log, a.Chats, keyCleanupEvery) })
if debugLn != nil {
background.Go(func() {
@@ -103,13 +96,13 @@ func run(ctx context.Context, log *slog.Logger, cfg config.Config, alias string)
})
}
return server.Run(ctx, log, ln, a.Engine, a.Health, cfg.DrainDelay, cfg.ShutdownTimeout)
err = server.Run(ctx, log, ln, a.Engine, a.Health, cfg.DrainDelay, cfg.ShutdownTimeout)
cancel()
background.Wait()
return err
}
// publishDebugVars exposes, next to the runtime's memstats, what the scaling
// study needs from a replica: who it is, how many CPUs Go uses inside the
// container's limit, and how often requests had to wait for a pooled
// database connection.
// publishDebugVars adds to expvar what the load tests read from a replica.
func publishDebugVars(alias string, pool *pgxpool.Pool) {
expvar.NewString("instance").Set(alias)
expvar.Publish("gomaxprocs", expvar.Func(func() any { return runtime.GOMAXPROCS(0) }))
@@ -125,14 +118,7 @@ func publishDebugVars(alias string, pool *pgxpool.Pool) {
"empty_acquire_count": s.EmptyAcquireCount(),
"empty_acquire_wait_ms": s.EmptyAcquireWaitTime().Milliseconds(),
"canceled_acquire_count": s.CanceledAcquireCount(),
"new_conns_count": s.NewConnsCount(),
}
}))
}
func newLogger(cfg config.Config) *slog.Logger {
opts := &slog.HandlerOptions{Level: cfg.LogLevel}
if cfg.Env == "dev" {
return slog.New(slog.NewTextHandler(os.Stdout, opts))
}
return slog.New(slog.NewJSONHandler(os.Stdout, opts))
}