forked from mtusi2026/mtusi2026lab3
feat(auth): make session cache optional via SESSION_STORE
This commit is contained in:
@@ -7,6 +7,8 @@ LOG_LEVEL=INFO
|
||||
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
|
||||
# Session store: postgres | redis (redis requires CACHE_URL_FILE)
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
|
||||
API_REPLICAS=2
|
||||
|
||||
+17
-10
@@ -10,6 +10,8 @@ import (
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi2026-messenger/internal/config"
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/logger"
|
||||
@@ -42,18 +44,23 @@ func Run() error {
|
||||
|
||||
queries := db.New(pool)
|
||||
|
||||
cacheURL, err := cfg.Redis.URL()
|
||||
if err != nil {
|
||||
log.Error("read redis url", "error", err)
|
||||
return err
|
||||
var rdb *goredis.Client
|
||||
if cfg.UseCache() {
|
||||
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()
|
||||
}
|
||||
|
||||
rdb, err := redis.New(context.Background(), log, cacheURL)
|
||||
if err != nil {
|
||||
log.Error("create redis client", "error", err)
|
||||
return err
|
||||
}
|
||||
defer rdb.Close()
|
||||
log.Info("session store configured", "store", cfg.SessionStore)
|
||||
|
||||
cleanupCtx, stopCleanup := context.WithCancel(context.Background())
|
||||
cleanupDone := make(chan struct{})
|
||||
|
||||
@@ -10,11 +10,21 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
SessionStorePostgres = "postgres"
|
||||
SessionStoreRedis = "redis"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Server ServerConfig
|
||||
Logging LoggingConfig
|
||||
Database DatabaseConfig
|
||||
Redis RedisConfig
|
||||
Server ServerConfig
|
||||
Logging LoggingConfig
|
||||
Database DatabaseConfig
|
||||
Redis RedisConfig
|
||||
SessionStore string
|
||||
}
|
||||
|
||||
func (c Config) UseCache() bool {
|
||||
return c.SessionStore == SessionStoreRedis
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
@@ -64,6 +74,8 @@ func Load() Config {
|
||||
Redis: RedisConfig{
|
||||
URLFile: getEnv("CACHE_URL_FILE", "/run/secrets/cache_url"),
|
||||
},
|
||||
|
||||
SessionStore: getEnvSessionStore("SESSION_STORE", SessionStorePostgres),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,3 +151,17 @@ func readSecretFile(path string) (string, error) {
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func getEnvSessionStore(key, def string) string {
|
||||
v := strings.ToLower(os.Getenv(key))
|
||||
|
||||
switch v {
|
||||
case "":
|
||||
return def
|
||||
case SessionStorePostgres, SessionStoreRedis:
|
||||
return v
|
||||
default:
|
||||
log.Printf("invalid session store for %s=%q, using default %s", key, v, def)
|
||||
return def
|
||||
}
|
||||
}
|
||||
|
||||
+56
-25
@@ -93,18 +93,8 @@ func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID
|
||||
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)
|
||||
if id, ok := s.cacheGet(ctx, key); ok {
|
||||
return id, nil
|
||||
}
|
||||
|
||||
row, err := s.q.GetActiveSession(ctx, tokenHash)
|
||||
@@ -115,14 +105,7 @@ func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID
|
||||
return uuid.Nil, err
|
||||
}
|
||||
|
||||
ttl := min(time.Until(row.ExpiresAt), sessionCacheTTL)
|
||||
if ttl > 0 {
|
||||
cctx, cancel = context.WithTimeout(ctx, cacheOpTimeout)
|
||||
if err := s.cache.Set(cctx, key, row.UserID.String(), ttl).Err(); err != nil {
|
||||
s.log.Warn("session cache set failed", "error", err)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
s.cacheSet(ctx, key, row.UserID, min(time.Until(row.ExpiresAt), sessionCacheTTL))
|
||||
|
||||
return row.UserID, nil
|
||||
}
|
||||
@@ -135,11 +118,7 @@ func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
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)
|
||||
}
|
||||
s.cacheDel(ctx, cacheKey(tokenHash))
|
||||
|
||||
if n == 0 {
|
||||
return ErrUnauthorized
|
||||
@@ -150,3 +129,55 @@ func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
func cacheKey(tokenHash string) string {
|
||||
return "session:" + tokenHash
|
||||
}
|
||||
|
||||
func (s *AuthService) cacheGet(ctx context.Context, key string) (uuid.UUID, bool) {
|
||||
if s.cache == nil {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
||||
defer cancel()
|
||||
|
||||
val, err := s.cache.Get(cctx, key).Result()
|
||||
switch {
|
||||
case err == nil:
|
||||
id, perr := uuid.Parse(val)
|
||||
if perr != nil {
|
||||
s.log.Warn("session cache value is not a uuid", "error", perr)
|
||||
return uuid.Nil, false
|
||||
}
|
||||
s.log.Debug("session cache hit")
|
||||
return id, true
|
||||
case errors.Is(err, goredis.Nil):
|
||||
s.log.Debug("session cache miss")
|
||||
default:
|
||||
s.log.Warn("session cache get failed, falling back to database", "error", err)
|
||||
}
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
func (s *AuthService) cacheSet(ctx context.Context, key string, id uuid.UUID, ttl time.Duration) {
|
||||
if s.cache == nil || ttl <= 0 {
|
||||
return
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := s.cache.Set(cctx, key, id.String(), ttl).Err(); err != nil {
|
||||
s.log.Warn("session cache set failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AuthService) cacheDel(ctx context.Context, key string) {
|
||||
if s.cache == nil {
|
||||
return
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := s.cache.Del(cctx, key).Err(); err != nil {
|
||||
s.log.Warn("session cache delete failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user