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

263 lines
7.4 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"log"
"log/slog"
"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"
"high-loud-apps-labs/internal/telemetry"
)
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)
}
instanceID := os.Getenv("INSTANCE_ID")
if instanceID == "" {
instanceID, _ = os.Hostname()
}
tel, err := telemetry.Setup(context.Background(), telemetry.SetupConfig{
ServiceName: "messenger-api",
ServiceVersion: "1.6.0",
InstanceID: instanceID,
Environment: "lab",
})
if err != nil {
log.Fatalf("телеметрия: %v", err)
}
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := tel.Shutdown(ctx); err != nil {
log.Printf("остановка телеметрии: %v", err)
}
}()
// Делаем логгер глобальным для всего приложения
slog.SetDefault(tel.Logger)
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 {
slog.Error("Ошибка подключения к БД", "error", err)
os.Exit(1)
}
defer pool.Close()
registration, err := postgres.ObservePool(pool)
if err != nil {
slog.Warn("Не удалось зарегистрировать метрики пула", "error", err)
} else {
defer registration.Unregister()
}
store := postgres.New(pool)
rabbitPub, err := broker.NewRabbitPublisher(cfg.RabbitMQURL)
if err != nil {
slog.Error("Ошибка подключения к RabbitMQ", "error", err)
os.Exit(1)
}
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() {
slog.Error("S3 не настроен: задайте S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID_FILE/S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY_FILE/S3_SECRET_ACCESS_KEY")
os.Exit(1)
}
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) {
slog.Error("Ошибка S3", "error", err, "reason", unavailable.Reason)
} else {
slog.Error("Ошибка S3", "error", err)
}
os.Exit(1)
}
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() {
slog.Info("Запускаем сервер", "addr", addr, "session_store", cfg.SessionStore)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("Ошибка запуска сервера", "error", err)
os.Exit(1)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
slog.Info("Получен сигнал завершения; readiness выключен", "drain", cfg.ShutdownDrain)
ready.Store(false)
outboxCancel()
if cfg.ShutdownDrain > 0 {
time.Sleep(cfg.ShutdownDrain)
}
slog.Info("Drain завершён, останавливаем HTTP-сервер...")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("Ошибка при остановке", "error", err)
}
slog.Info("Сервер остановлен")
}
func runMigrate() error {
// Пока стандартный log, поменяем потом на slog
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
}
}