package redis import ( "context" "encoding/json" "fmt" "time" "github.com/redis/go-redis/v9" "github.com/charawein/mtusi2026lab2/internal/domain" ) type MessageCache struct { client *redis.Client } func NewMessageCache(client *redis.Client) *MessageCache { return &MessageCache{client: client} } type cacheEntry struct { Items []*domain.Message `json:"items"` NextCursor string `json:"next_cursor"` } func cacheKey(chatID, cursor string, limit int) string { return fmt.Sprintf("messages:%s:%s:%d", chatID, cursor, limit) } func (c *MessageCache) Get(ctx context.Context, chatID, cursor string, limit int) ([]*domain.Message, string, bool) { raw, err := c.client.Get(ctx, cacheKey(chatID, cursor, limit)).Bytes() if err != nil { return nil, "", false } var e cacheEntry if err := json.Unmarshal(raw, &e); err != nil { return nil, "", false } return e.Items, e.NextCursor, true } func (c *MessageCache) Set(ctx context.Context, chatID, cursor string, limit int, items []*domain.Message, next string) { e := cacheEntry{Items: items, NextCursor: next} raw, _ := json.Marshal(e) _ = c.client.Set(ctx, cacheKey(chatID, cursor, limit), raw, 30*time.Second).Err() } // Invalidate удаляет все ключи для чата через SCAN (безопасно на больших объёмах). func (c *MessageCache) Invalidate(ctx context.Context, chatID string) error { pattern := fmt.Sprintf("messages:%s:*", chatID) iter := c.client.Scan(ctx, 0, pattern, 100).Iterator() for iter.Next(ctx) { _ = c.client.Del(ctx, iter.Val()).Err() } return iter.Err() }