package main import ( "context" "errors" "fmt" "log" "net/http" "os" "os/signal" "strings" "sync/atomic" "syscall" "time" "high-loud-apps-labs/internal/broker" "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/outbox" "high-loud-apps-labs/internal/service" "high-loud-apps-labs/internal/storage/postgres" redisstore "high-loud-apps-labs/internal/storage/redis" s3store "high-loud-apps-labs/internal/storage/s3" ) 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) rabbitPub, err := broker.NewRabbitPublisher(cfg.RabbitMQURL) if err != nil { log.Fatalf("rabbitmq: %v", err) } defer rabbitPub.Close() outboxPub := outbox.NewPublisher(store.Outbox(), rabbitPub, 50) outboxCtx, outboxCancel := context.WithCancel(context.Background()) defer outboxCancel() go outboxPub.Run(outboxCtx, cfg.OutboxInterval) 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) if !cfg.S3Configured() { log.Fatal("S3 не настроен: задайте S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID_FILE/S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY_FILE/S3_SECRET_ACCESS_KEY") } objectStorage, err := s3store.New(ctx, s3store.Config{ Endpoint: cfg.S3Endpoint, Bucket: cfg.S3Bucket, AccessKey: cfg.S3AccessKey, SecretKey: cfg.S3SecretKey, UseSSL: cfg.S3UseSSL, Region: cfg.S3Region, }) if err != nil { var unavailable *domain.UnavailableError if errors.As(err, &unavailable) { log.Fatalf("s3: %v (reason: %s)", err, unavailable.Reason) } log.Fatalf("s3: %v", err) } attachmentSvc := service.NewAttachmentService( store.Attachments(), store.Chats(), objectStorage, store.Outbox(), store.FailedJobs(), store, cfg.MaxUploadBytes, cfg.MaxImagePixels, ) healthChecks := []handler.HealthCheck{ func(ctx context.Context) error { return pool.Ping(ctx) }, func(ctx context.Context) error { return objectStorage.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), Attachment: handler.NewAttachmentHandler(attachmentSvc), }, middleware.BearerAuth(sessionSvc), ) srv := &http.Server{Addr: addr, Handler: router} reconcilerCtx, reconcilerCancel := context.WithCancel(context.Background()) defer reconcilerCancel() if cfg.ReconcilerEnabled { reconciler := service.NewReconciler( store.Attachments(), objectStorage, store.Outbox(), pool, cfg.ReconcilerGracePeriod, ) go reconciler.Run(reconcilerCtx, cfg.ReconcilerInterval) } go func() { log.Printf("Запускаем на %s (SESSION_STORE=%s, RECONCILER_ENABLED=%v)", addr, cfg.SessionStore, cfg.ReconcilerEnabled) 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) outboxCancel() reconcilerCancel() 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("Сервер остановлен") } 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 } }