From 812efa67bb94bf3075bc5d827ecd866d4a99713c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=93=D0=BE=D0=BB=D0=B8=D0=BA=D0=BE=D0=B2=20Maximillian?= =?UTF-8?q?=20=D0=90=D0=BD=D1=82=D0=BE=D0=BD?= Date: Fri, 2 Oct 2026 14:02:55 +0300 Subject: [PATCH] feat(redis): session repository with native TTL and main connection --- backend/cmd/server/main.go | 34 ++++++++-- backend/internal/storage/redis/client.go | 32 +++++++++ backend/internal/storage/redis/errors.go | 26 ++++++++ backend/internal/storage/redis/session.go | 80 +++++++++++++++++++++++ 4 files changed, 166 insertions(+), 6 deletions(-) create mode 100644 backend/internal/storage/redis/client.go create mode 100644 backend/internal/storage/redis/errors.go create mode 100644 backend/internal/storage/redis/session.go diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go index 4846e9a7..30f75b98 100644 --- a/backend/cmd/server/main.go +++ b/backend/cmd/server/main.go @@ -7,15 +7,18 @@ import ( "net/http" "os" "os/signal" + "strings" "syscall" "time" "high-loud-apps-labs/internal/config" + "high-loud-apps-labs/internal/domain" "high-loud-apps-labs/internal/httpapi" "high-loud-apps-labs/internal/httpapi/handler" "high-loud-apps-labs/internal/httpapi/middleware" "high-loud-apps-labs/internal/service" "high-loud-apps-labs/internal/storage/postgres" + redisstore "high-loud-apps-labs/internal/storage/redis" ) func main() { @@ -46,10 +49,13 @@ func main() { store := postgres.New(pool) + sessionRepo, closeSession := newSessionRepo(cfg, store) + defer closeSession() + hasher := service.NewArgon2idHasher() userSvc := service.NewUserService(store.Users(), hasher) - sessionSvc := service.NewSessionService(store.Users(), store.Sessions(), hasher, cfg.SessionTTL) + sessionSvc := service.NewSessionService(store.Users(), sessionRepo, hasher, cfg.SessionTTL) chatSvc := service.NewChatService(store.Chats(), store.Users()) messageSvc := service.NewMessageService(store.Messages(), store.Chats()) @@ -64,13 +70,10 @@ func main() { middleware.BearerAuth(sessionSvc), ) - srv := &http.Server{ - Addr: addr, - Handler: router, - } + srv := &http.Server{Addr: addr, Handler: router} go func() { - log.Printf("Запускаем на %s", addr) + log.Printf("Запускаем на %s (SESSION_STORE=%s)", addr, cfg.SessionStore) if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatalf("Ошибка запуска: %v", err) } @@ -88,3 +91,22 @@ func main() { } log.Println("Сервер остановлен") } + +func newSessionRepo(cfg *config.Config, store *postgres.Storage) (domain.SessionRepository, func()) { + switch strings.ToLower(cfg.SessionStore) { + case "", "postgres": + return store.Sessions(), func() {} + case "redis", "valkey": + if cfg.CacheURL == "" { + log.Fatalf("SESSION_STORE=%s требует CACHE_URL_FILE или CACHE_URL", cfg.SessionStore) + } + client, err := redisstore.NewClient(cfg.CacheURL) + if err != nil { + log.Fatalf("redis: %v", err) + } + return redisstore.NewSessionRepo(client), func() { _ = client.Close() } + default: + log.Fatalf("SESSION_STORE=%q не поддерживается", cfg.SessionStore) + return nil, nil + } +} diff --git a/backend/internal/storage/redis/client.go b/backend/internal/storage/redis/client.go new file mode 100644 index 00000000..9680e60a --- /dev/null +++ b/backend/internal/storage/redis/client.go @@ -0,0 +1,32 @@ +package redis + +import ( + "context" + "fmt" + "time" + + "github.com/redis/go-redis/v9" +) + +func NewClient(url string) (*redis.Client, error) { + opt, err := redis.ParseURL(url) + if err != nil { + return nil, fmt.Errorf("разбор URL: %w", err) + } + + opt.DialTimeout = 5 * time.Second + opt.ReadTimeout = 3 * time.Second + opt.WriteTimeout = 3 * time.Second + opt.MaxRetries = 2 + opt.PoolSize = 10 + + client := redis.NewClient(opt) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := client.Ping(ctx).Err(); err != nil { + _ = client.Close() + return nil, fmt.Errorf("ping: %w", err) + } + return client, nil +} diff --git a/backend/internal/storage/redis/errors.go b/backend/internal/storage/redis/errors.go new file mode 100644 index 00000000..c2cc4355 --- /dev/null +++ b/backend/internal/storage/redis/errors.go @@ -0,0 +1,26 @@ +package redis + +import ( + "context" + "errors" + + "high-loud-apps-labs/internal/domain" +) + +type coded interface { + Code() domain.ErrorCode +} + +func mapError(err error) error { + if err == nil { + return nil + } + var c coded + if errors.As(err, &c) { + return err + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return err + } + return &domain.UnavailableError{Reason: err.Error()} +} diff --git a/backend/internal/storage/redis/session.go b/backend/internal/storage/redis/session.go new file mode 100644 index 00000000..0aecfd59 --- /dev/null +++ b/backend/internal/storage/redis/session.go @@ -0,0 +1,80 @@ +package redis + +import ( + "context" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/redis/go-redis/v9" + + "high-loud-apps-labs/internal/domain" +) + +const sessionKeyPrefix = "session:" + +type SessionRepo struct { + client *redis.Client +} + +func NewSessionRepo(client *redis.Client) *SessionRepo { + return &SessionRepo{client: client} +} + +type sessionValue struct { + UserID string `json:"user_id"` + ExpiresAt time.Time `json:"expires_at"` + CreatedAt time.Time `json:"created_at"` +} + +func (r *SessionRepo) key(tokenHash []byte) string { + return sessionKeyPrefix + hex.EncodeToString(tokenHash) +} + +func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error { + ttl := time.Until(s.ExpiresAt) + if ttl <= 0 { + return nil + } + + data, err := json.Marshal(sessionValue{ + UserID: s.UserID, + ExpiresAt: s.ExpiresAt.UTC(), + CreatedAt: s.CreatedAt.UTC(), + }) + if err != nil { + return fmt.Errorf("сериализация сессии: %w", err) + } + + return mapError(r.client.Set(ctx, r.key(s.TokenHash), data, ttl).Err()) +} + +func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) { + data, err := r.client.Get(ctx, r.key(tokenHash)).Bytes() + if err != nil { + if errors.Is(err, redis.Nil) { + return nil, &domain.NotFoundError{Entity: "session"} + } + return nil, mapError(err) + } + + var sv sessionValue + if err := json.Unmarshal(data, &sv); err != nil { + return nil, fmt.Errorf("разбор сессии: %w", err) + } + + return &domain.Session{ + TokenHash: tokenHash, + UserID: sv.UserID, + ExpiresAt: sv.ExpiresAt, + CreatedAt: sv.CreatedAt, + }, nil +} + +func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error { + return mapError(r.client.Del(ctx, r.key(tokenHash)).Err()) +} + +var _ domain.SessionRepository = (*SessionRepo)(nil)