forked from mtusi2026/mtusi2026lab2
feat(auth): cache sessions in redis with postgres fallback
This commit is contained in:
+15
-1
@@ -14,6 +14,7 @@ import (
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/logger"
|
||||
"mtusi2026-messenger/internal/postgres"
|
||||
"mtusi2026-messenger/internal/redis"
|
||||
"mtusi2026-messenger/internal/service"
|
||||
)
|
||||
|
||||
@@ -41,6 +42,19 @@ func Run() error {
|
||||
|
||||
queries := db.New(pool)
|
||||
|
||||
cacheURL, err := cfg.Redis.URL()
|
||||
if err != nil {
|
||||
log.Error("read redis url", "error", err)
|
||||
return err
|
||||
}
|
||||
|
||||
rdb, err := redis.New(context.Background(), log, cacheURL)
|
||||
if err != nil {
|
||||
log.Error("create redis client", "error", err)
|
||||
return err
|
||||
}
|
||||
defer rdb.Close()
|
||||
|
||||
cleanupCtx, stopCleanup := context.WithCancel(context.Background())
|
||||
cleanupDone := make(chan struct{})
|
||||
go func() {
|
||||
@@ -52,7 +66,7 @@ func Run() error {
|
||||
<-cleanupDone
|
||||
}()
|
||||
|
||||
authService := service.NewAuthService(queries, cfg.Server.SessionTTL)
|
||||
authService := service.NewAuthService(queries, rdb, cfg.Server.SessionTTL, log)
|
||||
userService := service.NewUserService(queries)
|
||||
chatService := service.NewChatService(pool, queries)
|
||||
messageService := service.NewMessageService(queries)
|
||||
|
||||
@@ -1 +1,32 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func New(ctx context.Context, log *slog.Logger, url string) (*goredis.Client, error) {
|
||||
opts, err := goredis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse redis url: %w", err)
|
||||
}
|
||||
|
||||
opts.DialTimeout = 1 * time.Second
|
||||
opts.ReadTimeout = 200 * time.Millisecond
|
||||
opts.WriteTimeout = 200 * time.Millisecond
|
||||
opts.MaxRetries = -1
|
||||
|
||||
client := goredis.NewClient(opts)
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
if err := client.Ping(pingCtx).Err(); err != nil {
|
||||
log.Warn("redis unavailable, running without cache", "error", err)
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"mtusi2026-messenger/internal/credentials"
|
||||
@@ -11,8 +12,12 @@ import (
|
||||
"mtusi2026-messenger/internal/postgres"
|
||||
|
||||
"github.com/google/uuid"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const sessionCacheTTL = 60 * time.Second
|
||||
const cacheOpTimeout = 300 * time.Millisecond
|
||||
|
||||
var (
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
@@ -27,13 +32,17 @@ type authQueries interface {
|
||||
|
||||
type AuthService struct {
|
||||
q authQueries
|
||||
cache *goredis.Client
|
||||
sessionTTL time.Duration
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewAuthService(q authQueries, sessionTTL time.Duration) *AuthService {
|
||||
func NewAuthService(q authQueries, cache *goredis.Client, sessionTTL time.Duration, log *slog.Logger) *AuthService {
|
||||
return &AuthService{
|
||||
q: q,
|
||||
cache: cache,
|
||||
sessionTTL: sessionTTL,
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,7 +90,24 @@ func (s *AuthService) Login(ctx context.Context, username, plain string) (model.
|
||||
}
|
||||
|
||||
func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
userID, err := s.q.GetSessionUserID(ctx, credentials.HashToken(token))
|
||||
tokenHash := credentials.HashToken(token)
|
||||
key := cacheKey(tokenHash)
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
||||
val, err := s.cache.Get(cctx, key).Result()
|
||||
cancel()
|
||||
|
||||
if err == nil {
|
||||
id, perr := uuid.Parse(val)
|
||||
if perr == nil {
|
||||
return id, nil
|
||||
}
|
||||
s.log.Warn("session cache value is not a uuid", "error", perr)
|
||||
} else if !errors.Is(err, goredis.Nil) {
|
||||
s.log.Warn("session cache get failed, falling back to database", "error", err)
|
||||
}
|
||||
|
||||
userID, err := s.q.GetSessionUserID(ctx, tokenHash)
|
||||
if postgres.IsNotFound(err) {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
@@ -89,17 +115,42 @@ func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID
|
||||
return uuid.Nil, err
|
||||
}
|
||||
|
||||
cctx, cancel = context.WithTimeout(ctx, cacheOpTimeout)
|
||||
if err := s.cache.Set(cctx, key, userID.String(), s.cacheTTL()).Err(); err != nil {
|
||||
s.log.Warn("session cache set failed", "error", err)
|
||||
}
|
||||
cancel()
|
||||
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
n, err := s.q.DeleteSession(ctx, credentials.HashToken(token))
|
||||
tokenHash := credentials.HashToken(token)
|
||||
|
||||
n, err := s.q.DeleteSession(ctx, tokenHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
||||
defer cancel()
|
||||
if err := s.cache.Del(cctx, cacheKey(tokenHash)).Err(); err != nil {
|
||||
s.log.Warn("session cache delete failed", "error", err)
|
||||
}
|
||||
|
||||
if n == 0 {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func cacheKey(tokenHash string) string {
|
||||
return "session:" + tokenHash
|
||||
}
|
||||
|
||||
func (s *AuthService) cacheTTL() time.Duration {
|
||||
if s.sessionTTL < sessionCacheTTL {
|
||||
return s.sessionTTL
|
||||
}
|
||||
return sessionCacheTTL
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user