forked from mtusi2026/mtusi2026lab3
Lab3 baseline: HAProxy, replicated stateless API, shared PostgreSQL/Valkey, idempotent messages
This commit is contained in:
@@ -0,0 +1,273 @@
|
||||
// Command messenger runs the lab3 HTTP API and the container healthcheck
|
||||
// helper. PostgreSQL holds users, chats, membership, messages and idempotency
|
||||
// records; Valkey holds server-side sessions shared by every API replica.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab3/internal/api"
|
||||
"mtusi.ru/messenger-lab3/internal/config"
|
||||
"mtusi.ru/messenger-lab3/internal/session"
|
||||
"mtusi.ru/messenger-lab3/internal/store"
|
||||
"mtusi.ru/messenger-lab3/internal/uuid"
|
||||
)
|
||||
|
||||
// Overridden at build time with -X main.version=... and -X main.revision=...
|
||||
var (
|
||||
version = "dev"
|
||||
revision = "unknown"
|
||||
)
|
||||
|
||||
const idempotencyRetention = 24 * time.Hour
|
||||
|
||||
func main() {
|
||||
healthcheck := flag.Bool("healthcheck", false, "probe the local liveness endpoint and exit 0/1")
|
||||
flag.Parse()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
if *healthcheck {
|
||||
os.Exit(runHealthcheck(cfg))
|
||||
}
|
||||
|
||||
logger := newLogger(cfg)
|
||||
ctx := context.Background()
|
||||
instanceID := instanceIdentity()
|
||||
|
||||
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
|
||||
MaxConns: cfg.DBMaxConns,
|
||||
MinConns: cfg.DBMinConns,
|
||||
ConnectTimeout: cfg.DBConnectTimeout,
|
||||
StatementTimeout: cfg.DBStatementTimeout,
|
||||
QueryTimeout: cfg.QueryTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("database configuration failed", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
defer repository.Close()
|
||||
|
||||
if err := waitForDatabase(ctx, repository, cfg.StartupTimeout, logger); err != nil {
|
||||
logger.Error("postgres did not become ready", "timeout_seconds", int(cfg.StartupTimeout.Seconds()), "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
sessions, err := session.Open(cfg.CacheURL, session.Options{
|
||||
PoolSize: cfg.CachePoolSize,
|
||||
DialTimeout: cfg.CacheTimeout,
|
||||
IOTimeout: cfg.CacheTimeout,
|
||||
TTL: cfg.SessionTTL,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("session store configuration failed", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
defer func() { _ = sessions.Close() }()
|
||||
|
||||
app, err := api.New(repository, sessions, logger, instanceID, version)
|
||||
if err != nil {
|
||||
logger.Error("application initialization failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
Handler: app.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 20 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20,
|
||||
}
|
||||
|
||||
address := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
|
||||
listener, err := net.Listen("tcp", address)
|
||||
if err != nil {
|
||||
logger.Error("listen failed", "address", address, "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Operator-only stats listener. It is bound to container loopback by
|
||||
// default and is not published by compose, so it cannot bypass the LB.
|
||||
var metricsServer *http.Server
|
||||
if cfg.MetricsAddr != "off" {
|
||||
metricsMux := http.NewServeMux()
|
||||
metricsMux.HandleFunc("/internal/stats", app.InternalStatsHandler)
|
||||
metricsServer = &http.Server{
|
||||
Handler: metricsMux,
|
||||
ReadHeaderTimeout: 2 * time.Second,
|
||||
ReadTimeout: 5 * time.Second,
|
||||
WriteTimeout: 5 * time.Second,
|
||||
}
|
||||
metricsListener, listenErr := net.Listen("tcp", cfg.MetricsAddr)
|
||||
if listenErr != nil {
|
||||
logger.Error("metrics listen failed", "address", cfg.MetricsAddr, "error", listenErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
go func() {
|
||||
if serveErr := metricsServer.Serve(metricsListener); serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) {
|
||||
logger.Error("metrics server stopped unexpectedly", "error", serveErr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
pruneCtx, pruneCancel := context.WithCancel(ctx)
|
||||
defer pruneCancel()
|
||||
go pruneIdempotency(pruneCtx, repository, logger)
|
||||
|
||||
logger.Info("server listening",
|
||||
"address", listener.Addr().String(),
|
||||
"env", cfg.Env,
|
||||
"instance_id", instanceID,
|
||||
"version", version,
|
||||
"revision", revision,
|
||||
"session_ttl_seconds", int(cfg.SessionTTL.Seconds()),
|
||||
"shutdown_timeout_seconds", int(cfg.ShutdownTimeout.Seconds()),
|
||||
"shutdown_drain_seconds", int(cfg.ShutdownDrain.Seconds()),
|
||||
"db_max_conns", cfg.DBMaxConns,
|
||||
)
|
||||
|
||||
serveErrors := make(chan error, 1)
|
||||
go func() {
|
||||
serveErrors <- server.Serve(listener)
|
||||
}()
|
||||
|
||||
signals := make(chan os.Signal, 1)
|
||||
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
select {
|
||||
case received := <-signals:
|
||||
logger.Info("shutdown initiated", "signal", received.String(), "instance_id", instanceID)
|
||||
// Stop advertising readiness first. The load balancer removes this
|
||||
// backend during the drain window while the process still accepts
|
||||
// requests, so in-flight work is not cut off by the health transition.
|
||||
app.SetReady(false)
|
||||
if cfg.ShutdownDrain > 0 {
|
||||
logger.Info("draining", "seconds", int(cfg.ShutdownDrain.Seconds()))
|
||||
time.Sleep(cfg.ShutdownDrain)
|
||||
}
|
||||
started := time.Now()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Error("graceful shutdown failed", "error", err)
|
||||
_ = server.Close()
|
||||
os.Exit(1)
|
||||
}
|
||||
if metricsServer != nil {
|
||||
_ = metricsServer.Close()
|
||||
}
|
||||
pruneCancel()
|
||||
logger.Info("shutdown complete",
|
||||
"instance_id", instanceID,
|
||||
"elapsed_ms", float64(time.Since(started).Microseconds())/1000.0,
|
||||
)
|
||||
os.Exit(0)
|
||||
case err := <-serveErrors:
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
logger.Error("server stopped unexpectedly", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// instanceIdentity is stable for the lifetime of this process and unique per
|
||||
// container. INSTANCE_ID overrides it; otherwise the container hostname is the
|
||||
// actual process identity, which lets scripts/stop-one.sh map an X-Instance-Id
|
||||
// response to exactly one Docker container. lab7 replaces this with an opaque
|
||||
// alias that does not reveal a hostname.
|
||||
func instanceIdentity() string {
|
||||
if value := strings.TrimSpace(os.Getenv("INSTANCE_ID")); value != "" {
|
||||
return value
|
||||
}
|
||||
if hostname, err := os.Hostname(); err == nil && strings.TrimSpace(hostname) != "" {
|
||||
return hostname
|
||||
}
|
||||
return uuid.NewRandom(8)
|
||||
}
|
||||
|
||||
func newLogger(cfg config.Config) *slog.Logger {
|
||||
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel})
|
||||
return slog.New(handler).With("service", "messenger-lab3", "app_env", cfg.Env)
|
||||
}
|
||||
|
||||
func waitForDatabase(ctx context.Context, repository *store.Store, timeout time.Duration, logger *slog.Logger) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
attempt := 0
|
||||
for {
|
||||
attempt++
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
err := repository.Ping(pingCtx)
|
||||
cancel()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return err
|
||||
}
|
||||
logger.Debug("waiting for postgres", "attempt", attempt, "error", err)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func pruneIdempotency(ctx context.Context, repository *store.Store, logger *slog.Logger) {
|
||||
run := func() {
|
||||
pruneCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
deleted, err := repository.PruneIdempotency(pruneCtx, idempotencyRetention)
|
||||
cancel()
|
||||
if err != nil && ctx.Err() == nil {
|
||||
logger.Warn("idempotency prune failed", "error", err)
|
||||
return
|
||||
}
|
||||
if deleted > 0 {
|
||||
logger.Info("pruned expired idempotency records", "rows", deleted, "retention_hours", 24)
|
||||
}
|
||||
}
|
||||
run()
|
||||
ticker := time.NewTicker(time.Hour)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
run()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runHealthcheck is compiled into the same binary as the server, so the
|
||||
// runtime image needs no curl, wget or shell. It always talks to loopback
|
||||
// inside the container, independently of APP_HOST.
|
||||
func runHealthcheck(cfg config.Config) int {
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
url := "http://127.0.0.1:" + strconv.Itoa(cfg.Port) + "/health/live"
|
||||
response, err := client.Get(url) //nolint:gosec // fixed loopback URL built from a validated port
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "healthcheck request failed:", err)
|
||||
return 1
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, _ = io.Copy(io.Discard, response.Body)
|
||||
if response.StatusCode != http.StatusOK {
|
||||
fmt.Fprintln(os.Stderr, "healthcheck status:", response.StatusCode)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
Reference in New Issue
Block a user