forked from mtusi2026/mtusi2026lab4
131 lines
3.5 KiB
Go
131 lines
3.5 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"net/http"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"messenger/internal/blob"
|
|
"messenger/internal/password"
|
|
"messenger/internal/session"
|
|
"messenger/internal/store"
|
|
)
|
|
|
|
type ctxKey struct{}
|
|
|
|
type API struct {
|
|
store store.Repository
|
|
sessions session.Store
|
|
hasher password.Params
|
|
dummyHash string
|
|
sessionTTL time.Duration
|
|
instanceID string
|
|
log *slog.Logger
|
|
shutting atomic.Bool
|
|
blobs blob.Store
|
|
maxUpload int64
|
|
maxPixels int
|
|
}
|
|
|
|
// New связывает HTTP с хранилищем и сессиями.
|
|
// dummyHash нужен, чтобы несуществующий username тратил столько же KDF, сколько существующий.
|
|
func New(st store.Repository, sessions session.Store, hasher password.Params, sessionTTL time.Duration, instanceID string, log *slog.Logger) *API {
|
|
if log == nil {
|
|
log = slog.Default()
|
|
}
|
|
if sessionTTL <= 0 {
|
|
sessionTTL = time.Hour
|
|
}
|
|
if instanceID == "" {
|
|
instanceID = "api"
|
|
}
|
|
dummy, err := hasher.Hash("dummy-password-not-a-login")
|
|
if err != nil {
|
|
// Параметры KDF проверяются на старте. Пустая строка заставит Verify сразу вернуть false.
|
|
dummy = ""
|
|
}
|
|
return &API{
|
|
store: st,
|
|
sessions: sessions,
|
|
hasher: hasher,
|
|
dummyHash: dummy,
|
|
sessionTTL: sessionTTL,
|
|
instanceID: instanceID,
|
|
log: log,
|
|
}
|
|
}
|
|
|
|
// EnableAttachments подключает приватный bucket и жёсткие лимиты загрузки.
|
|
// maxUpload не может превысить 10 МиБ контракта.
|
|
func (a *API) EnableAttachments(objects blob.Store, maxUpload int64, maxPixels int) {
|
|
const contractMax = 10 * 1024 * 1024
|
|
if maxUpload <= 0 || maxUpload > contractMax {
|
|
maxUpload = contractMax
|
|
}
|
|
if maxPixels <= 0 || maxPixels > 40_000_000 {
|
|
maxPixels = 40_000_000
|
|
}
|
|
a.blobs = objects
|
|
a.maxUpload = maxUpload
|
|
a.maxPixels = maxPixels
|
|
}
|
|
|
|
// BeginShutdown переводит /health/ready в 503 и говорит новым бизнес-запросам
|
|
// отказать до закрытия слушателя. Уже принятые обработчики дорабатывают.
|
|
func (a *API) BeginShutdown() {
|
|
a.shutting.Store(true)
|
|
a.log.Info("shutdown started")
|
|
}
|
|
|
|
// Точка входа
|
|
func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
|
start := time.Now()
|
|
id := requestID(r)
|
|
sw.Header().Set("X-Request-Id", id)
|
|
sw.Header().Set("X-Instance-Id", a.instanceID)
|
|
r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, id))
|
|
|
|
defer func() {
|
|
if p := recover(); p != nil {
|
|
a.log.Error("panic", "request_id", id)
|
|
if !sw.wrote {
|
|
a.fail(sw, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
|
}
|
|
}
|
|
a.log.Info("request",
|
|
"request_id", id,
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
"status", sw.status,
|
|
"duration_ms", time.Since(start).Milliseconds(),
|
|
"bytes_in", r.ContentLength,
|
|
)
|
|
}()
|
|
|
|
switch {
|
|
case r.Method == http.MethodGet && r.URL.Path == "/health/live":
|
|
a.live(sw, r)
|
|
return
|
|
case r.Method == http.MethodGet && r.URL.Path == "/health/ready":
|
|
a.ready(sw, r)
|
|
return
|
|
}
|
|
|
|
if a.shutting.Load() {
|
|
a.fail(sw, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1)
|
|
return
|
|
}
|
|
a.route(sw, r)
|
|
}
|
|
|
|
func requestIDFrom(r *http.Request) string {
|
|
id, _ := r.Context().Value(ctxKey{}).(string)
|
|
if id == "" {
|
|
return "unknown"
|
|
}
|
|
return id
|
|
}
|