Files
pipu-music/services/api/internal/system/handler.go
T
mrleo1nidandClaude Opus 5.5 ed4a492dba
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m15s
ci / api / api (push) Successful in 1m31s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 47s
ci / ts / ts (packages + web) (push) Successful in 39s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 26s
feat(api): sign-in, refresh rotation and bootstrap admin (M1)
- users, refresh_tokens and audit_log schema (migration 00002)
- argon2id passwords with rehash on login, password policy, lockout
  with exponential back-off and a per-IP rate limit in Redis
- Ed25519 JWT access tokens with kid-based key rotation; rotating
  refresh tokens with reuse detection (cookie for web, body for Android)
- bootstrap admin on first start; must_change_credentials and
  must_change_password gate every other endpoint
- /auth/login, /auth/refresh, /auth/logout(-all), /me, /me/password,
  /me/bootstrap-credentials, /me/sessions; server-info reports
  bootstrap_required
- role policy from docs/auth-and-roles.md with table tests
- problem+json errors with field errors; ru/en translations of the codes
- install.sh and update.sh generate JWT_PRIVATE_KEY

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 06:12:25 +03:00

108 lines
3.7 KiB
Go

// Package system — служебные эндпоинты: живость, готовность, сведения о сервере.
package system
import (
"context"
"log/slog"
"sync"
"time"
"pipu/api/internal/api/gen"
)
// Checker проверяет одну зависимость (БД, Redis, ...). Возвращает ошибку, если она недоступна.
type Checker interface {
Check(ctx context.Context) error
}
// CheckerFunc адаптирует функцию к Checker.
type CheckerFunc func(ctx context.Context) error
// Check реализует Checker.
func (f CheckerFunc) Check(ctx context.Context) error { return f(ctx) }
// Info — статические сведения о сервере.
type Info struct {
Version string
SupportedLocales []string
MinAndroidVersionCode int
// BootstrapRequired сообщает, что первый вход администратора не завершён (nil — false).
BootstrapRequired func(ctx context.Context) (bool, error)
}
// Handler реализует системную часть gen.StrictServerInterface.
type Handler struct {
info Info
log *slog.Logger
checks map[string]Checker
checkTimeout time.Duration
}
// NewHandler создаёт обработчик. checks — именованные проверки для /readyz.
func NewHandler(info Info, log *slog.Logger, checks map[string]Checker) *Handler {
if log == nil {
log = slog.New(slog.DiscardHandler)
}
return &Handler{info: info, log: log, checks: checks, checkTimeout: 2 * time.Second}
}
// GetHealthz сообщает, что процесс жив; зависимости не проверяет.
func (h *Handler) GetHealthz(context.Context, gen.GetHealthzRequestObject) (gen.GetHealthzResponseObject, error) {
return gen.GetHealthz200JSONResponse{Status: gen.HealthStatusStatusOk}, nil
}
// GetReadyz параллельно проверяет все зависимости; 503, если хотя бы одна недоступна.
// /readyz доступен снаружи, поэтому текст ошибки пишется только в лог, а в ответ — "fail".
func (h *Handler) GetReadyz(ctx context.Context, _ gen.GetReadyzRequestObject) (gen.GetReadyzResponseObject, error) {
ctx, cancel := context.WithTimeout(ctx, h.checkTimeout)
defer cancel()
var (
mu sync.Mutex
wg sync.WaitGroup
results = make(map[string]string, len(h.checks))
healthy = true
)
for name, c := range h.checks {
wg.Add(1)
go func() {
defer wg.Done()
err := c.Check(ctx)
mu.Lock()
defer mu.Unlock()
if err != nil {
h.log.WarnContext(ctx, "readiness check failed", "check", name, "err", err)
results[name] = "fail"
healthy = false
return
}
results[name] = "ok"
}()
}
wg.Wait()
if !healthy {
return gen.GetReadyz503JSONResponse{Status: gen.ReadyStatusStatusDegraded, Checks: results}, nil
}
return gen.GetReadyz200JSONResponse{Status: gen.ReadyStatusStatusOk, Checks: results}, nil
}
// GetServerInfo отдаёт сведения о сервере для экрана подключения клиентов.
func (h *Handler) GetServerInfo(ctx context.Context, _ gen.GetServerInfoRequestObject) (gen.GetServerInfoResponseObject, error) {
var bootstrap bool
if h.info.BootstrapRequired != nil {
var err error
if bootstrap, err = h.info.BootstrapRequired(ctx); err != nil {
return nil, err
}
}
return gen.GetServerInfo200JSONResponse{
BootstrapRequired: bootstrap,
Name: "pipu-music",
Version: h.info.Version,
ApiVersion: "v1",
SupportedLocales: h.info.SupportedLocales,
MinAndroidVersionCode: h.info.MinAndroidVersionCode,
}, nil
}