Files
mtusi2026lab4/internal/adapter/cache/repository.go
T
2026-10-28 12:40:39 +03:00

100 lines
2.3 KiB
Go

package cache
import (
"context"
"errors"
"log"
"mtusi2026lab4/internal/adapter/redis"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
)
// CachedRepository декорирует основной Repository. Все операции, кроме чтения
// и создания чата, автоматически делегируются встроенному Repository.
type CachedRepository struct {
application.Repository
chatCache redis.ChatCache
logger *log.Logger
}
func NewCachedRepository(
repository application.Repository,
chatCache redis.ChatCache,
logger *log.Logger,
) *CachedRepository {
if logger == nil {
logger = log.Default()
}
return &CachedRepository{
Repository: repository,
chatCache: chatCache,
logger: logger,
}
}
func (r *CachedRepository) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
) (domain.Chat, error) {
chat, err := r.Repository.CreateChat(ctx, title, memberIDs)
if err != nil {
return domain.Chat{}, err
}
// Запись в PostgreSQL уже подтверждена. Ошибка необязательного кэша не
// должна превращать успешную бизнес-операцию в 503.
if err = r.chatCache.Set(ctx, chat); err != nil {
r.logger.Printf("[WARN] Redis chat cache write failed: %v", err)
}
return chat, nil
}
func (r *CachedRepository) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
chat, err := r.chatCache.Get(ctx, chatID)
if err == nil {
if !containsMember(chat.MemberIDs, callerID) {
return domain.Chat{}, domain.ErrNotFound
}
return chat, nil
}
shouldFillCache := errors.Is(err, redis.ErrMiss)
if !shouldFillCache {
r.logger.Printf("[WARN] Redis chat cache read failed: %v", err)
}
chat, err = r.Repository.GetChatByID(ctx, chatID, callerID)
if err != nil {
return domain.Chat{}, err
}
if shouldFillCache {
if err = r.chatCache.Set(ctx, chat); err != nil {
r.logger.Printf("[WARN] Redis chat cache fill failed: %v", err)
}
}
return chat, nil
}
func containsMember(memberIDs []string, callerID string) bool {
for _, memberID := range memberIDs {
if memberID == callerID {
return true
}
}
return false
}
var _ application.Repository = (*CachedRepository)(nil)