forked from mtusi2026/mtusi2026lab3
176 lines
4.0 KiB
Go
176 lines
4.0 KiB
Go
package redis
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"mtusi2026lab3/internal/domain"
|
|
|
|
"github.com/google/uuid"
|
|
goredis "github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
const chatKeyPrefix = "chat:v2:"
|
|
|
|
var ErrMiss = errors.New("cache miss")
|
|
|
|
// ChatCache хранит только производную копию неизменяемых данных чата.
|
|
// PostgreSQL остаётся источником истины.
|
|
type ChatCache interface {
|
|
Get(ctx context.Context, chatID string) (domain.Chat, error)
|
|
Set(ctx context.Context, chat domain.Chat) error
|
|
}
|
|
|
|
type RedisChatCache struct {
|
|
client *goredis.Client
|
|
ttl time.Duration
|
|
operationTimeout time.Duration
|
|
}
|
|
|
|
func NewRedisChatCache(
|
|
redisURL string,
|
|
ttl time.Duration,
|
|
operationTimeout time.Duration,
|
|
poolSize int,
|
|
) (*RedisChatCache, error) {
|
|
options, err := goredis.ParseURL(strings.TrimSpace(redisURL))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse Redis URL: %w", err)
|
|
}
|
|
|
|
options.DialTimeout = operationTimeout
|
|
options.ReadTimeout = operationTimeout
|
|
options.WriteTimeout = operationTimeout
|
|
options.PoolTimeout = operationTimeout
|
|
options.PoolSize = poolSize
|
|
options.MaxRetries = -1
|
|
|
|
return &RedisChatCache{
|
|
client: goredis.NewClient(options),
|
|
ttl: ttl,
|
|
operationTimeout: operationTimeout,
|
|
}, nil
|
|
}
|
|
|
|
func (c *RedisChatCache) Ping(ctx context.Context) error {
|
|
operationContext, cancel := c.withTimeout(ctx)
|
|
defer cancel()
|
|
|
|
if err := c.client.Ping(operationContext).Err(); err != nil {
|
|
return fmt.Errorf("ping Redis: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c *RedisChatCache) Close() error {
|
|
return c.client.Close()
|
|
}
|
|
|
|
func (c *RedisChatCache) Get(
|
|
ctx context.Context,
|
|
chatID string,
|
|
) (domain.Chat, error) {
|
|
operationContext, cancel := c.withTimeout(ctx)
|
|
defer cancel()
|
|
|
|
payload, err := c.client.Get(
|
|
operationContext,
|
|
chatKey(chatID),
|
|
).Bytes()
|
|
if errors.Is(err, goredis.Nil) {
|
|
return domain.Chat{}, ErrMiss
|
|
}
|
|
if err != nil {
|
|
return domain.Chat{}, fmt.Errorf("get cached chat: %w", err)
|
|
}
|
|
|
|
var chat domain.Chat
|
|
if err = json.Unmarshal(payload, &chat); err != nil {
|
|
c.deleteInvalidValue(operationContext, chatID)
|
|
return domain.Chat{}, fmt.Errorf("decode cached chat: %w", err)
|
|
}
|
|
|
|
if err = validateCachedChat(chat, chatID); err != nil {
|
|
c.deleteInvalidValue(operationContext, chatID)
|
|
return domain.Chat{}, err
|
|
}
|
|
|
|
return chat, nil
|
|
}
|
|
|
|
func (c *RedisChatCache) Set(
|
|
ctx context.Context,
|
|
chat domain.Chat,
|
|
) error {
|
|
payload, err := json.Marshal(chat)
|
|
if err != nil {
|
|
return fmt.Errorf("encode chat for cache: %w", err)
|
|
}
|
|
|
|
operationContext, cancel := c.withTimeout(ctx)
|
|
defer cancel()
|
|
|
|
if err = c.client.Set(
|
|
operationContext,
|
|
chatKey(chat.ID),
|
|
payload,
|
|
c.ttl,
|
|
).Err(); err != nil {
|
|
return fmt.Errorf("cache chat: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c *RedisChatCache) withTimeout(
|
|
ctx context.Context,
|
|
) (context.Context, context.CancelFunc) {
|
|
return context.WithTimeout(ctx, c.operationTimeout)
|
|
}
|
|
|
|
func (c *RedisChatCache) deleteInvalidValue(
|
|
ctx context.Context,
|
|
chatID string,
|
|
) {
|
|
_ = c.client.Del(ctx, chatKey(chatID)).Err()
|
|
}
|
|
|
|
func chatKey(chatID string) string {
|
|
return chatKeyPrefix + chatID
|
|
}
|
|
|
|
func validateCachedChat(chat domain.Chat, expectedID string) error {
|
|
if chat.ID != expectedID {
|
|
return errors.New("cached chat id does not match cache key")
|
|
}
|
|
if _, err := uuid.Parse(chat.ID); err != nil {
|
|
return errors.New("cached chat contains invalid id")
|
|
}
|
|
if strings.TrimSpace(chat.Title) == "" || chat.CreatedAt.IsZero() {
|
|
return errors.New("cached chat is incomplete")
|
|
}
|
|
if len(chat.MemberIDs) == 0 {
|
|
return errors.New("cached chat has no members")
|
|
}
|
|
|
|
seenMembers := make(map[string]struct{}, len(chat.MemberIDs))
|
|
for _, memberID := range chat.MemberIDs {
|
|
if _, err := uuid.Parse(memberID); err != nil {
|
|
return errors.New("cached chat contains invalid member id")
|
|
}
|
|
if _, exists := seenMembers[memberID]; exists {
|
|
return errors.New("cached chat contains duplicate member id")
|
|
}
|
|
seenMembers[memberID] = struct{}{}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
var _ ChatCache = (*RedisChatCache)(nil)
|