forked from mtusi2026/mtusi2026lab3
feat: implement lab3 load balancing and idempotency
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type SessionCache struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionCache(redisURL string) (*SessionCache, error) {
|
||||
options, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid redis URL: %w", err)
|
||||
}
|
||||
|
||||
options.DialTimeout = 2 * time.Second
|
||||
options.ReadTimeout = 2 * time.Second
|
||||
options.WriteTimeout = 2 * time.Second
|
||||
options.MaxRetries = 0
|
||||
|
||||
return &SessionCache{
|
||||
client: redis.NewClient(options),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *SessionCache) Close() error {
|
||||
return c.client.Close()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Ping(ctx context.Context) error {
|
||||
return c.client.Ping(ctx).Err()
|
||||
}
|
||||
|
||||
func cacheKey(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "session:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (c *SessionCache) Set(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
user model.User,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
ttl := time.Until(expiresAt)
|
||||
if ttl <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.client.Set(ctx, cacheKey(token), payload, ttl).Err()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Get(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (model.User, bool, error) {
|
||||
value, err := c.client.Get(ctx, cacheKey(token)).Result()
|
||||
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return model.User{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
|
||||
var user model.User
|
||||
if err := json.Unmarshal([]byte(value), &user); err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
return user, true, nil
|
||||
}
|
||||
|
||||
func (c *SessionCache) Delete(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
return c.client.Del(ctx, cacheKey(token)).Err()
|
||||
}
|
||||
Reference in New Issue
Block a user