forked from mtusi2026/mtusi2026lab2
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
66dffa5346 |
+12
-1
@@ -26,12 +26,23 @@ func (h *Handler) bearerAuth(next http.HandlerFunc) http.HandlerFunc {
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "missing bearer token")
|
||||
return
|
||||
}
|
||||
|
||||
u, err := h.Sessions.Lookup(r.Context(), token)
|
||||
if err != nil {
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrUnauthorized):
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "invalid session")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "session store timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "session store unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), userKey, *u)
|
||||
ctx = context.WithValue(ctx, tokenKey, token)
|
||||
next(w, r.WithContext(ctx))
|
||||
|
||||
+64
-17
@@ -2,6 +2,7 @@ package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
@@ -63,11 +64,16 @@ func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
u, err := h.Store.CreateUser(r.Context(), req.Username, req.DisplayName, req.Password)
|
||||
if err == domain.ErrConflict {
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrConflict):
|
||||
writeError(w, r, http.StatusConflict, "conflict", "username taken")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
@@ -91,17 +97,26 @@ func (h *Handler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
u, err := h.Store.VerifyPassword(r.Context(), username, password)
|
||||
if err != nil {
|
||||
if err == domain.ErrUnauthorized {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrUnauthorized):
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "invalid credentials")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
s, err := h.Sessions.Create(r.Context(), *u)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrTimeout) {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "session store timeout")
|
||||
return
|
||||
}
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "session store unavailable")
|
||||
return
|
||||
}
|
||||
@@ -145,11 +160,16 @@ func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
c, err := h.Store.CreateChat(r.Context(), req.Title, req.MemberIDs, me.ID)
|
||||
if err == domain.ErrInvalid {
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid members")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
@@ -162,6 +182,10 @@ func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
chats, err := h.Store.ListChats(r.Context(), me.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrTimeout) {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
}
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
@@ -173,9 +197,18 @@ func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
c, err := h.Store.GetChat(r.Context(), r.PathValue("chat_id"), me.ID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, c)
|
||||
})(w, r)
|
||||
@@ -211,11 +244,16 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
m, err := h.Store.AddMessage(r.Context(), chatID, me.ID, req.Text)
|
||||
if err == domain.ErrNotFound {
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
@@ -242,9 +280,18 @@ func (h *Handler) ListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
items, next, err := h.Store.ListMessages(r.Context(), chatID, limit, cursor)
|
||||
if err != nil {
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "query timeout")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, domain.MessagePage{Items: items, NextCursor: next})
|
||||
})(w, r)
|
||||
|
||||
+9
-8
@@ -38,7 +38,7 @@ func NewSessionCache(ctx context.Context, url string) (*SessionCache, error) {
|
||||
return &SessionCache{rdb: rdb}, nil
|
||||
}
|
||||
|
||||
func (c *SessionCache) key(token string) string { return "session:" + token }
|
||||
func (c *SessionCache) userKey(userID string) string { return "user:" + userID }
|
||||
|
||||
// opCtx возвращает контекст с коротким таймаутом для каждой операции.
|
||||
// Не наследуем HTTP-контекст напрямую, чтобы не блокировать ответ клиенту.
|
||||
@@ -46,7 +46,8 @@ func (c *SessionCache) opCtx() (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
}
|
||||
|
||||
func (c *SessionCache) Set(ctx context.Context, token string, u User, expires time.Time) {
|
||||
// SetUser кладёт публичные данные пользователя в кэш с TTL до конца сессии.
|
||||
func (c *SessionCache) SetUser(ctx context.Context, userID string, u User, expires time.Time) {
|
||||
ttl := time.Until(expires)
|
||||
if ttl <= 0 {
|
||||
return
|
||||
@@ -57,14 +58,13 @@ func (c *SessionCache) Set(ctx context.Context, token string, u User, expires ti
|
||||
}
|
||||
opCtx, cancel := c.opCtx()
|
||||
defer cancel()
|
||||
// Ошибку глотаем: кэш не критичен.
|
||||
_ = c.rdb.Set(opCtx, c.key(token), b, ttl).Err()
|
||||
_ = c.rdb.Set(opCtx, c.userKey(userID), b, ttl).Err()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Get(ctx context.Context, token string) (User, bool) {
|
||||
func (c *SessionCache) GetUser(ctx context.Context, userID string) (User, bool) {
|
||||
opCtx, cancel := c.opCtx()
|
||||
defer cancel()
|
||||
b, err := c.rdb.Get(opCtx, c.key(token)).Bytes()
|
||||
b, err := c.rdb.Get(opCtx, c.userKey(userID)).Bytes()
|
||||
if err != nil {
|
||||
return User{}, false
|
||||
}
|
||||
@@ -75,10 +75,11 @@ func (c *SessionCache) Get(ctx context.Context, token string) (User, bool) {
|
||||
return u, true
|
||||
}
|
||||
|
||||
func (c *SessionCache) Del(ctx context.Context, token string) {
|
||||
// DelUser — на случай удаления пользователя (в lab2 не вызывается).
|
||||
func (c *SessionCache) DelUser(ctx context.Context, userID string) error {
|
||||
opCtx, cancel := c.opCtx()
|
||||
defer cancel()
|
||||
_ = c.rdb.Del(opCtx, c.key(token)).Err()
|
||||
return c.rdb.Del(opCtx, c.userKey(userID)).Err()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Ping(ctx context.Context) error {
|
||||
|
||||
@@ -59,4 +59,6 @@ var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrInvalid = errors.New("invalid request")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrTimeout = errors.New("timeout")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
)
|
||||
|
||||
+64
-29
@@ -25,7 +25,7 @@ type Store struct {
|
||||
func NewStore(ctx context.Context, dsn string) (*Store, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
cfg.MaxConns = 10
|
||||
cfg.MinConns = 1
|
||||
@@ -33,15 +33,24 @@ func NewStore(ctx context.Context, dsn string) (*Store, error) {
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.ConnConfig.ConnectTimeout = 5 * time.Second
|
||||
|
||||
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
||||
_, err := conn.Exec(ctx, `
|
||||
SET statement_timeout = '5s';
|
||||
SET lock_timeout = '2s';
|
||||
SET idle_in_transaction_session_timeout = '5s';
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
ctxPing, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(ctxPing); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
return &Store{pool: pool}, nil
|
||||
}
|
||||
@@ -105,7 +114,7 @@ func verifyPassword(password, encoded string) bool {
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) {
|
||||
hash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
id := uuid.NewString()
|
||||
var u User
|
||||
@@ -120,7 +129,7 @@ func (s *Store) CreateUser(ctx context.Context, username, displayName, password
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
@@ -134,7 +143,7 @@ func (s *Store) GetUserByID(ctx context.Context, id string) (*User, error) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
@@ -154,7 +163,7 @@ func (s *Store) VerifyPassword(ctx context.Context, username, password string) (
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
if !verifyPassword(password, hash) {
|
||||
return nil, ErrUnauthorized
|
||||
@@ -179,7 +188,7 @@ func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
@@ -190,7 +199,7 @@ func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,7 +210,7 @@ func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string
|
||||
chatID, title,
|
||||
).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
for id := range seen {
|
||||
@@ -209,12 +218,12 @@ func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string
|
||||
`INSERT INTO chat_members (chat_id, user_id) VALUES ($1,$2)`,
|
||||
c.ID, id,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
// Порядок member_ids — как в запросе.
|
||||
@@ -232,7 +241,7 @@ func (s *Store) GetChat(ctx context.Context, chatID, userID string) (*Chat, erro
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
var c Chat
|
||||
@@ -243,19 +252,19 @@ func (s *Store) GetChat(ctx context.Context, chatID, userID string) (*Chat, erro
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id`, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var uid string
|
||||
if err := rows.Scan(&uid); err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
c.MemberIDs = append(c.MemberIDs, uid)
|
||||
}
|
||||
@@ -270,7 +279,7 @@ func (s *Store) ListChats(ctx context.Context, userID string) ([]Chat, error) {
|
||||
WHERE m.user_id = $1
|
||||
ORDER BY c.created_at, c.id`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
@@ -278,12 +287,12 @@ func (s *Store) ListChats(ctx context.Context, userID string) ([]Chat, error) {
|
||||
for rows.Next() {
|
||||
var c Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
chats = append(chats, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
// Догружаем участников (небольшие объёмы в учебном сценарии).
|
||||
@@ -291,13 +300,13 @@ func (s *Store) ListChats(ctx context.Context, userID string) ([]Chat, error) {
|
||||
mrows, err := s.pool.Query(ctx,
|
||||
`SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id`, chats[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
for mrows.Next() {
|
||||
var uid string
|
||||
if err := mrows.Scan(&uid); err != nil {
|
||||
mrows.Close()
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
chats[i].MemberIDs = append(chats[i].MemberIDs, uid)
|
||||
}
|
||||
@@ -315,7 +324,7 @@ func (s *Store) AddMessage(ctx context.Context, chatID, senderID, text string) (
|
||||
// Проверка членства + вставка в одной транзакции.
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
@@ -327,7 +336,7 @@ func (s *Store) AddMessage(ctx context.Context, chatID, senderID, text string) (
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
var m Message
|
||||
@@ -338,10 +347,10 @@ func (s *Store) AddMessage(ctx context.Context, chatID, senderID, text string) (
|
||||
uuid.NewString(), chatID, senderID, text,
|
||||
).Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
@@ -370,7 +379,7 @@ func (s *Store) ListMessages(ctx context.Context, chatID string, limit int, curs
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil, ErrInvalid
|
||||
}
|
||||
return nil, nil, err
|
||||
return nil, nil, classifyDBError(err)
|
||||
}
|
||||
rows, err = s.pool.Query(ctx,
|
||||
`SELECT id, chat_id, sender_id, text, created_at
|
||||
@@ -381,7 +390,7 @@ func (s *Store) ListMessages(ctx context.Context, chatID string, limit int, curs
|
||||
LIMIT $4`, chatID, cCreated, cursor, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, classifyDBError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
@@ -389,12 +398,12 @@ func (s *Store) ListMessages(ctx context.Context, chatID string, limit int, curs
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, classifyDBError(err)
|
||||
}
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, classifyDBError(err)
|
||||
}
|
||||
|
||||
var next *string
|
||||
@@ -408,3 +417,29 @@ func (s *Store) ListMessages(ctx context.Context, chatID string, limit int, curs
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
|
||||
func classifyDBError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "57014": // query_canceled (statement_timeout)
|
||||
return ErrTimeout
|
||||
case "55P03": // lock_not_available (lock_timeout)
|
||||
return ErrTimeout
|
||||
case "40001": // serialization_failure
|
||||
return ErrUnavailable
|
||||
case "53300": // too_many_connections
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return ErrTimeout
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
+22
-28
@@ -23,26 +23,25 @@ func NewSessionStore(store *Store, cache *SessionCache, ttl time.Duration) *Sess
|
||||
func newToken() (string, error) {
|
||||
b := make([]byte, 32) // 256 бит
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
return "", classifyDBError(err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// Create создаёт сессию: сначала пишем в PostgreSQL (источник истины), затем кэш.
|
||||
// Create — пишем сессию в БД (источник истины) и кэшируем публичные данные User.
|
||||
func (s *SessionStore) Create(ctx context.Context, user User) (*Session, error) {
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
expires := time.Now().UTC().Add(s.ttl)
|
||||
_, err = s.store.pool.Exec(ctx,
|
||||
if _, err := s.store.pool.Exec(ctx,
|
||||
`INSERT INTO sessions (token, user_id, expires_at) VALUES ($1,$2,$3)`,
|
||||
token, user.ID, expires)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
token, user.ID, expires); err != nil {
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Set(ctx, token, user, expires)
|
||||
s.cache.SetUser(ctx, user.ID, user, expires)
|
||||
}
|
||||
return &Session{
|
||||
Token: token,
|
||||
@@ -52,15 +51,9 @@ func (s *SessionStore) Create(ctx context.Context, user User) (*Session, error)
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Lookup проверяет токен. Сначала кэш; при miss — PostgreSQL.
|
||||
// Истёкшие сессии удаляются лениво.
|
||||
// Lookup ВСЕГДА обращается к PostgreSQL за фактом существования сессии.
|
||||
// Кэш используется только для публичных данных User.
|
||||
func (s *SessionStore) Lookup(ctx context.Context, token string) (*User, error) {
|
||||
if s.cache != nil {
|
||||
if u, ok := s.cache.Get(ctx, token); ok {
|
||||
return &u, nil
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
userID string
|
||||
expiresAt time.Time
|
||||
@@ -72,33 +65,34 @@ func (s *SessionStore) Lookup(ctx context.Context, token string) (*User, error)
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyDBError(err)
|
||||
}
|
||||
if time.Now().UTC().After(expiresAt) {
|
||||
_, _ = s.store.pool.Exec(ctx, `DELETE FROM sessions WHERE token=$1`, token)
|
||||
if s.cache != nil {
|
||||
s.cache.Del(ctx, token)
|
||||
}
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
if u, ok := s.cache.GetUser(ctx, userID); ok {
|
||||
return &u, nil
|
||||
}
|
||||
}
|
||||
|
||||
u, err := s.store.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Set(ctx, token, *u, expiresAt)
|
||||
s.cache.SetUser(ctx, userID, *u, expiresAt)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// Revoke удаляет сессию из БД и кэша.
|
||||
func (s *SessionStore) Revoke(ctx context.Context, token string) error {
|
||||
if _, err := s.store.pool.Exec(ctx, `DELETE FROM sessions WHERE token=$1`, token); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Del(ctx, token)
|
||||
}
|
||||
// Достаём user_id, чтобы потом сбросить кэш User (не обязательно, но полезно).
|
||||
var userID string
|
||||
_ = s.store.pool.QueryRow(ctx,
|
||||
`DELETE FROM sessions WHERE token=$1 RETURNING user_id`, token,
|
||||
).Scan(&userID)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -62,18 +62,22 @@ def test_redis_down_api_still_works(c):
|
||||
|
||||
|
||||
def test_postgres_down_readiness_503(c):
|
||||
"""Остановить PostgreSQL → /health/ready должен вернуть 503."""
|
||||
c.call('GET', '/health/ready', 200, schema='Health')
|
||||
"""Активный токен при недоступном PostgreSQL → 503, не 401."""
|
||||
alice, _, _, _ = c.bootstrap()
|
||||
# очищаем кэш, чтобы гарантированно идти в БД
|
||||
compose('exec', '-T', 'redis', 'redis-cli', 'FLUSHALL')
|
||||
compose('stop', '-t', '1', 'postgres')
|
||||
try:
|
||||
c.call('GET', '/health/ready', 503)
|
||||
c.call('GET', '/api/v1/users/me', 503, actor=alice)
|
||||
# анонимный доступ всё ещё 401
|
||||
c.call('GET', '/api/v1/users/me', 401)
|
||||
finally:
|
||||
compose('start', 'postgres')
|
||||
for _ in range(60):
|
||||
if compose('ps', '--format', 'json', 'postgres', check_rc=False).stdout.find('"Health":"healthy"') >= 0:
|
||||
if '"Health":"healthy"' in compose('ps', '--format', 'json', 'postgres', check_rc=False).stdout:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
print('PASS: /health/ready returns 503 when PostgreSQL is down')
|
||||
print('PASS: PostgreSQL down returns 503 for valid token, not 401')
|
||||
|
||||
|
||||
def test_username_race(c):
|
||||
@@ -118,6 +122,26 @@ def test_logout_removes_from_source_of_truth(c):
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: logout revokes session in source of truth')
|
||||
|
||||
def test_revoked_token_not_resurrected_by_redis(c):
|
||||
"""Отозванный токен не оживает после рестарта Redis."""
|
||||
alice, _, _, _ = c.bootstrap()
|
||||
compose('stop', '-t', '1', 'redis')
|
||||
try:
|
||||
# logout при лежащем Redis
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
# токен уже не работает (Redis лежит, идём в БД)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
finally:
|
||||
compose('start', 'redis')
|
||||
# ждём healthy
|
||||
for _ in range(30):
|
||||
out = compose('ps', '--format', 'json', 'redis', check_rc=False).stdout
|
||||
if '"Health":"healthy"' in out:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
# ключевая проверка: после рестарта Redis тот же токен по-прежнему 401
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: revoked token is not resurrected by Redis restart')
|
||||
|
||||
|
||||
def main():
|
||||
@@ -139,6 +163,7 @@ def main():
|
||||
else:
|
||||
test_redis_down_api_still_works(c)
|
||||
test_postgres_down_readiness_503(c)
|
||||
test_revoked_token_not_resurrected_by_redis(c)
|
||||
|
||||
print('PASS: lab2 level-4 criteria (own tests, no short TTL)')
|
||||
|
||||
|
||||
Reference in New Issue
Block a user