forked from mtusi2026/mtusi2026lab2
72 lines
1.6 KiB
Go
72 lines
1.6 KiB
Go
package redis
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
"uuid"
|
|
|
|
goredis "github.com/redis/go-redis/v9"
|
|
|
|
"messenger/internal/domain"
|
|
)
|
|
|
|
const keyPrefix = "session:"
|
|
|
|
type SessionStore struct {
|
|
client *goredis.Client
|
|
}
|
|
|
|
func NewClient(url string) (*goredis.Client, error) {
|
|
opts, err := goredis.ParseURL(url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
opts.PoolSize = 10
|
|
opts.DialTimeout = 2 * time.Second
|
|
opts.ReadTimeout = time.Second
|
|
opts.WriteTimeout = time.Second
|
|
opts.MaxRetries = 0
|
|
return goredis.NewClient(opts), nil
|
|
}
|
|
|
|
func NewSessionStore(client *goredis.Client) *SessionStore {
|
|
return &SessionStore{client: client}
|
|
}
|
|
|
|
func (s *SessionStore) Ping(ctx context.Context) error {
|
|
return cacheErr(s.client.Ping(ctx).Err())
|
|
}
|
|
|
|
func (s *SessionStore) Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error {
|
|
return cacheErr(s.client.SetArgs(ctx, keyPrefix+tokenHash, userID.String(),
|
|
goredis.SetArgs{ExpireAt: expiresAt}).Err())
|
|
}
|
|
|
|
func (s *SessionStore) Get(ctx context.Context, tokenHash string) (uuid.UUID, error) {
|
|
v, err := s.client.Get(ctx, keyPrefix+tokenHash).Result()
|
|
if errors.Is(err, goredis.Nil) {
|
|
return uuid.UUID{}, domain.ErrUnauthorized
|
|
}
|
|
if err != nil {
|
|
return uuid.UUID{}, cacheErr(err)
|
|
}
|
|
id, err := uuid.Parse(v)
|
|
if err != nil {
|
|
return uuid.UUID{}, domain.ErrUnauthorized
|
|
}
|
|
return id, nil
|
|
}
|
|
|
|
func (s *SessionStore) Delete(ctx context.Context, tokenHash string) error {
|
|
return cacheErr(s.client.Del(ctx, keyPrefix+tokenHash).Err())
|
|
}
|
|
|
|
func cacheErr(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("%w: %v", domain.ErrUnavailable, err)
|
|
}
|