forked from mtusi2026/mtusi2026lab2
2 lab
This commit is contained in:
@@ -0,0 +1,233 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi.local/messenger/internal/authpw"
|
||||
"mtusi.local/messenger/internal/httpapi"
|
||||
"mtusi.local/messenger/internal/migrate"
|
||||
"mtusi.local/messenger/internal/pgstore"
|
||||
"mtusi.local/messenger/internal/sessions"
|
||||
)
|
||||
|
||||
type config struct {
|
||||
host string
|
||||
port string
|
||||
env string
|
||||
database string
|
||||
cache string
|
||||
migrations string
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
|
||||
os.Exit(healthcheck())
|
||||
}
|
||||
cfg, err := loadConfig()
|
||||
if err != nil {
|
||||
logger.Error("config", "err", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := waitPostgres(ctx, cfg.database, logger)
|
||||
if err != nil {
|
||||
logger.Error("postgres", "err", "not ready")
|
||||
os.Exit(1)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := migrate.Apply(ctx, pool, cfg.migrations); err != nil {
|
||||
logger.Error("migrate", "err", "failed")
|
||||
os.Exit(1)
|
||||
}
|
||||
cache, err := waitRedis(ctx, cfg.cache, logger)
|
||||
if err != nil {
|
||||
logger.Error("redis", "err", "not ready")
|
||||
os.Exit(1)
|
||||
}
|
||||
defer cache.Close()
|
||||
dummy, err := authpw.Hash("not-a-user-password")
|
||||
if err != nil {
|
||||
logger.Error("password", "err", "kdf init failed")
|
||||
os.Exit(1)
|
||||
}
|
||||
api := httpapi.New(pgstore.New(pool), sessions.New(cache, cfg.ttl), logger, dummy)
|
||||
server := &http.Server{
|
||||
Addr: net.JoinHostPort(cfg.host, cfg.port),
|
||||
Handler: api.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 20 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
logger.Info("start", "addr", server.Addr, "app_env", cfg.env, "session_ttl_seconds", int(cfg.ttl.Seconds()))
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- server.ListenAndServe()
|
||||
}()
|
||||
signals := make(chan os.Signal, 1)
|
||||
signal.Notify(signals, syscall.SIGTERM, os.Interrupt)
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
logger.Error("listen", "err", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
case sig := <-signals:
|
||||
logger.Info("shutdown", "signal", sig.String())
|
||||
api.StartDraining()
|
||||
shut, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
defer cancel()
|
||||
if err := server.Shutdown(shut); err != nil {
|
||||
logger.Error("shutdown", "err", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
logger.Info("shutdown_complete")
|
||||
}
|
||||
}
|
||||
|
||||
func loadConfig() (config, error) {
|
||||
port := getenv("APP_PORT", "8080")
|
||||
if port == "" {
|
||||
return config{}, fmt.Errorf("APP_PORT is empty")
|
||||
}
|
||||
database, err := secret("DATABASE_URL", "DATABASE_URL_FILE")
|
||||
if err != nil {
|
||||
return config{}, fmt.Errorf("database url is missing")
|
||||
}
|
||||
cache, err := secret("CACHE_URL", "CACHE_URL_FILE")
|
||||
if err != nil {
|
||||
return config{}, fmt.Errorf("cache url is missing")
|
||||
}
|
||||
ttlSeconds, err := strconv.Atoi(getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
if err != nil || ttlSeconds < 1 || ttlSeconds > 86400*30 {
|
||||
return config{}, fmt.Errorf("SESSION_TTL_SECONDS is invalid")
|
||||
}
|
||||
return config{
|
||||
host: getenv("APP_HOST", "0.0.0.0"),
|
||||
port: port,
|
||||
env: getenv("APP_ENV", "lab"),
|
||||
database: database,
|
||||
cache: cache,
|
||||
migrations: getenv("MIGRATIONS_DIR", "migrations"),
|
||||
ttl: time.Duration(ttlSeconds) * time.Second,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func secret(directKey, fileKey string) (string, error) {
|
||||
if value := strings.TrimSpace(os.Getenv(directKey)); value != "" {
|
||||
return value, nil
|
||||
}
|
||||
path := strings.TrimSpace(os.Getenv(fileKey))
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("missing")
|
||||
}
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
value := strings.TrimSpace(string(body))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("empty")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func getenv(key, fallback string) string {
|
||||
value, ok := os.LookupEnv(key)
|
||||
if !ok || value == "" {
|
||||
return fallback
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func waitPostgres(ctx context.Context, url string, logger *slog.Logger) (*pgxpool.Pool, error) {
|
||||
var last error
|
||||
for attempt := 1; attempt <= 30; attempt++ {
|
||||
pool, err := openPool(url)
|
||||
if err == nil {
|
||||
ping, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
err = pool.Ping(ping)
|
||||
cancel()
|
||||
if err == nil {
|
||||
return pool, nil
|
||||
}
|
||||
pool.Close()
|
||||
}
|
||||
last = err
|
||||
logger.Info("postgres_wait", "attempt", attempt)
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
return nil, last
|
||||
}
|
||||
|
||||
func openPool(url string) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.MaxConns = 8
|
||||
cfg.MinConns = 0
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConnIdleTime = time.Minute
|
||||
cfg.HealthCheckPeriod = 5 * time.Second
|
||||
cfg.ConnConfig.ConnectTimeout = time.Second
|
||||
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "8000"
|
||||
cfg.ConnConfig.RuntimeParams["lock_timeout"] = "2000"
|
||||
cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = "5000"
|
||||
return pgxpool.NewWithConfig(context.Background(), cfg)
|
||||
}
|
||||
|
||||
func waitRedis(ctx context.Context, url string, logger *slog.Logger) (*redis.Client, error) {
|
||||
opt, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opt.DialTimeout = 2 * time.Second
|
||||
opt.ReadTimeout = 2 * time.Second
|
||||
opt.WriteTimeout = 2 * time.Second
|
||||
opt.PoolSize = 8
|
||||
client := redis.NewClient(opt)
|
||||
var last error
|
||||
for attempt := 1; attempt <= 30; attempt++ {
|
||||
ping, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
last = client.Ping(ping).Err()
|
||||
cancel()
|
||||
if last == nil {
|
||||
return client, nil
|
||||
}
|
||||
logger.Info("redis_wait", "attempt", attempt)
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
_ = client.Close()
|
||||
return nil, last
|
||||
}
|
||||
|
||||
func healthcheck() int {
|
||||
port := getenv("APP_PORT", "8080")
|
||||
client := http.Client{Timeout: 2 * time.Second}
|
||||
response, err := client.Get("http://127.0.0.1:" + port + "/health/ready")
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
Reference in New Issue
Block a user