forked from mtusi2026/mtusi2026lab5
ЛР 5: асинхронная обработка изображений, уровень 5
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ Store = (*Memory)(nil)
|
||||
|
||||
type Memory struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]Session
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewMemory() *Memory {
|
||||
return &Memory{sessions: make(map[string]Session), now: time.Now}
|
||||
}
|
||||
|
||||
func (m *Memory) Save(_ context.Context, tokenHash []byte, s Session) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.sessions[string(tokenHash)] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Get(_ context.Context, tokenHash []byte) (Session, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
s, ok := m.sessions[string(tokenHash)]
|
||||
if !ok {
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
if !m.now().Before(s.ExpiresAt) {
|
||||
delete(m.sessions, string(tokenHash))
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (m *Memory) Delete(_ context.Context, tokenHash []byte) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.sessions, string(tokenHash))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Ping(context.Context) error { return nil }
|
||||
@@ -0,0 +1,21 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
var ErrNotFound = errors.New("session: not found")
|
||||
|
||||
type Store interface {
|
||||
Save(ctx context.Context, tokenHash []byte, s Session) error
|
||||
Get(ctx context.Context, tokenHash []byte) (Session, error)
|
||||
Delete(ctx context.Context, tokenHash []byte) error
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user