Перенесите реализацию lab3 и сохраните серии нагрузочных экспериментов

This commit is contained in:
2026-11-16 12:17:15 +03:00
parent ec540a1a72
commit b323f2dab9
109 changed files with 10747 additions and 0 deletions
+125
View File
@@ -0,0 +1,125 @@
// Command server starts the messenger API over PostgreSQL and Valkey.
package main
import (
"context"
"expvar"
"fmt"
"log/slog"
"net"
"os"
"os/signal"
"runtime"
"sync"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/app"
"messenger/internal/chat"
"messenger/internal/platform/config"
"messenger/internal/platform/ident"
"messenger/internal/platform/postgres"
"messenger/internal/platform/valkey"
"messenger/internal/server"
)
const keyCleanupEvery = 10 * time.Minute
func main() {
cfg, err := config.Load(os.LookupEnv)
if err != nil {
fmt.Fprintln(os.Stderr, "configuration error:", err)
os.Exit(2)
}
alias := ident.NewAlias()
log := cfg.NewLogger().With("instance", alias)
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
if err := run(ctx, log, cfg, alias); err != nil {
log.Error("server stopped with error", "error", err.Error())
os.Exit(1)
}
}
// run connects the dependencies before it listens, so the port accepts
// 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 {
return err
}
defer pool.Close()
sessions, err := valkey.NewClient(ctx, cfg.SessionStoreURL)
if err != nil {
return err
}
defer sessions.Close()
ln, err := net.Listen("tcp", cfg.Addr())
if err != nil {
return fmt.Errorf("listen on %s: %w", cfg.Addr(), err)
}
defer ln.Close()
log.Info("starting", "env", cfg.Env, "addr", cfg.Addr(),
"gomaxprocs", runtime.GOMAXPROCS(0), "db_max_conns", cfg.DBMaxConns,
"drain_delay", cfg.DrainDelay.String(), "shutdown_timeout", cfg.ShutdownTimeout.String(),
"session_ttl", cfg.SessionTTL.String(), "idempotency_ttl", cfg.IdempotencyTTL.String())
a := app.New(app.Deps{
Log: log,
DB: pool,
Sessions: sessions,
SessionTTL: cfg.SessionTTL,
MaxBodyBytes: cfg.MaxBodyBytes,
InstanceID: alias,
IdempotencyTTL: cfg.IdempotencyTTL,
})
var debugLn net.Listener
if cfg.DebugAddr != "" {
if debugLn, err = net.Listen("tcp", cfg.DebugAddr); err != nil {
return fmt.Errorf("listen on %s: %w", cfg.DebugAddr, err)
}
publishDebugVars(alias, pool)
}
ctx, cancel := context.WithCancel(ctx)
var background sync.WaitGroup
background.Go(func() { chat.RunKeyCleanup(ctx, log, a.Chats, keyCleanupEvery) })
if debugLn != nil {
background.Go(func() {
if err := server.RunDebug(ctx, log, debugLn, expvar.Handler()); err != nil {
log.Error("debug listener stopped", "error", err.Error())
}
})
}
err = server.Run(ctx, log, ln, a.Engine, a.Health, cfg.DrainDelay, cfg.ShutdownTimeout)
cancel()
background.Wait()
return err
}
// 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) }))
expvar.Publish("pgxpool", expvar.Func(func() any {
s := pool.Stat()
return map[string]any{
"acquire_count": s.AcquireCount(),
"acquire_duration_ms": s.AcquireDuration().Milliseconds(),
"acquired_conns": s.AcquiredConns(),
"idle_conns": s.IdleConns(),
"total_conns": s.TotalConns(),
"max_conns": s.MaxConns(),
"empty_acquire_count": s.EmptyAcquireCount(),
"empty_acquire_wait_ms": s.EmptyAcquireWaitTime().Milliseconds(),
"canceled_acquire_count": s.CanceledAcquireCount(),
"new_conns_count": s.NewConnsCount(),
}
}))
}
+96
View File
@@ -0,0 +1,96 @@
package main
import (
"context"
"fmt"
"io"
"log/slog"
"net"
"os"
"testing"
"time"
"messenger/internal/platform/config"
"messenger/internal/testenv"
)
var (
db *testenv.DB
kv *testenv.KV
)
func TestMain(m *testing.M) {
ctx := context.Background()
var err error
if db, err = testenv.StartPostgres(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if kv, err = testenv.StartValkey(ctx); err != nil {
db.Close()
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
code := m.Run()
kv.Close()
db.Close()
os.Exit(code)
}
// A start-up failure after the background work began must still end the
// process with an error, not leave it waiting for a signal.
func TestRunFailsFastWhenTheDebugListenerCannotStart(t *testing.T) {
if err := runWithBusyDebugAddr(t, 0); err == nil {
t.Fatal("run succeeded on a busy debug address")
}
}
func TestFailedStartReleasesTheAPIPort(t *testing.T) {
probe, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := probe.Addr().(*net.TCPAddr).Port
probe.Close()
if err := runWithBusyDebugAddr(t, port); err == nil {
t.Fatal("run succeeded on a busy debug address")
}
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
t.Fatalf("the API port is still taken after the failed start: %v", err)
}
ln.Close()
}
func runWithBusyDebugAddr(t *testing.T, port int) error {
t.Helper()
busy, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer busy.Close()
cfg := config.Config{
Host: "127.0.0.1",
Port: port,
ShutdownTimeout: time.Second,
MaxBodyBytes: 1024,
DatabaseURL: db.DSN,
SessionStoreURL: kv.URL,
SessionTTL: time.Hour,
IdempotencyTTL: time.Hour,
DBMaxConns: 2,
DebugAddr: busy.Addr().String(),
}
done := make(chan error, 1)
go func() {
done <- run(context.Background(), slog.New(slog.NewTextHandler(io.Discard, nil)), cfg, "alias")
}()
select {
case err := <-done:
return err
case <-time.After(10 * time.Second):
t.Fatal("run hung instead of returning the listen error")
return nil
}
}