forked from mtusi2026/mtusi2026lab5
261 lines
6.3 KiB
Go
261 lines
6.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
cacheadapter "mtusi2026lab5/internal/adapter/cache"
|
|
"mtusi2026lab5/internal/adapter/health"
|
|
"mtusi2026lab5/internal/adapter/objectstore"
|
|
"mtusi2026lab5/internal/adapter/postgres"
|
|
redisadapter "mtusi2026lab5/internal/adapter/redis"
|
|
"mtusi2026lab5/internal/application"
|
|
"mtusi2026lab5/internal/config"
|
|
"mtusi2026lab5/internal/database"
|
|
"mtusi2026lab5/internal/transport/http/handlers"
|
|
"mtusi2026lab5/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,
|
|
)
|
|
minioStore, err := objectstore.NewMinIOStore(
|
|
cfg.S3Endpoint,
|
|
cfg.S3Region,
|
|
cfg.S3Bucket,
|
|
cfg.S3AccessKeyID,
|
|
cfg.S3SecretAccessKey,
|
|
cfg.S3OperationTimeout,
|
|
)
|
|
if err != nil {
|
|
log.Fatalf("[FATAL] Invalid object storage configuration: %v", err)
|
|
}
|
|
storageContext, storageCancel := context.WithTimeout(
|
|
context.Background(),
|
|
cfg.S3OperationTimeout,
|
|
)
|
|
if err = minioStore.Ping(storageContext); err != nil {
|
|
log.Printf("[WARN] Object storage unavailable at startup: %v", err)
|
|
}
|
|
storageCancel()
|
|
|
|
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),
|
|
application.WithObjectStore(minioStore),
|
|
application.WithJobMaxAttempts(cfg.JobMaxAttempts),
|
|
)
|
|
if err != nil {
|
|
log.Fatalf("[FATAL] Application initialization failed: %v", err)
|
|
}
|
|
|
|
handler := handlers.NewHandler(
|
|
service,
|
|
handlers.WithReadiness(
|
|
health.NewMultiChecker(databasePool, minioStore),
|
|
cfg.ReadinessTimeout,
|
|
),
|
|
handlers.WithSessionCookieSecure(cfg.SessionCookieSecure),
|
|
)
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("GET /health/live", handler.HealthLive)
|
|
mux.HandleFunc("GET /health/lb", 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),
|
|
)
|
|
mux.HandleFunc(
|
|
"POST /api/v1/chats/{chat_id}/attachments",
|
|
requireAuth(handler.UploadAttachment),
|
|
)
|
|
mux.HandleFunc(
|
|
"GET /api/v1/attachments/{attachment_id}",
|
|
requireAuth(handler.GetAttachment),
|
|
)
|
|
mux.HandleFunc(
|
|
"GET /api/v1/attachments/{attachment_id}/content",
|
|
requireAuth(handler.DownloadAttachment),
|
|
)
|
|
|
|
var rootHandler http.Handler = mux
|
|
rootHandler = middleware.Recovery(rootHandler)
|
|
rootHandler = middleware.Logger(rootHandler)
|
|
availabilityGate := middleware.NewAvailabilityGate()
|
|
rootHandler = availabilityGate.Middleware(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,
|
|
)
|
|
|
|
availabilityGate.BeginDrain()
|
|
log.Printf(
|
|
"[INFO] Readiness disabled; draining new traffic for %s",
|
|
cfg.ShutdownDrainDelay,
|
|
)
|
|
time.Sleep(cfg.ShutdownDrainDelay)
|
|
|
|
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.")
|
|
}
|
|
}
|