Files
mtusi2026lab3/internal/app/app.go
T

82 lines
2.4 KiB
Go

// 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
// Chats is exposed for the background cleanup of idempotency keys.
Chats *chat.Service
}
// 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
InstanceID string
// IdempotencyTTL zero means the contract's 24 hours.
IdempotencyTTL 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
const defaultIdempotencyTTL = 24 * time.Hour
func New(d Deps) *App {
users := user.NewService(userstore.NewUsers(d.DB))
keyTTL := d.IdempotencyTTL
if keyTTL == 0 {
keyTTL = defaultIdempotencyTTL
}
chats := chat.NewService(chatstore.NewChats(d.DB), chatstore.NewMessages(d.DB), users, keyTTL)
engine := httpx.NewEngine(d.Log, d.MaxBodyBytes, d.InstanceID)
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, Chats: chats}
}