forked from mtusi2026/mtusi2026lab2
134 lines
3.9 KiB
Go
134 lines
3.9 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"backend/db"
|
|
"backend/internal/adapter/handler"
|
|
"backend/internal/adapter/password"
|
|
"backend/internal/adapter/repository/postgres"
|
|
"backend/internal/application/usecase"
|
|
"backend/internal/config"
|
|
"backend/pkg/logger"
|
|
"backend/pkg/server"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
func main() {
|
|
healthcheck := flag.Bool("healthcheck", false, "проверить /health/ready и выйти (для Docker HEALTHCHECK)")
|
|
migrate := flag.Bool("migrate", false, "apply migrations and exit")
|
|
flag.Parse()
|
|
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "config:", err)
|
|
os.Exit(1)
|
|
}
|
|
if *healthcheck {
|
|
os.Exit(probe(cfg.Port))
|
|
}
|
|
|
|
log := logger.New(cfg.LogLevel)
|
|
dsn, err := config.ReadSecret(cfg.DatabaseURLFile)
|
|
if err != nil {
|
|
log.Fatal().Msg("database secret unavailable")
|
|
}
|
|
if *migrate {
|
|
if err = db.Migrate(context.Background(), dsn); err != nil {
|
|
log.Fatal().Err(err).Msg("migration failed")
|
|
}
|
|
return
|
|
}
|
|
pc, err := pgxpool.ParseConfig(dsn)
|
|
if err != nil {
|
|
log.Fatal().Msg("invalid database configuration")
|
|
}
|
|
pc.MaxConns = cfg.MaxConns
|
|
pc.MinConns = 0
|
|
pc.ConnConfig.ConnectTimeout = time.Second
|
|
pc.ConnConfig.RuntimeParams["statement_timeout"] = "2000"
|
|
pc.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
|
|
pool, err := pgxpool.NewWithConfig(context.Background(), pc)
|
|
if err != nil {
|
|
log.Fatal().Msg("database initialization failed")
|
|
}
|
|
defer pool.Close()
|
|
var cache *redis.Client
|
|
if url, e := config.ReadSecret(cfg.CacheURLFile); e == nil {
|
|
opts, e := redis.ParseURL(url)
|
|
if e != nil {
|
|
log.Fatal().Msg("invalid cache configuration")
|
|
}
|
|
opts.MaxRetries = 0
|
|
opts.DialTimeout = 80 * time.Millisecond
|
|
opts.ReadTimeout = 80 * time.Millisecond
|
|
opts.WriteTimeout = 80 * time.Millisecond
|
|
cache = redis.NewClient(opts)
|
|
defer func(){_ = cache.Close()}()
|
|
}
|
|
store := postgres.New(pool, cache)
|
|
app := usecase.NewMessenger(store)
|
|
auth := usecase.NewAuth(store, password.New(), app, time.Duration(cfg.SessionTTLSeconds)*time.Second, time.Now)
|
|
h := handler.New(app, auth, pool.Ping, handler.Limits{
|
|
MaxBodyBytes: cfg.MaxBodyBytes,
|
|
MaxInflight: cfg.MaxInflight,
|
|
MaxQueue: cfg.MaxQueue,
|
|
QueueTimeout: cfg.QueueTimeout,
|
|
}, func() any {
|
|
return map[string]any{"pool_total": pool.Stat().TotalConns(), "pool_acquired": pool.Stat().AcquiredConns(),"pool_max":pool.Stat().MaxConns()}
|
|
}, &log)
|
|
srv := server.New(cfg.Addr(), h.Router())
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
|
defer stop()
|
|
|
|
serveErr := make(chan error, 1)
|
|
go func() { serveErr <- srv.ListenAndServe() }()
|
|
log.Info().Str("addr", cfg.Addr()).Str("env", cfg.Env).
|
|
Int("max_inflight", cfg.MaxInflight).
|
|
Int("max_queue", cfg.MaxQueue).Msg("server started")
|
|
|
|
select {
|
|
case err := <-serveErr:
|
|
log.Fatal().Err(err).Msg("server failed")
|
|
case <-ctx.Done():
|
|
}
|
|
|
|
started := time.Now()
|
|
log.Info().Dur("timeout", cfg.ShutdownTimeout).Msg("shutdown signal received, draining")
|
|
h.Drain()
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
|
log.Error().Err(err).Msg("shutdown timed out, open requests aborted")
|
|
}
|
|
if err := <-serveErr; err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Error().Err(err).Msg("server error")
|
|
}
|
|
log.Info().Dur("took", time.Since(started)).Msg("shutdown complete")
|
|
}
|
|
|
|
// probe — healthcheck без curl в образе distroless: сам бинарник ходит в
|
|
// /health/ready и возвращает код выхода для Docker.
|
|
func probe(port int) int {
|
|
client := http.Client{Timeout: 2 * time.Second}
|
|
resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/health/ready", port))
|
|
if err != nil {
|
|
return 1
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|