// Package app is the composition root: it builds every module with its // stores and mounts them on one HTTP engine. Both the server binary and the // integration tests start from here. package app import ( "context" "log/slog" "time" "github.com/gin-gonic/gin" "github.com/jackc/pgx/v5/pgxpool" "github.com/redis/go-redis/v9" "messenger/internal/auth" authstore "messenger/internal/auth/store" "messenger/internal/chat" chatstore "messenger/internal/chat/store" "messenger/internal/health" "messenger/internal/platform/httpx" "messenger/internal/user" userstore "messenger/internal/user/store" ) type App struct { Engine *gin.Engine Health *health.Handler } // Deps are the shared resources the modules are built on; their lifetime is // owned by the caller. type Deps struct { Log *slog.Logger DB *pgxpool.Pool Sessions *redis.Client SessionTTL time.Duration MaxBodyBytes int64 // RequestTimeout bounds every API request; zero means the default. RequestTimeout time.Duration } // defaultRequestTimeout stays below the server's 10s write timeout, so a // request that gives up on a dependency can still write its 503. const defaultRequestTimeout = 5 * time.Second func New(d Deps) *App { users := user.NewService(userstore.NewUsers(d.DB)) chats := chat.NewService(chatstore.NewChats(d.DB), chatstore.NewMessages(d.DB), users) engine := httpx.NewEngine(d.Log, d.MaxBodyBytes) probes := health.New( health.Check{Name: "postgres", Probe: d.DB.Ping}, health.Check{Name: "valkey", Probe: func(ctx context.Context) error { return d.Sessions.Ping(ctx).Err() }}, ) probes.Register(engine) sessions := auth.NewService(users, authstore.NewSessions(d.Sessions), d.SessionTTL) timeout := d.RequestTimeout if timeout == 0 { timeout = defaultRequestTimeout } public := engine.Group("/api/v1", httpx.Timeout(timeout)) protected := public.Group("", auth.RequireSession(sessions)) auth.NewHandler(sessions).Register(public, protected) user.NewHandler(users).Register(public, protected) chat.NewHandler(chats).Register(protected) return &App{Engine: engine, Health: probes} }