Files
mtusi2026lab3/main.go
T

117 lines
3.1 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
command := "serve"
if len(os.Args) > 1 {
command = os.Args[1]
}
switch command {
case "serve":
os.Exit(serve())
case "migrate":
os.Exit(migrateCommand())
case "healthcheck":
os.Exit(healthcheck())
default:
fmt.Fprintln(os.Stderr, "usage: messenger [serve|migrate|healthcheck]")
os.Exit(2)
}
}
func migrateCommand() int {
cfg, err := loadConfig()
if err != nil {
log.Printf("config error: %v", err)
return 1
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
if err := runMigrations(ctx, cfg.DatabaseURL); err != nil {
log.Printf("migrate failed: %v", err)
return 1
}
return 0
}
// healthcheck нужен для HEALTHCHECK контейнера: в образе scratch нет ни shell, ни curl.
func healthcheck() int {
client := &http.Client{Timeout: 3 * time.Second}
resp, err := client.Get("http://127.0.0.1:" + envOr("APP_PORT", "8080") + "/health/ready")
if err != nil {
return 1
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 1
}
return 0
}
func serve() int {
cfg, err := loadConfig()
if err != nil {
log.Printf("config error: %v", err)
return 1
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
pool, err := newPool(ctx, cfg.DatabaseURL, cfg.DBMaxConns)
if err != nil {
log.Printf("database setup error: %v", err)
return 1
}
defer pool.Close()
// Псевдоним реплики = hostname контейнера (короткий ID): по нему stop-one находит контейнер.
instance, _ := os.Hostname()
if instance == "" {
instance = newUUID()
}
api := &API{store: &Store{pool: pool}, hasher: newHasher(4), ttlSecs: cfg.SessionTTLSecs, reqLimit: 8 * time.Second, instanceID: instance}
server := &http.Server{
Addr: net.JoinHostPort(cfg.Host, cfg.Port),
Handler: api,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
errs := make(chan error, 1)
go func() { errs <- server.ListenAndServe() }()
log.Printf("messenger listening on %s (instance %s, session ttl %ds, max db conns %d)", server.Addr, instance, cfg.SessionTTLSecs, cfg.DBMaxConns)
select {
case err := <-errs:
if !errors.Is(err, http.ErrServerClosed) {
log.Printf("server error: %v", err)
return 1
}
case <-ctx.Done():
// Сначала перестаём быть «готовыми», даём LB время убрать реплику, и только затем закрываем listener.
api.draining.Store(true)
log.Printf("shutting down: not ready, draining %s, then finishing in-flight requests", cfg.DrainPeriod)
time.Sleep(cfg.DrainPeriod)
shutdown, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
if err := server.Shutdown(shutdown); err != nil {
log.Printf("shutdown error: %v", err)
return 1
}
}
return 0
}