// Command server starts the messenger HTTP API, applies optional migrations, // and shuts down gracefully on SIGINT/SIGTERM. package main import ( "context" "log" "net" "os/signal" "syscall" "time" "gitflic.ru/project/bulla-max/mtusi2026lab/internal" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/attachments" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/broker" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/config" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/database" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/health" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/outbox" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/session" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/store" ) func main() { cfg, err := config.Load() if err != nil { log.Fatalf("configuration: %v", err) } rootCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() pool, err := database.Connect(rootCtx, cfg.DatabaseURL, cfg.DBMaxConns, cfg.StartupWait) if err != nil { log.Fatalf("database: %v", err) } defer pool.Close() if cfg.MigrateOnly || cfg.RunMigrations { if err = database.Migrate(cfg.DatabaseURL); err != nil { log.Fatalf("migrations: %v", err) } } if cfg.MigrateOnly { log.Printf("migrations applied; migrate-only process exiting") return } sessions, err := session.New(cfg.CacheURL, cfg.SessionTTL, cfg.RedisTimeout) if err != nil { log.Fatalf("session store: %v", err) } defer sessions.Close() attachments.CleanupStaleUploads(cfg.UploadTempDir, time.Hour) st := store.New(pool, cfg.DBTimeout, cfg.IdempotencyTTL) // AGENT: the outbox publisher runs in every API replica. Duplicate // publication is harmless because workers claim by job_id; the important // property is that a committed intent is retried until a confirm. publisher := broker.NewPublisher(cfg.BrokerURL, cfg.JobQueue) defer publisher.Close() go outbox.New(st, publisher, nil).Run(rootCtx) app, err := internal.New(cfg, st, sessions) if err != nil { log.Fatalf("application: %v", err) } addr := net.JoinHostPort(cfg.Host, cfg.Port) listenErr := make(chan error, 1) go func() { listenErr <- app.Listen(addr) }() select { case err = <-listenErr: if err != nil { log.Fatalf("server: %v", err) } case <-rootCtx.Done(): } log.Printf("shutting down") health.SignalShutdown() if err = app.ShutdownWithTimeout(10 * time.Second); err != nil { log.Printf("shutdown: %v", err) } }