fix: address lab2 review feedback

This commit is contained in:
Fedoroff
2026-10-27 20:03:08 +03:00
parent c251f2cb7d
commit f08011385a
11 changed files with 280 additions and 82 deletions
+14
View File
@@ -199,3 +199,17 @@ func (s *AuthStore) RevokeSession(
}
return nil
}
// GetActiveSessionUserID is the authoritative expiry/revocation check.
// Redis only caches the public user profile; it never grants access on its own.
func (s *AuthStore) GetActiveSessionUserID(ctx context.Context, token string) (uuid.UUID, error) {
var userID uuid.UUID
err := s.pool.QueryRow(ctx, `SELECT user_id FROM sessions WHERE token_hash=$1 AND expires_at>NOW()`, tokenHash(token)).Scan(&userID)
if errors.Is(err, pgx.ErrNoRows) {
return uuid.Nil, ErrSessionNotFound
}
if err != nil {
return uuid.Nil, fmt.Errorf("validate session: %w", err)
}
return userID, nil
}
+40
View File
@@ -203,3 +203,43 @@ func (s *ChatStore) ExistsUser(
// Kept here to document that chat timestamps are stored in UTC.
var _ = time.UTC
// ListChatsPage uses (created_at,id) keyset pagination and fetches limit+1.
func (s *ChatStore) ListChatsPage(ctx context.Context, userID uuid.UUID, limit int, cursorTime *time.Time, cursorID *uuid.UUID) ([]model.Chat, bool, error) {
var rows pgx.Rows
var err error
if cursorTime == nil || cursorID == nil {
rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 ORDER BY c.created_at,c.id LIMIT $2`, userID, limit+1)
} else {
rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 AND (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, userID, *cursorTime, *cursorID, limit+1)
}
if err != nil {
return nil, false, fmt.Errorf("list chats: %w", err)
}
chats := make([]model.Chat, 0, limit+1)
for rows.Next() {
var c model.Chat
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
rows.Close()
return nil, false, err
}
chats = append(chats, c)
}
if err := rows.Err(); err != nil {
rows.Close()
return nil, false, err
}
rows.Close()
more := len(chats) > limit
if more {
chats = chats[:limit]
}
for i := range chats {
members, err := s.getMemberIDs(ctx, chats[i].ID)
if err != nil {
return nil, false, err
}
chats[i].MemberIDs = members
}
return chats, more, nil
}
+16 -16
View File
@@ -4,11 +4,13 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"mtusi2026lab2/internal/model"
"github.com/redis/go-redis/v9"
)
@@ -48,7 +50,7 @@ func cacheKey(token string) string {
func (c *SessionCache) Set(
ctx context.Context,
token string,
userID uuid.UUID,
user model.User,
expiresAt time.Time,
) error {
ttl := time.Until(expiresAt)
@@ -56,33 +58,31 @@ func (c *SessionCache) Set(
return nil
}
return c.client.Set(
ctx,
cacheKey(token),
userID.String(),
ttl,
).Err()
payload, err := json.Marshal(user)
if err != nil {
return err
}
return c.client.Set(ctx, cacheKey(token), payload, ttl).Err()
}
func (c *SessionCache) Get(
ctx context.Context,
token string,
) (uuid.UUID, bool, error) {
) (model.User, bool, error) {
value, err := c.client.Get(ctx, cacheKey(token)).Result()
if errors.Is(err, redis.Nil) {
return uuid.Nil, false, nil
return model.User{}, false, nil
}
if err != nil {
return uuid.Nil, false, err
return model.User{}, false, err
}
userID, err := uuid.Parse(value)
if err != nil {
return uuid.Nil, false, err
var user model.User
if err := json.Unmarshal([]byte(value), &user); err != nil {
return model.User{}, false, err
}
return userID, true, nil
return user, true, nil
}
func (c *SessionCache) Delete(
+28 -22
View File
@@ -37,38 +37,44 @@ func (s *SessionService) CreateSession(
return err
}
// Populate the profile cache best-effort after the authoritative INSERT.
if s.cache != nil {
cacheCtx, cancel := context.WithTimeout(
context.Background(), 2*time.Second,
)
defer cancel()
_ = s.cache.Set(cacheCtx, token, userID, expiresAt)
user, err := s.db.GetUserByID(ctx, userID)
if err == nil {
cacheCtx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
_ = s.cache.Set(cacheCtx, token, user, expiresAt)
cancel()
}
}
return nil
}
func (s *SessionService) GetSessionUser(
ctx context.Context,
token string,
) (model.User, error) {
// PostgreSQL remains the source of truth.
user, err := s.db.GetSessionUser(ctx, token)
func (s *SessionService) GetSessionUser(ctx context.Context, token string) (model.User, error) {
// A cheap indexed PostgreSQL check on EVERY request enforces expiry and logout,
// even if Redis contains a stale value or its deletion fails.
userID, err := s.db.GetActiveSessionUserID(ctx, token)
if err != nil {
return model.User{}, err
}
// Redis is best-effort and cannot extend a session.
if s.cache != nil {
cacheCtx, cancel := context.WithTimeout(
context.Background(), 2*time.Second,
)
defer cancel()
_, _, _ = s.cache.Get(cacheCtx, token)
cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
cached, hit, err := s.cache.Get(cacheCtx, token)
cancel()
if err == nil && hit && cached.ID == userID {
return cached, nil
}
}
user, err := s.db.GetUserByID(ctx, userID)
if err != nil {
return model.User{}, err
}
if s.cache != nil {
cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
// Conservative short TTL on read-through; session lifetime is still checked in PostgreSQL.
_ = s.cache.Set(cacheCtx, token, user, time.Now().Add(30*time.Second))
cancel()
}
return user, nil
}
@@ -82,7 +88,7 @@ func (s *SessionService) RevokeSession(
if s.cache != nil {
cacheCtx, cancel := context.WithTimeout(
context.Background(), 2*time.Second,
context.Background(), 250*time.Millisecond,
)
defer cancel()