Перенесите реализацию ЛР 4 на стенд ЛР 5

This commit is contained in:
2026-11-18 15:33:31 +03:00
parent 276dbdad8a
commit 911d97a77a
153 changed files with 17451 additions and 1 deletions
+200
View File
@@ -0,0 +1,200 @@
// 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"
)
// Allow a 30s binary request, its independent 3s cleanup, and 5s margin.
const defaultShutdownTimeout = 38 * time.Second
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
S3 S3
}
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: defaultShutdownTimeout,
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 = LoadDatabaseURL(lookup); err != nil {
return Config{}, err
}
if cfg.SessionStoreURL, err = secret(lookup, "SESSION_STORE_URL_FILE"); err != nil {
return Config{}, err
}
if _, ok := lookup("S3_ENDPOINT"); ok {
if cfg.S3, err = LoadS3(lookup); 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 = LoadDatabaseURL(lookup); err != nil {
return Migrate{}, err
}
return cfg, nil
}
func LoadDatabaseURL(lookup Lookup) (string, error) {
return secret(lookup, "DATABASE_URL_FILE")
}
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))
}
+190
View File
@@ -0,0 +1,190 @@
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 != 38*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 TestDefaultShutdownTimeoutCoversBinaryLifecycle(t *testing.T) {
cfg, err := config.Load(env(required(t, nil)))
if err != nil {
t.Fatal(err)
}
// Binary requests can use 30s, followed by 3s independent cleanup. Keep
// another 5s for shutdown scheduling and closing the remaining resources.
budget := 30*time.Second + 3*time.Second + 5*time.Second
if cfg.ShutdownTimeout < budget {
t.Fatalf("default shutdown budget %v cannot cover binary request and cleanup budget %v", cfg.ShutdownTimeout, budget)
}
}
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)
}
}
+55
View File
@@ -0,0 +1,55 @@
package config
import (
"fmt"
"strconv"
)
type S3 struct {
Endpoint, Region, Bucket string
AccessKey, SecretKey string
MaxBytes, MaxPixels int64
}
func LoadS3(lookup Lookup) (S3, error) {
cfg := S3{Endpoint: "http://s3:8333", Region: "us-east-1", Bucket: "messenger-attachments", MaxBytes: 10485760, MaxPixels: 40000000}
for key, dest := range map[string]*string{"S3_ENDPOINT": &cfg.Endpoint, "S3_REGION": &cfg.Region, "S3_BUCKET": &cfg.Bucket} {
if v, ok := lookup(key); ok {
*dest = v
}
}
var err error
if cfg.AccessKey, err = secret(lookup, "S3_ACCESS_KEY_ID_FILE"); err != nil {
return S3{}, err
}
if cfg.SecretKey, err = secret(lookup, "S3_SECRET_ACCESS_KEY_FILE"); err != nil {
return S3{}, err
}
for _, p := range []struct {
key string
dest *int64
max int64
}{{"MAX_UPLOAD_BYTES", &cfg.MaxBytes, 10485760}, {"MAX_IMAGE_PIXELS", &cfg.MaxPixels, 40000000}} {
if v, ok := lookup(p.key); ok {
n, e := strconv.ParseInt(v, 10, 64)
if e != nil || n < 1 || n > p.max {
return S3{}, fmt.Errorf("%s must be between 1 and %d", p.key, p.max)
}
*p.dest = n
}
}
return cfg, nil
}
// ReconcileS3 selects the separate listing identity used by background scans.
func ReconcileS3(lookup Lookup) Lookup {
return func(key string) (string, bool) {
if key == "S3_ACCESS_KEY_ID_FILE" {
return lookup("S3_RECONCILE_ACCESS_KEY_ID_FILE")
}
if key == "S3_SECRET_ACCESS_KEY_FILE" {
return lookup("S3_RECONCILE_SECRET_ACCESS_KEY_FILE")
}
return lookup(key)
}
}
+27
View File
@@ -0,0 +1,27 @@
package config_test
import (
"messenger/internal/platform/config"
"testing"
)
func TestS3LimitsAndSecretFiles(t *testing.T) {
values := map[string]string{"S3_ACCESS_KEY_ID_FILE": secretFile(t, "access\n"), "S3_SECRET_ACCESS_KEY_FILE": secretFile(t, "private\n")}
cfg, err := config.LoadS3(env(values))
if err != nil {
t.Fatal(err)
}
if cfg.AccessKey != "access" || cfg.SecretKey != "private" || cfg.MaxBytes != 10485760 || cfg.MaxPixels != 40000000 {
t.Fatal("S3 defaults or secret trimming broken")
}
for _, tc := range []struct{ k, v string }{{"MAX_UPLOAD_BYTES", "0"}, {"MAX_UPLOAD_BYTES", "10485761"}, {"MAX_IMAGE_PIXELS", "40000001"}, {"MAX_IMAGE_PIXELS", "x"}} {
v := map[string]string{}
for k, x := range values {
v[k] = x
}
v[tc.k] = tc.v
if _, err := config.LoadS3(env(v)); err == nil {
t.Fatalf("accepted %s=%s", tc.k, tc.v)
}
}
}