Реализовать лабораторную 2: PostgreSQL, Bearer-сессии и Valkey

Переносит минимум lab1 на PostgreSQL, добавляет Argon2id, Basic-вход,
opaque Bearer-сессии в Valkey с TTL и AOF, строгую валидацию JSON,
keyset-пагинацию по индексу, миграции, compose-стенд и собственные
проверки уровня 3/4. Трек 5 — план запроса и восстановление.
This commit is contained in:
IvanMeln1k
2026-11-30 23:51:33 +03:00
parent 65003b6119
commit 6ea767732e
469 changed files with 204712 additions and 10 deletions
+190
View File
@@ -0,0 +1,190 @@
// Command messenger runs the lab2 HTTP API and the container healthcheck
// helper. PostgreSQL holds users, chats, membership and messages; Valkey holds
// server-side sessions with an absolute TTL.
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"mtusi.ru/messenger-lab2/internal/api"
"mtusi.ru/messenger-lab2/internal/config"
"mtusi.ru/messenger-lab2/internal/session"
"mtusi.ru/messenger-lab2/internal/store"
)
// version is overridden at build time with -X main.version=...
var version = "dev"
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()
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)
}
migrateCtx, migrateCancel := context.WithTimeout(ctx, 60*time.Second)
err = repository.Migrate(migrateCtx)
migrateCancel()
if err != nil {
logger.Error("database migrations failed", "error", err)
os.Exit(1)
}
logger.Info("database ready", "migrations", "up-to-date")
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)
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)
}
logger.Info("server listening",
"address", listener.Addr().String(),
"env", cfg.Env,
"session_ttl_seconds", int(cfg.SessionTTL.Seconds()),
"graceful_shutdown_seconds", int(cfg.ShutdownTimeout.Seconds()),
"version", version,
)
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())
// Clear readiness first: a request that races with Shutdown must not
// see a successful readiness probe.
app.SetReady(false)
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)
}
logger.Info("shutdown complete",
"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)
}
}
}
func newLogger(cfg config.Config) *slog.Logger {
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel})
return slog.New(handler).With("service", "messenger-lab2", "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)
}
}
// 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
}