From 5bd210b59d98c6384ffb6034d21ac4da44d83e04 Mon Sep 17 00:00:00 2001 From: kk10 Date: Tue, 6 Oct 2026 15:36:52 +0300 Subject: [PATCH] feat(auth): cache sessions in redis with postgres fallback --- docker-compose.yml | 2 -- go.mod | 4 +++ go.sum | 27 +++++++++++++----- internal/app/app.go | 16 ++++++++++- internal/redis/client.go | 31 +++++++++++++++++++++ internal/service/auth.go | 59 +++++++++++++++++++++++++++++++++++++--- scripts/restart.sh | 2 +- 7 files changed, 126 insertions(+), 15 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index eaa1e10..caf3650 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -14,8 +14,6 @@ services: depends_on: migrate: condition: service_completed_successfully - redis: - condition: service_healthy restart: unless-stopped postgres: diff --git a/go.mod b/go.mod index 658d8f9..a1de767 100644 --- a/go.mod +++ b/go.mod @@ -7,13 +7,17 @@ require ( github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.11.0 github.com/joho/godotenv v1.5.1 + github.com/redis/go-redis/v9 v9.23.0 golang.org/x/crypto v0.57.0 ) require ( + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect + go.uber.org/atomic v1.12.0 // indirect golang.org/x/sync v0.23.0 // indirect + golang.org/x/sys v0.48.0 // indirect golang.org/x/text v0.42.0 // indirect ) diff --git a/go.sum b/go.sum index 1c8ee76..8e78d73 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,10 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -15,20 +19,29 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s= +github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= +go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/app/app.go b/internal/app/app.go index dfa8d02..e4e9224 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -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) diff --git a/internal/redis/client.go b/internal/redis/client.go index 65a229e..65ccd3a 100644 --- a/internal/redis/client.go +++ b/internal/redis/client.go @@ -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 +} diff --git a/internal/service/auth.go b/internal/service/auth.go index 84a2944..e15cc64 100644 --- a/internal/service/auth.go +++ b/internal/service/auth.go @@ -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 +} diff --git a/scripts/restart.sh b/scripts/restart.sh index 5a124d2..8b31375 100644 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -1,4 +1,4 @@ #!/bin/sh set -eu -docker compose restart postgres api +docker compose restart postgres redis api