Files
mtusi2026lab3/backend/cmd/server/main.go
T

165 lines
4.7 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strings"
"sync/atomic"
"syscall"
"time"
"high-loud-apps-labs/internal/config"
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/httpapi"
"high-loud-apps-labs/internal/httpapi/handler"
"high-loud-apps-labs/internal/httpapi/middleware"
"high-loud-apps-labs/internal/service"
"high-loud-apps-labs/internal/storage/postgres"
redisstore "high-loud-apps-labs/internal/storage/redis"
)
func main() {
if len(os.Args) > 1 && os.Args[1] == "migrate" {
if err := runMigrate(); err != nil {
log.Fatalf("миграции: %v", err)
}
return
}
cfg, err := config.Load()
if err != nil {
log.Fatalf("конфигурация: %v", err)
}
addr := cfg.Host + ":" + cfg.Port
ctx := context.Background()
pool, err := postgres.Connect(ctx, postgres.Config{
URL: cfg.DatabaseURL,
MaxConns: 10,
MinConns: 1,
MaxConnLifetime: time.Hour,
MaxConnIdleTime: 30 * time.Minute,
ConnectTimeout: 5 * time.Second,
})
if err != nil {
log.Fatalf("БД: %v", err)
}
defer pool.Close()
store := postgres.New(pool)
sessionRepo, cachePing, closeSession := newSessionRepo(cfg, store)
defer closeSession()
hasher := service.NewArgon2idHasher()
userSvc := service.NewUserService(store.Users(), hasher)
sessionSvc := service.NewSessionService(store.Users(), sessionRepo, hasher, cfg.SessionTTL)
chatSvc := service.NewChatService(store.Chats(), store.Users())
messageSvc := service.NewMessageService(store.Messages(), store.Chats(), cfg.IdempotencyTTL)
healthChecks := []handler.HealthCheck{
func(ctx context.Context) error { return pool.Ping(ctx) },
}
if cachePing != nil {
healthChecks = append(healthChecks, cachePing)
}
var ready atomic.Bool
ready.Store(true)
router := httpapi.NewRouter(
httpapi.Handlers{
Health: handler.NewHealthHandler(healthChecks...).WithReadyFlag(&ready),
User: handler.NewUserHandler(userSvc),
Chat: handler.NewChatHandler(chatSvc),
Message: handler.NewMessageHandler(messageSvc),
Auth: handler.NewAuthHandler(sessionSvc),
},
middleware.BearerAuth(sessionSvc),
)
srv := &http.Server{Addr: addr, Handler: router}
go func() {
log.Printf("Запускаем на %s (SESSION_STORE=%s)", addr, cfg.SessionStore)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("Ошибка запуска: %v", err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Printf("Получен сигнал завершения; readiness выключен, drain %s", cfg.ShutdownDrain)
ready.Store(false)
if cfg.ShutdownDrain > 0 {
time.Sleep(cfg.ShutdownDrain)
}
log.Println("Drain завершён, останавливаем HTTP-сервер...")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Fatalf("Ошибка при остановке: %v", err)
}
log.Println("Сервер остановлен")
}
// runMigrate — одноразовый прогон goose. Запускается как `/server migrate`.
// Использует те же DATABASE_URL_FILE / DATABASE_URL, что и сервер.
// Отдельный процесс, поэтому не конкурирует с репликами за goose lock.
func runMigrate() error {
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("конфигурация: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
pool, err := postgres.Connect(ctx, postgres.Config{
URL: cfg.DatabaseURL,
ConnectTimeout: 5 * time.Second,
})
if err != nil {
return fmt.Errorf("БД: %w", err)
}
defer pool.Close()
if err := postgres.RunMigrations(ctx, pool); err != nil {
return fmt.Errorf("применение миграций: %w", err)
}
return nil
}
func newSessionRepo(cfg *config.Config, store *postgres.Storage) (domain.SessionRepository, handler.HealthCheck, func()) {
switch strings.ToLower(cfg.SessionStore) {
case "", "postgres":
return store.Sessions(), nil, func() {}
case "redis":
if cfg.CacheURL == "" {
log.Fatalf("SESSION_STORE=%s требует CACHE_URL_FILE или CACHE_URL", cfg.SessionStore)
}
client, err := redisstore.NewClient(cfg.CacheURL)
if err != nil {
log.Fatalf("redis: %v", err)
}
ping := func(ctx context.Context) error {
return client.Ping(ctx).Err()
}
return redisstore.NewSessionRepo(client), ping, func() { _ = client.Close() }
default:
log.Fatalf("SESSION_STORE=%q не поддерживается", cfg.SessionStore)
return nil, nil, nil
}
}