lab2: fix review — cache consistency, readiness, timeouts, uuid validation, tuple index
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -19,30 +19,39 @@ func NewMessageCache(client *redis.Client) *MessageCache {
|
||||
return &MessageCache{client: client}
|
||||
}
|
||||
|
||||
func (c *MessageCache) Get(ctx context.Context, chatID, cursor string) ([]*domain.Message, bool) {
|
||||
key := fmt.Sprintf("messages:%s:%s", chatID, cursor)
|
||||
raw, err := c.client.Get(ctx, key).Bytes()
|
||||
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
|
||||
return nil, "", false
|
||||
}
|
||||
var msgs []*domain.Message
|
||||
if err := json.Unmarshal(raw, &msgs); err != nil {
|
||||
return nil, false
|
||||
var e cacheEntry
|
||||
if err := json.Unmarshal(raw, &e); err != nil {
|
||||
return nil, "", false
|
||||
}
|
||||
return msgs, true
|
||||
return e.Items, e.NextCursor, true
|
||||
}
|
||||
|
||||
func (c *MessageCache) Set(ctx context.Context, chatID, cursor string, msgs []*domain.Message) {
|
||||
key := fmt.Sprintf("messages:%s:%s", chatID, cursor)
|
||||
raw, _ := json.Marshal(msgs)
|
||||
_ = c.client.Set(ctx, key, raw, 30*time.Second).Err()
|
||||
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)
|
||||
keys, err := c.client.Keys(ctx, pattern).Result()
|
||||
if err != nil || len(keys) == 0 {
|
||||
return err
|
||||
iter := c.client.Scan(ctx, 0, pattern, 100).Iterator()
|
||||
for iter.Next(ctx) {
|
||||
_ = c.client.Del(ctx, iter.Val()).Err()
|
||||
}
|
||||
return c.client.Del(ctx, keys...).Err()
|
||||
return iter.Err()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user