Files
mtusi2026lab3/cmd/server/main.go
T
2026-10-21 13:51:35 +03:00

215 lines
4.8 KiB
Go

package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
cacheadapter "mtusi2026lab3/internal/adapter/cache"
"mtusi2026lab3/internal/adapter/postgres"
redisadapter "mtusi2026lab3/internal/adapter/redis"
"mtusi2026lab3/internal/application"
"mtusi2026lab3/internal/config"
"mtusi2026lab3/internal/database"
"mtusi2026lab3/internal/transport/http/handlers"
"mtusi2026lab3/internal/transport/http/middleware"
)
func main() {
cfg, err := config.Load()
if err != nil {
log.Fatalf("[FATAL] Invalid configuration: %v", err)
}
startupContext, startupCancel := context.WithTimeout(
context.Background(),
cfg.DatabaseConnectTimeout,
)
databasePool, err := database.Open(startupContext, cfg)
startupCancel()
if err != nil {
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
}
defer databasePool.Close()
postgresStore := postgres.NewPostgreSQLStore(
databasePool,
cfg.DatabaseQueryTimeout,
)
var applicationStore application.Repository = postgresStore
if cfg.RedisURL != "" {
redisChatCache, cacheError := redisadapter.NewRedisChatCache(
cfg.RedisURL,
cfg.RedisCacheTTL,
cfg.RedisOperationTimeout,
cfg.RedisPoolSize,
)
if cacheError != nil {
log.Fatalf("[FATAL] Invalid Redis configuration: %v", cacheError)
}
defer func() {
if closeError := redisChatCache.Close(); closeError != nil {
log.Printf("[WARN] Redis client close failed: %v", closeError)
}
}()
cacheContext, cacheCancel := context.WithTimeout(
context.Background(),
cfg.RedisOperationTimeout,
)
if cacheError = redisChatCache.Ping(cacheContext); cacheError != nil {
log.Printf("[WARN] Redis unavailable at startup; PostgreSQL fallback is active: %v", cacheError)
} else {
log.Println("[INFO] Redis chat cache is available")
}
cacheCancel()
applicationStore = cacheadapter.NewCachedRepository(
postgresStore,
redisChatCache,
log.Default(),
)
}
cursorCodec, err := application.NewCursorCodec(cfg.CursorSigningKey)
if err != nil {
log.Fatalf("[FATAL] Invalid cursor configuration: %v", err)
}
service, err := application.NewService(
applicationStore,
cursorCodec,
cfg.SessionTTL,
application.WithIdempotencyTTL(cfg.IdempotencyTTL),
)
if err != nil {
log.Fatalf("[FATAL] Application initialization failed: %v", err)
}
handler := handlers.NewHandler(
service,
handlers.WithReadiness(
databasePool,
cfg.ReadinessTimeout,
),
)
mux := http.NewServeMux()
mux.HandleFunc("GET /health/live", handler.HealthLive)
mux.HandleFunc("GET /health/ready", handler.HealthReady)
mux.HandleFunc(
"POST /api/v1/auth/sessions",
handler.CreateSession,
)
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
requireAuth := func(next http.HandlerFunc) http.HandlerFunc {
return middleware.RequireAuth(service, next)
}
mux.HandleFunc(
"GET /api/v1/users/me",
requireAuth(handler.GetMe),
)
mux.HandleFunc(
"DELETE /api/v1/auth/sessions/current",
requireAuth(handler.DeleteCurrentSession),
)
mux.HandleFunc(
"POST /api/v1/chats",
requireAuth(handler.CreateChat),
)
mux.HandleFunc(
"GET /api/v1/chats",
requireAuth(handler.ListChats),
)
mux.HandleFunc(
"GET /api/v1/chats/{chat_id}",
requireAuth(handler.GetChat),
)
mux.HandleFunc(
"POST /api/v1/chats/{chat_id}/messages",
requireAuth(handler.CreateMessage),
)
mux.HandleFunc(
"GET /api/v1/chats/{chat_id}/messages",
requireAuth(handler.GetMessages),
)
var rootHandler http.Handler = mux
rootHandler = middleware.Recovery(rootHandler)
rootHandler = middleware.Logger(rootHandler)
rootHandler = middleware.RequestID(rootHandler)
rootHandler = middleware.InstanceID(cfg.InstanceID, rootHandler)
server := &http.Server{
Addr: cfg.HTTPAddress(),
Handler: rootHandler,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
serverErrors := make(chan error, 1)
go func() {
log.Printf(
"[INFO] Server instance %s starting on %s",
cfg.InstanceID,
server.Addr,
)
serverErrors <- server.ListenAndServe()
}()
shutdownSignals := make(chan os.Signal, 1)
signal.Notify(
shutdownSignals,
os.Interrupt,
syscall.SIGTERM,
)
defer signal.Stop(shutdownSignals)
select {
case serverError := <-serverErrors:
if !errors.Is(serverError, http.ErrServerClosed) {
log.Fatalf("[FATAL] Server crashed: %v", serverError)
}
case signalValue := <-shutdownSignals:
log.Printf(
"[INFO] Signal %v received. Starting graceful shutdown...",
signalValue,
)
shutdownContext, shutdownCancel := context.WithTimeout(
context.Background(),
cfg.ShutdownTimeout,
)
defer shutdownCancel()
if err := server.Shutdown(shutdownContext); err != nil {
log.Printf(
"[WARN] Graceful shutdown failed: %v. Forcing close.",
err,
)
_ = server.Close()
}
log.Println("[INFO] Server stopped gracefully.")
}
}