package session import ( "context" "encoding/hex" "encoding/json" "errors" "fmt" "os" "strings" "time" "github.com/redis/go-redis/v9" "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" ) var _ Store = (*Valkey)(nil) const keyPrefix = "session:" type Valkey struct { client *redis.Client } func NewValkey(client *redis.Client) *Valkey { return &Valkey{client: client} } func Connect(ctx context.Context, cfg config.Cache) (*redis.Client, error) { url, err := urlFrom(cfg) if err != nil { return nil, err } opts, err := redis.ParseURL(url) if err != nil { return nil, errors.New("session: invalid CACHE_URL") } timeout := time.Duration(cfg.TimeoutMs) * time.Millisecond opts.PoolSize = cfg.PoolSize opts.DialTimeout = timeout opts.ReadTimeout = timeout opts.WriteTimeout = timeout opts.PoolTimeout = timeout opts.MaxRetries = 1 client := redis.NewClient(opts) pingCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() if err := client.Ping(pingCtx).Err(); err != nil { _ = client.Close() return nil, fmt.Errorf("session: ping: %w", err) } return client, nil } func urlFrom(cfg config.Cache) (string, error) { if cfg.URLFile != "" { b, err := os.ReadFile(cfg.URLFile) if err != nil { return "", fmt.Errorf("session: read CACHE_URL_FILE: %w", err) } return strings.TrimSpace(string(b)), nil } if cfg.URL != "" { return cfg.URL, nil } return "", errors.New("session: CACHE_URL_FILE or CACHE_URL is required") } func key(tokenHash []byte) string { return keyPrefix + hex.EncodeToString(tokenHash) } func (v *Valkey) Save(ctx context.Context, tokenHash []byte, s Session) error { val, err := json.Marshal(s) if err != nil { return err } // NX: 256-битный токен не совпадёт, но перезаписать чужую сессию нельзя даже теоретически. err = v.client.SetArgs(ctx, key(tokenHash), val, redis.SetArgs{ Mode: "NX", ExpireAt: s.ExpiresAt, }).Err() if errors.Is(err, redis.Nil) { return fmt.Errorf("session: token collision") } return unavailable(err) } func (v *Valkey) Get(ctx context.Context, tokenHash []byte) (Session, error) { val, err := v.client.Get(ctx, key(tokenHash)).Bytes() if errors.Is(err, redis.Nil) { return Session{}, ErrNotFound } if err != nil { return Session{}, unavailable(err) } var s Session if err := json.Unmarshal(val, &s); err != nil { return Session{}, fmt.Errorf("session: corrupt value: %w", err) } return s, nil } func (v *Valkey) Delete(ctx context.Context, tokenHash []byte) error { return unavailable(v.client.Del(ctx, key(tokenHash)).Err()) } func (v *Valkey) Ping(ctx context.Context) error { return unavailable(v.client.Ping(ctx).Err()) } func unavailable(err error) error { if err == nil { return nil } return fmt.Errorf("%w: session store: %v", domain.ErrUnavailable, err) }