feat(app) implemented lab 4

This commit is contained in:
imadev
2026-11-06 19:06:21 +03:00
parent 68968c4a3a
commit b4239f8cf0
63 changed files with 3944 additions and 137 deletions
+130 -15
View File
@@ -5,11 +5,23 @@ package config
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const (
// Configuration may make a limit stricter, never looser.
MaxUploadBytesHardCap = 10 * 1024 * 1024
MaxImagePixelsHardCap = 40_000_000
// MaxJSONBodyBytes is the body budget of every JSON endpoint. It is also
// the slack between the global HTTP body limit and the upload limit, so a
// smaller MAX_UPLOAD_BYTES cannot strangle JSON requests.
MaxJSONBodyBytes = 1 * 1024 * 1024
)
type Config struct {
Host string
Port string
@@ -24,6 +36,30 @@ type Config struct {
StartupWait time.Duration
RunMigrations bool
MigrateOnly bool
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKey string
S3SecretKey string
UploadTimeout time.Duration
DownloadTimeout time.Duration
MaxUploadBytes int64
MaxImagePixels int64
ImageDecodeBytes int64
UploadTempDir string
// HTTP timeouts and body limits are derived once in Load so that app.go
// and the handlers never invent values of their own.
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
UploadDrainLimit int64
HTTPBodyLimit int
ReconcileGrace time.Duration
ReconcileInterval time.Duration
}
func Load() (Config, error) {
@@ -45,17 +81,42 @@ func Load() (Config, error) {
return Config{}, err
}
cfg := Config{
Host: envOr("APP_HOST", "0.0.0.0"),
Port: envOr("APP_PORT", "8080"),
InstanceID: instance,
SessionTTL: time.Duration(sessionTTL) * time.Second,
IdempotencyTTL: time.Duration(idempotencyTTL) * time.Second,
DBMaxConns: int32(maxConns),
DBTimeout: 5 * time.Second,
RedisTimeout: 2 * time.Second,
StartupWait: 30 * time.Second,
maxUpload, err := envInt[int64]("MAX_UPLOAD_BYTES", MaxUploadBytesHardCap, 1, MaxUploadBytesHardCap)
if err != nil {
return Config{}, err
}
maxPixels, err := envInt[int64]("MAX_IMAGE_PIXELS", MaxImagePixelsHardCap, 1, MaxImagePixelsHardCap)
if err != nil {
return Config{}, err
}
decodeMB, err := envInt("IMAGE_DECODE_MEMORY_MB", 256, 32, 4096)
if err != nil {
return Config{}, err
}
cfg := Config{
Host: envOr("APP_HOST", "0.0.0.0"),
Port: envOr("APP_PORT", "8080"),
InstanceID: instance,
SessionTTL: time.Duration(sessionTTL) * time.Second,
IdempotencyTTL: time.Duration(idempotencyTTL) * time.Second,
DBMaxConns: int32(maxConns),
DBTimeout: 5 * time.Second,
RedisTimeout: 2 * time.Second,
StartupWait: 30 * time.Second,
S3Region: envOr("S3_REGION", "us-east-1"),
S3Bucket: envOr("S3_BUCKET", "messenger-attachments"),
ReadTimeout: 30 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 60 * time.Second,
UploadTimeout: 30 * time.Second,
DownloadTimeout: 60 * time.Second,
MaxUploadBytes: maxUpload,
MaxImagePixels: maxPixels,
ImageDecodeBytes: int64(decodeMB) * 1024 * 1024,
UploadTempDir: envOr("UPLOAD_TEMP_DIR", filepath.Join(os.TempDir(), "messenger-uploads")),
}
cfg.deriveHTTPLimits()
if cfg.RunMigrations, err = envBool("RUN_MIGRATIONS", true); err != nil {
return Config{}, err
@@ -63,6 +124,22 @@ func Load() (Config, error) {
if cfg.MigrateOnly, err = envBool("MIGRATE_ONLY", false); err != nil {
return Config{}, err
}
reconcileOnly, err := envBool("RECONCILE_ONLY", false)
if err != nil {
return Config{}, err
}
reconcileGrace, err := envInt("RECONCILE_GRACE_SECONDS", 900, 60, 0)
if err != nil {
return Config{}, err
}
cfg.ReconcileGrace = time.Duration(reconcileGrace) * time.Second
reconcileInterval, err := envInt("RECONCILE_INTERVAL_SECONDS", 300, 10, 0)
if err != nil {
return Config{}, err
}
cfg.ReconcileInterval = time.Duration(reconcileInterval) * time.Second
if cfg.DatabaseURL, err = secret("DATABASE_URL"); err != nil {
return Config{}, err
@@ -75,6 +152,29 @@ func Load() (Config, error) {
return cfg, nil
}
if cfg.S3Endpoint, err = secret("S3_ENDPOINT"); err != nil {
return Config{}, err
}
if cfg.S3Endpoint == "" {
return Config{}, fmt.Errorf("S3_ENDPOINT or S3_ENDPOINT_FILE is required")
}
if cfg.S3AccessKey, err = secret("S3_ACCESS_KEY_ID"); err != nil {
return Config{}, err
}
if cfg.S3AccessKey == "" {
return Config{}, fmt.Errorf("S3_ACCESS_KEY_ID or S3_ACCESS_KEY_ID_FILE is required")
}
if cfg.S3SecretKey, err = secret("S3_SECRET_ACCESS_KEY"); err != nil {
return Config{}, err
}
if cfg.S3SecretKey == "" {
return Config{}, fmt.Errorf("S3_SECRET_ACCESS_KEY or S3_SECRET_ACCESS_KEY_FILE is required")
}
if reconcileOnly {
return cfg, nil
}
if cfg.CacheURL, err = secret("CACHE_URL"); err != nil {
return Config{}, err
}
@@ -94,6 +194,15 @@ func Load() (Config, error) {
return cfg, nil
}
// deriveHTTPLimits is the single place that relates the three HTTP budgets:
// the transport gate must admit both a full upload and a full JSON body, and it
// must leave room for the handler to drain an oversized declared body so the
// client receives a 413 instead of a connection reset.
func (c *Config) deriveHTTPLimits() {
c.UploadDrainLimit = c.MaxUploadBytes + MaxJSONBodyBytes
c.HTTPBodyLimit = int(c.UploadDrainLimit)
}
func instanceID() (string, error) {
if value := strings.TrimSpace(os.Getenv("INSTANCE_ID")); value != "" {
return value, nil
@@ -120,21 +229,27 @@ func envBool(name string, fallback bool) (bool, error) {
return parsed, nil
}
// envInt parses an integer setting; max <= 0 means "no upper bound".
func envInt(name string, fallback, min, max int) (int, error) {
// envInt parses an integer setting into int or int64; max <= 0 means "no upper
// bound". Both widths are needed by Config, and one helper keeps validation
// identical for every numeric variable.
func envInt[T ~int | ~int64](name string, fallback, min, max T) (T, error) {
value := os.Getenv(name)
if value == "" {
return fallback, nil
}
parsed, err := strconv.Atoi(value)
if err != nil || parsed < min || (max > 0 && parsed > max) {
parsed, err := strconv.ParseInt(value, 10, 64)
if err != nil || parsed < int64(min) || (max > 0 && parsed > int64(max)) {
if max > 0 {
return 0, fmt.Errorf("%s must be an integer between %d and %d", name, min, max)
}
return 0, fmt.Errorf("%s must be an integer >= %d", name, min)
}
return parsed, nil
result := T(parsed)
if int64(result) != parsed {
return 0, fmt.Errorf("%s is out of range", name)
}
return result, nil
}
func envOr(name, fallback string) string {
+37
View File
@@ -25,3 +25,40 @@ func TestInstanceIDFallsBackToHostname(t *testing.T) {
t.Fatal("instanceID returned an empty value")
}
}
func TestDerivedHTTPLimits(t *testing.T) {
cfg := Config{MaxUploadBytes: 2 * 1024 * 1024}
cfg.deriveHTTPLimits()
if cfg.UploadDrainLimit != cfg.MaxUploadBytes+MaxJSONBodyBytes {
t.Fatalf("drain limit = %d, want upload + JSON body", cfg.UploadDrainLimit)
}
if cfg.HTTPBodyLimit != int(cfg.UploadDrainLimit) {
t.Fatalf("body limit = %d, want %d", cfg.HTTPBodyLimit, cfg.UploadDrainLimit)
}
if cfg.HTTPBodyLimit-int(cfg.MaxUploadBytes) != MaxJSONBodyBytes {
t.Fatal("transport gate would strangle a full JSON body")
}
}
func TestEnvIntHandlesBothWidths(t *testing.T) {
t.Setenv("TEST_ENV_INT", "42")
small, err := envInt("TEST_ENV_INT", 1, 1, 100)
if err != nil || small != 42 {
t.Fatalf("envInt = %d, %v; want 42, nil", small, err)
}
large, err := envInt[int64]("TEST_ENV_INT", 1, 1, 100)
if err != nil || large != 42 {
t.Fatalf("envInt[int64] = %d, %v; want 42, nil", large, err)
}
}
func TestEnvIntRejectsOutOfRange(t *testing.T) {
for _, value := range []string{"0", "101", "not-a-number"} {
t.Setenv("TEST_ENV_INT", value)
if _, err := envInt("TEST_ENV_INT", 1, 1, 100); err == nil {
t.Fatalf("envInt accepted %q", value)
}
}
}