Перенесите реализацию 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
+187
View File
@@ -0,0 +1,187 @@
// Package config reads the process configuration from the environment.
// Settings have defaults suited to the lab stand, except credentials, which
// are required and read from files named by *_FILE variables so that their
// values never appear in the environment. An invalid value stops the process
// at start-up with a message naming the variable, never the secret.
package config
import (
"fmt"
"log/slog"
"net"
"os"
"strconv"
"strings"
"time"
)
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
ShutdownTimeout time.Duration
MaxBodyBytes int64
DatabaseURL string
SessionStoreURL string
SessionTTL time.Duration
// 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 string
}
type Migrate struct {
Logging
DatabaseURL string
}
// Lookup reads one variable, reporting whether it was set; os.LookupEnv
// in production, a map in tests.
type Lookup func(key string) (string, bool)
func Load(lookup Lookup) (Config, error) {
cfg := Config{
Host: "0.0.0.0",
Port: 8080,
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) == "" {
return Config{}, fmt.Errorf("APP_HOST must not be empty")
}
cfg.Host = v
}
if v, ok := lookup("APP_PORT"); ok {
port, err := strconv.Atoi(v)
if err != nil || port < 1 || port > 65535 {
return Config{}, fmt.Errorf("APP_PORT must be an integer between 1 and 65535, got %q", v)
}
cfg.Port = port
}
var err error
if cfg.Logging, err = loadLogging(lookup); err != nil {
return Config{}, err
}
if v, ok := lookup("APP_SHUTDOWN_TIMEOUT"); ok {
d, err := time.ParseDuration(v)
if err != nil || d <= 0 {
return Config{}, fmt.Errorf("APP_SHUTDOWN_TIMEOUT must be a positive duration such as 8s, got %q", v)
}
cfg.ShutdownTimeout = d
}
if v, ok := lookup("APP_MAX_BODY_BYTES"); ok {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n <= 0 {
return Config{}, fmt.Errorf("APP_MAX_BODY_BYTES must be a positive integer, got %q", v)
}
cfg.MaxBodyBytes = n
}
if v, ok := lookup("SESSION_TTL_SECONDS"); ok {
n, err := strconv.ParseUint(v, 10, 32)
if err != nil || n == 0 {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive whole number of seconds, got %q", v)
}
cfg.SessionTTL = time.Duration(n) * time.Second
}
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
}
if cfg.SessionStoreURL, err = secret(lookup, "SESSION_STORE_URL_FILE"); err != nil {
return Config{}, err
}
return cfg, nil
}
func LoadMigrate(lookup Lookup) (Migrate, error) {
var cfg Migrate
var err error
if cfg.Logging, err = loadLogging(lookup); err != nil {
return Migrate{}, err
}
if cfg.DatabaseURL, err = secret(lookup, "DATABASE_URL_FILE"); err != nil {
return Migrate{}, err
}
return cfg, nil
}
func loadLogging(lookup Lookup) (Logging, error) {
l := Logging{Env: "lab", Level: slog.LevelInfo}
if v, ok := lookup("APP_ENV"); ok && strings.TrimSpace(v) != "" {
l.Env = v
}
if v, ok := lookup("APP_LOG_LEVEL"); ok {
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 l, 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) {
path, ok := lookup(key)
if !ok || strings.TrimSpace(path) == "" {
return "", fmt.Errorf("%s must name a file with the value", key)
}
raw, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("%s: cannot read %s: %w", key, path, err)
}
value := strings.TrimSpace(string(raw))
if value == "" {
return "", fmt.Errorf("%s: file %s is empty", key, path)
}
return value, nil
}
func (c Config) Addr() string {
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
}
+177
View File
@@ -0,0 +1,177 @@
package config_test
import (
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"time"
"messenger/internal/platform/config"
)
func env(values map[string]string) func(string) (string, bool) {
return func(key string) (string, bool) {
v, ok := values[key]
return v, ok
}
}
func secretFile(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "secret")
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
return path
}
const (
databaseURL = "postgres://app:s3cret@db:5432/messenger"
sessionStoreURL = "redis://:s3cret@valkey:6379/0"
)
// required holds the variables without defaults, merged with extra.
func required(t *testing.T, extra map[string]string) map[string]string {
t.Helper()
values := map[string]string{
"DATABASE_URL_FILE": secretFile(t, databaseURL+"\n"),
"SESSION_STORE_URL_FILE": secretFile(t, sessionStoreURL+"\r\n"),
}
for k, v := range extra {
values[k] = v
}
return values
}
func TestDefaults(t *testing.T) {
cfg, err := config.Load(env(required(t, nil)))
if err != nil {
t.Fatalf("Load error: %v", err)
}
if cfg.Addr() != "0.0.0.0:8080" {
t.Fatalf("Addr = %q", cfg.Addr())
}
if cfg.Env != "lab" || cfg.Level != slog.LevelInfo {
t.Fatalf("cfg = %+v", cfg)
}
if cfg.ShutdownTimeout != 8*time.Second || cfg.MaxBodyBytes != 65536 {
t.Fatalf("cfg = %+v", cfg)
}
if cfg.DatabaseURL != databaseURL || cfg.SessionStoreURL != sessionStoreURL {
t.Fatalf("urls = %q, %q; want the file contents without line endings", cfg.DatabaseURL, cfg.SessionStoreURL)
}
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) {
for _, key := range []string{"DATABASE_URL_FILE", "SESSION_STORE_URL_FILE"} {
cases := map[string]func(map[string]string){
"unset": func(v map[string]string) { delete(v, key) },
"empty path": func(v map[string]string) { v[key] = "" },
"no file": func(v map[string]string) { v[key] = filepath.Join(t.TempDir(), "missing") },
"blank file": func(v map[string]string) { v[key] = secretFile(t, " \r\n") },
}
for name, breakIt := range cases {
values := required(t, nil)
breakIt(values)
_, err := config.Load(env(values))
if err == nil {
t.Errorf("%s %s: want error", key, name)
continue
}
if !strings.Contains(err.Error(), key) || strings.Contains(err.Error(), "s3cret") {
t.Errorf("%s %s: error must name the variable and hide the secret: %v", key, name, err)
}
}
}
}
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_DRAIN_DELAY": "0s",
"IDEMPOTENCY_TTL_SECONDS": "60",
"DB_MAX_CONNS": "25",
"APP_DEBUG_ADDR": ":9090",
})))
if err != nil {
t.Fatalf("Load error: %v", err)
}
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 {
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) {
cases := map[string]map[string]string{
"port text": {"APP_PORT": "abc"},
"port zero": {"APP_PORT": "0"},
"port too big": {"APP_PORT": "70000"},
"level": {"APP_LOG_LEVEL": "loud"},
"timeout": {"APP_SHUTDOWN_TIMEOUT": "soon"},
"timeout negative": {"APP_SHUTDOWN_TIMEOUT": "-1s"},
"body zero": {"APP_MAX_BODY_BYTES": "0"},
"body text": {"APP_MAX_BODY_BYTES": "big"},
"empty host": {"APP_HOST": ""},
"ttl zero": {"SESSION_TTL_SECONDS": "0"},
"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 {
_, 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.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") {
t.Fatalf("missing database url: err = %v", err)
}
}