package main import ( "context" "fmt" "log/slog" "os" "os/signal" "syscall" "time" "encoding/json" "gitea.privcloud.tech/mtusi2026/internal/adapter/controller/http" "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/outside" "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/storage" "gitea.privcloud.tech/mtusi2026/internal/config" "gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider" "gitea.privcloud.tech/mtusi2026/internal/pkg/cache" "gitea.privcloud.tech/mtusi2026/internal/pkg/encrypting" "gitea.privcloud.tech/mtusi2026/internal/pkg/migrator" "gitea.privcloud.tech/mtusi2026/internal/pkg/objectstore" "gitea.privcloud.tech/mtusi2026/internal/pkg/postgres" "gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager" "gitea.privcloud.tech/mtusi2026/internal/pkg/rest/middleware" "gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router" "gitea.privcloud.tech/mtusi2026/internal/pkg/telemetry" "gitea.privcloud.tech/mtusi2026/internal/pkg/validator" "gitea.privcloud.tech/mtusi2026/internal/service/attachment" "gitea.privcloud.tech/mtusi2026/internal/service/auth" "gitea.privcloud.tech/mtusi2026/internal/service/chat" "gitea.privcloud.tech/mtusi2026/internal/service/outbox" "gitea.privcloud.tech/mtusi2026/internal/service/user" stdhttp "net/http" ) func main() { time.Local = time.UTC if err := run(); err != nil { slog.Error("application stopped", "error", err) os.Exit(1) } } func run() error { cfg, err := config.New() if err != nil { return fmt.Errorf("load server config: %w", err) } if len(os.Args) > 1 && os.Args[1] == "migrate" { cfg.Postgres.RunMigrations = true ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() return migrator.New(cfg).Start(ctx) } name := "messenger-api" if len(os.Args) > 1 { name = "messenger-" + os.Args[1] } shutdown, err := telemetry.Init(context.Background(), name) if err != nil { return err } defer shutdown() attachmentConfig, err := config.LoadAttachment() if err != nil { return err } if len(os.Args) > 1 && (os.Args[1] == "worker" || os.Args[1] == "dispatcher" || os.Args[1] == "jobs" || os.Args[1] == "outbox") { return runPipeline(cfg, attachmentConfig, os.Args[1:]) } if len(os.Args) > 1 && os.Args[1] == "storage" { return runStorage(cfg, attachmentConfig, os.Args[2:]) } // API processes never run migrations; the one-shot migrator owns schema changes. cfg.Postgres.RunMigrations = false var level slog.Level if err := level.UnmarshalText([]byte(cfg.Application.LogLevel)); err != nil { return err } // Logging is initialized for every process by telemetry.Init. instanceID := telemetry.InstanceID slog.Info("instance_started", "instance_id", instanceID) pgx := postgres.New(cfg.Postgres) rx := cache.New(cfg) postgresMigrator := migrator.New(cfg) defer pgx.Close() telemetry.ObservePool(pgx, 0) defer rx.Close() tm := txmanager.New(pgx) provider := jwtprovider.New(cfg) encryptor := encrypting.New() chatsRepo := storage.NewChatsRepo(pgx) messageRepo := storage.NewMessagesRepo(pgx) refreshTokensRepo := storage.NewRefreshTokensRepo(pgx) userRepo := storage.NewUsersRepo(pgx) chatCache := outside.NewChatCache(rx) authSvc := auth.New(provider, tm, encryptor, userRepo, refreshTokensRepo) userSvc := user.New(encryptor, userRepo) chatSvc := chat.New(tm, chatsRepo, messageRepo, chatCache) objectStore := objectstore.New(attachmentConfig) attachmentSvc := attachment.New(&storage.AttachmentsRepo{Pool: pgx}, objectStore, attachmentConfig, chatSvc) pipelineConfig, err := config.LoadPipeline() if err != nil { return err } outboxSvc := outbox.New(&storage.OutboxRepo{Pool: pgx}, tm, nil) attachmentSvc.Configure(tm, outboxSvc, pipelineConfig) httpRouter := router.New( middleware.NewAuthMiddleware(authSvc), middleware.Instance(instanceID), middleware.RequestIDMiddleware(), telemetry.HTTP, middleware.RequestTimeout(cfg.Postgres.QueryTimeout, attachmentConfig.Timeout), ) httpRouter.Get("/internal/metrics", func(w stdhttp.ResponseWriter, r *stdhttp.Request) { stat := pgx.Stat() _ = json.NewEncoder(w).Encode(map[string]any{"instance_id": instanceID, "acquire_count": stat.AcquireCount(), "acquire_duration_ns": stat.AcquireDuration().Nanoseconds(), "empty_acquire_count": stat.EmptyAcquireCount(), "acquired_conns": stat.AcquiredConns(), "total_conns": stat.TotalConns(), "max_conns": stat.MaxConns()}) }) server := http.New(cfg, httpRouter) requestValidator := validator.NewValidatorImpl() registerRoutes( http.NewAuthHandler(httpRouter, authSvc), http.NewHealthHandler(httpRouter, server, pgx, objectStore), http.NewChatHandler(httpRouter, provider, requestValidator, chatSvc), http.NewUserHandler(httpRouter, provider, requestValidator, userSvc), http.NewAttachmentHandler(httpRouter, provider, attachmentSvc), ) ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() if err = postgresMigrator.Start(ctx); err != nil { return fmt.Errorf("start postgres migrator: %w", err) } if err = server.Start(ctx); err != nil { return fmt.Errorf("start HTTP server: %w", err) } if err = rx.Start(ctx); err != nil { slog.Warn("redis unavailable at startup; continuing without cache", "error", err) } slog.Info("HTTP server started", "address", cfg.Server.BindAddress()) <-ctx.Done() shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeout) defer cancel() if err = server.Stop(shutdownCtx); err != nil { return fmt.Errorf("stop HTTP server: %w", err) } if err = postgresMigrator.Close(shutdownCtx); err != nil { return fmt.Errorf("close postgres migrator: %w", err) } if err = rx.Close(); err != nil { return fmt.Errorf("close redis: %w", err) } pgx.Close() return nil } func registerRoutes(handlers ...http.Handler) { for _, handler := range handlers { handler.RegisterRoutes() } }