feat(redis): session repository with native TTL and main connection
This commit is contained in:
@@ -7,15 +7,18 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"high-loud-apps-labs/internal/config"
|
"high-loud-apps-labs/internal/config"
|
||||||
|
"high-loud-apps-labs/internal/domain"
|
||||||
"high-loud-apps-labs/internal/httpapi"
|
"high-loud-apps-labs/internal/httpapi"
|
||||||
"high-loud-apps-labs/internal/httpapi/handler"
|
"high-loud-apps-labs/internal/httpapi/handler"
|
||||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||||
"high-loud-apps-labs/internal/service"
|
"high-loud-apps-labs/internal/service"
|
||||||
"high-loud-apps-labs/internal/storage/postgres"
|
"high-loud-apps-labs/internal/storage/postgres"
|
||||||
|
redisstore "high-loud-apps-labs/internal/storage/redis"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -46,10 +49,13 @@ func main() {
|
|||||||
|
|
||||||
store := postgres.New(pool)
|
store := postgres.New(pool)
|
||||||
|
|
||||||
|
sessionRepo, closeSession := newSessionRepo(cfg, store)
|
||||||
|
defer closeSession()
|
||||||
|
|
||||||
hasher := service.NewArgon2idHasher()
|
hasher := service.NewArgon2idHasher()
|
||||||
|
|
||||||
userSvc := service.NewUserService(store.Users(), hasher)
|
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())
|
chatSvc := service.NewChatService(store.Chats(), store.Users())
|
||||||
messageSvc := service.NewMessageService(store.Messages(), store.Chats())
|
messageSvc := service.NewMessageService(store.Messages(), store.Chats())
|
||||||
|
|
||||||
@@ -64,13 +70,10 @@ func main() {
|
|||||||
middleware.BearerAuth(sessionSvc),
|
middleware.BearerAuth(sessionSvc),
|
||||||
)
|
)
|
||||||
|
|
||||||
srv := &http.Server{
|
srv := &http.Server{Addr: addr, Handler: router}
|
||||||
Addr: addr,
|
|
||||||
Handler: router,
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
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) {
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
log.Fatalf("Ошибка запуска: %v", err)
|
log.Fatalf("Ошибка запуска: %v", err)
|
||||||
}
|
}
|
||||||
@@ -88,3 +91,22 @@ func main() {
|
|||||||
}
|
}
|
||||||
log.Println("Сервер остановлен")
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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()}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
Reference in New Issue
Block a user