package store import ( "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "strings" "sync" "time" "github.com/redis/go-redis/v9" "mtusi-messenger/internal/model" ) // redisTimeout — максимальное время на одну Redis-операцию. // При недоступном Redis клиент быстро возвращает ошибку, и мы деградируем // в SQL, а не блокируем запрос (требование уровня 4 про потерю сервиса). const redisTimeout = 300 * time.Millisecond // ─────────────── Кэш сессий (уровень 4) ─────────────── func sessKey(hash [sha256.Size]byte) string { return "sess:" + hex.EncodeToString(hash[:]) } // cacheSessionPut: TTL кэша = остаток срока сессии (политика expiry согласована // с источником истины); при ошибке Redis — только warn, запрос живёт через SQL. func (s *Store) cacheSessionPut(ctx context.Context, hash [sha256.Size]byte, userID string, expiresAt time.Time) { if s.rdb == nil { return } ttl := time.Until(expiresAt) if ttl <= 0 { return } val := userID + "|" + expiresAt.Format(time.RFC3339Nano) rctx, cancel := context.WithTimeout(ctx, redisTimeout) defer cancel() if err := s.rdb.Set(rctx, sessKey(hash), val, ttl).Err(); err != nil { s.log.Warn("redis set failed, degrading to postgres", "error", err.Error()) } } // cacheSessionGet: miss (redis.Nil) — норма; ошибка/таймаут Redis — деградация; // истёкшее значение в кэше не доверяем (двойная страховка помимо TTL). func (s *Store) cacheSessionGet(ctx context.Context, hash [sha256.Size]byte) (string, bool) { if s.rdb == nil { return "", false } rctx, cancel := context.WithTimeout(ctx, redisTimeout) defer cancel() val, err := s.rdb.Get(rctx, sessKey(hash)).Result() if errors.Is(err, redis.Nil) { return "", false } if err != nil { s.log.Warn("redis get failed, degrading to postgres", "error", err.Error()) return "", false } parts := strings.SplitN(val, "|", 2) if len(parts) != 2 { return "", false } exp, err := time.Parse(time.RFC3339Nano, parts[1]) if err != nil || time.Now().UTC().After(exp) { return "", false } return parts[0], true } func (s *Store) cacheSessionDel(ctx context.Context, hash [sha256.Size]byte) error { if s.rdb == nil { return nil } rctx, cancel := context.WithTimeout(ctx, redisTimeout) defer cancel() return s.rdb.Del(rctx, sessKey(hash)).Err() } // ─────────────── Версия чата (инвалидация кэша истории, трек 5) ─────────────── func chatVerKey(chatID string) string { return "chatver:" + chatID } func (s *Store) bumpChatVersion(ctx context.Context, chatID string) { if s.rdb == nil { return } var err error for attempt := 1; attempt <= 3; attempt++ { rctx, cancel := context.WithTimeout(ctx, redisTimeout) err = s.rdb.Incr(rctx, chatVerKey(chatID)).Err() cancel() if err == nil { return } s.log.Warn("redis incr failed, retrying", "attempt", attempt, "error", err.Error()) time.Sleep(50 * time.Millisecond) } s.log.Warn("redis incr failed after retries; history cache bounded stale until TTL", "error", err.Error()) } // ChatVersion: 0 при отсутствии Redis/ключа — кэш истории тогда не используется, // корректность не страдает. func (s *Store) ChatVersion(ctx context.Context, chatID string) int64 { if s.rdb == nil { return 0 } rctx, cancel := context.WithTimeout(ctx, redisTimeout) defer cancel() v, err := s.rdb.Get(rctx, chatVerKey(chatID)).Int64() if err != nil { return 0 } return v } // ─────────────── Кэш истории (трек 5) ─────────────── // HistoryCacheKey — ключ страницы истории: версия чата + параметры запроса. // Версия в ключе — это и есть защита от stale read. func HistoryCacheKey(chatID string, version int64, cursorJSON string, limit int) string { return fmt.Sprintf("hist:v%d:%s:%s:%d", version, chatID, cursorJSON, limit) } // CacheHistoryPut — положить страницу в кэш. TTL 60 c: кэш для горячего чтения, // не долгосрочное хранилище; источник истины остаётся Postgres. func (s *Store) CacheHistoryPut(ctx context.Context, key string, messages []*model.Message, hasMore bool) { if s.rdb == nil { return } data := map[string]any{ "items": messages, "has_more": hasMore, "cached_at": time.Now().UTC().Format(time.RFC3339Nano), } b, err := json.Marshal(data) if err != nil { return } rctx, cancel := context.WithTimeout(ctx, redisTimeout) defer cancel() if err := s.rdb.Set(rctx, key, b, 60*time.Second).Err(); err != nil { s.log.Warn("redis history set failed", "error", err.Error()) } } // CacheHistoryGet — достать страницу из кэша: (items, hasMore, ok). // ok=false означает miss или ошибку Redis — тогда идём в SQL. func (s *Store) CacheHistoryGet(ctx context.Context, key string) ([]*model.Message, bool, bool) { if s.rdb == nil { return nil, false, false } rctx, cancel := context.WithTimeout(ctx, redisTimeout) defer cancel() val, err := s.rdb.Get(rctx, key).Result() if err != nil { return nil, false, false } var data struct { Items []*model.Message `json:"items"` HasMore bool `json:"has_more"` } if err := json.Unmarshal([]byte(val), &data); err != nil { return nil, false, false } return data.Items, data.HasMore, true } // ─────────────── Single-flight (защита от cache stampede) ─────────────── // При конкурирующих холодных чтениях одного ключа только один поток выполняет // fn; остальные ждут его результат. Без этого N конкурентных miss дали бы N // SQL-запросов («лавиной») — это и есть cache stampede. type SingleFlight struct { mu sync.Mutex m map[string]*call } type call struct { wg sync.WaitGroup val any err error } func NewSingleFlight() *SingleFlight { return &SingleFlight{m: make(map[string]*call)} } // Do выполняет fn только если нет активного вызова с тем же key; иначе ждёт // готовый результат того вызова. func (sf *SingleFlight) Do(key string, fn func() (any, error)) (any, error) { sf.mu.Lock() if c, ok := sf.m[key]; ok { sf.mu.Unlock() c.wg.Wait() return c.val, c.err } c := new(call) c.wg.Add(1) sf.m[key] = c sf.mu.Unlock() c.val, c.err = fn() c.wg.Done() sf.mu.Lock() delete(sf.m, key) sf.mu.Unlock() return c.val, c.err } // EncodeCursorJSON — компактное представление курсора для ключа кэша. func EncodeCursorJSON(c *Cursor) string { if c == nil { return "null" } b, _ := json.Marshal(c) return base64.RawURLEncoding.EncodeToString(b) }