Implement lab3 scaling, shared idempotency, failure research and defense guide

This commit is contained in:
2026-10-29 21:36:47 +03:00
parent 0ab3a341aa
commit 99c87315cf
58 changed files with 8860 additions and 24 deletions
+93
View File
@@ -0,0 +1,93 @@
// bench is a closed-loop HTTP write generator with reusable connections.
// Credentials arrive only on stdin and never appear in output.
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"os"
"sort"
"sync"
"time"
)
func main() {
base := flag.String("base", "http://localhost:8083", "")
duration := flag.Duration("duration", 5*time.Second, "")
concurrency := flag.Int("concurrency", 16, "")
flag.Parse()
var fixture struct {
Token string `json:"token"`
Chats []string `json:"chats"`
}
if json.NewDecoder(os.Stdin).Decode(&fixture) != nil || len(fixture.Chats) == 0 {
panic("invalid fixture")
}
transport := &http.Transport{MaxIdleConns: 256, MaxIdleConnsPerHost: 256, MaxConnsPerHost: 256}
client := &http.Client{Transport: transport, Timeout: 4 * time.Second}
prefix := fmt.Sprint(time.Now().UnixNano())
start := time.Now()
deadline := start.Add(*duration)
var wg sync.WaitGroup
var mu sync.Mutex
all := []float64{}
errors := map[int]int{}
instances := map[string]int{}
for worker := 0; worker < *concurrency; worker++ {
wg.Add(1)
go func(worker int) {
defer wg.Done()
latencies := []float64{}
bad := map[int]int{}
observed := map[string]int{}
for n := 0; time.Now().Before(deadline); n++ {
chat := fixture.Chats[(worker+n)%len(fixture.Chats)]
req, _ := http.NewRequest("POST", *base+"/api/v1/chats/"+chat+"/messages", bytes.NewBufferString(`{"text":"`+prefix+` fixed payload 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+fixture.Token)
req.Header.Set("Idempotency-Key", fmt.Sprintf("%s-%d-%d", prefix, worker, n))
t := time.Now()
res, e := client.Do(req)
if e != nil {
bad[0]++
continue
}
_, e = io.Copy(io.Discard, res.Body)
res.Body.Close()
if res.StatusCode == 201 && e == nil {
latencies = append(latencies, float64(time.Since(t).Microseconds())/1000)
observed[res.Header.Get("X-Instance-Id")]++
} else {
bad[res.StatusCode]++
}
}
mu.Lock()
all = append(all, latencies...)
for k, v := range bad {
errors[k] += v
}
for k, v := range observed {
instances[k] += v
}
mu.Unlock()
}(worker)
}
wg.Wait()
elapsed := time.Since(start).Seconds()
sort.Float64s(all)
p := func(q float64) float64 {
if len(all) == 0 {
return 0
}
return all[int(float64(len(all)-1)*q)]
}
failed := 0
for _, v := range errors {
failed += v
}
json.NewEncoder(os.Stdout).Encode(map[string]any{"duration_seconds": elapsed, "concurrency": *concurrency, "successful_requests": len(all), "successful_rps": float64(len(all)) / elapsed, "failed_requests": failed, "error_fraction": float64(failed) / float64(len(all)+failed), "errors_by_status": errors, "p50_ms": p(.5), "p95_ms": p(.95), "p99_ms": p(.99), "instances": instances, "latency_scope": "successful responses only; closed loop"})
}
+154
View File
@@ -0,0 +1,154 @@
package main
import (
"context"
"encoding/base64"
"errors"
"fmt"
"github.com/redis/go-redis/v9"
"log/slog"
"mtusi/messenger/internal/database"
"mtusi/messenger/internal/messenger"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
)
func env(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func main() {
if err := run(); err != nil {
slog.Error("server failed", "error", err)
os.Exit(1)
}
}
func run() error {
host := env("APP_HOST", "0.0.0.0")
port := env("APP_PORT", "8080")
p, err := strconv.Atoi(port)
if err != nil || p < 1 || p > 65535 {
return fmt.Errorf("invalid APP_PORT")
}
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
c := http.Client{Timeout: time.Second}
r, e := c.Get("http://127.0.0.1:" + port + "/health/ready")
if e != nil {
return e
}
defer r.Body.Close()
if r.StatusCode != 200 {
return fmt.Errorf("not ready: %d", r.StatusCode)
}
return nil
}
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
ttl, err := strconv.Atoi(env("SESSION_TTL_SECONDS", "3600"))
if err != nil || ttl < 1 || ttl > 86400 {
return fmt.Errorf("SESSION_TTL_SECONDS must be 1..86400")
}
databaseURL, err := secret("DATABASE_URL_FILE")
if err != nil {
return err
}
cacheURL, err := secret("CACHE_URL_FILE")
if err != nil {
return err
}
cursorKey, err := secret("CURSOR_KEY_FILE")
if err != nil {
return err
}
key, err := base64.RawURLEncoding.DecodeString(cursorKey)
if err != nil || len(key) != 32 {
return fmt.Errorf("invalid cursor key")
}
startup, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
pool, err := database.Open(startup, databaseURL)
if err != nil {
return err
}
defer pool.Close()
if len(os.Args) == 2 && os.Args[1] == "migrate" {
return database.Migrate(startup, pool)
}
opts, err := redis.ParseURL(cacheURL)
if err != nil {
return fmt.Errorf("invalid cache configuration")
}
opts.DialTimeout = 60 * time.Millisecond
opts.ReadTimeout = 60 * time.Millisecond
opts.WriteTimeout = 60 * time.Millisecond
opts.PoolTimeout = 60 * time.Millisecond
opts.ContextTimeoutEnabled = true
opts.MaxRetries = -1
opts.PoolSize = 10
cache := redis.NewClient(opts)
defer cache.Close()
api := messenger.New(pool, cache, key, ttl, log)
srv := &http.Server{Addr: net.JoinHostPort(host, port), Handler: api, ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
if os.Getenv("POOL_DIAGNOSTICS") == "1" {
go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
stat := pool.Stat()
log.Info("pool", "instance", os.Getenv("HOSTNAME"), "acquires", stat.AcquireCount(), "empty_acquires", stat.EmptyAcquireCount(), "wait_ns", stat.EmptyAcquireWaitTime().Nanoseconds(), "in_use", stat.AcquiredConns(), "max", stat.MaxConns())
}
}
}()
}
done := make(chan error, 1)
go func() {
log.Info("listening", "address", srv.Addr, "session_store", "postgres", "profile_cache", "valkey", "environment", env("APP_ENV", "lab"))
done <- srv.ListenAndServe()
}()
select {
case err := <-done:
return err
case <-ctx.Done():
}
start := time.Now()
api.Stop()
log.Info("shutdown started")
shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(shutdown); err != nil {
_ = srv.Close()
return err
}
err = <-done
if !errors.Is(err, http.ErrServerClosed) {
return err
}
log.Info("shutdown completed", "duration_ms", time.Since(start).Milliseconds())
return nil
}
func secret(name string) (string, error) {
path := os.Getenv(name)
if path == "" {
return "", fmt.Errorf("missing %s", name)
}
raw, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("cannot read %s", name)
}
return strings.TrimSpace(string(raw)), nil
}