forked from mtusi2026/mtusi2026lab3
перенос лабы 2
This commit is contained in:
@@ -0,0 +1,193 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
applicationCache "mtusi2026lab3/internal/cache"
|
||||
"mtusi2026lab3/internal/config"
|
||||
"mtusi2026lab3/internal/database"
|
||||
"mtusi2026lab3/internal/store"
|
||||
"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 := store.NewPostgreSQLStore(
|
||||
databasePool,
|
||||
cfg.DatabaseQueryTimeout,
|
||||
)
|
||||
|
||||
var applicationStore store.Repository = postgresStore
|
||||
|
||||
if cfg.RedisURL != "" {
|
||||
redisChatCache, cacheError := applicationCache.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 = store.NewCachedRepository(
|
||||
postgresStore,
|
||||
redisChatCache,
|
||||
log.Default(),
|
||||
)
|
||||
}
|
||||
|
||||
handler := handlers.NewHandler(
|
||||
applicationStore,
|
||||
handlers.WithReadiness(
|
||||
databasePool,
|
||||
cfg.ReadinessTimeout,
|
||||
),
|
||||
handlers.WithSessionTTL(cfg.SessionTTL),
|
||||
)
|
||||
|
||||
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(postgresStore, 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)
|
||||
|
||||
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 starting on %s", 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.")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user