package cache import ( "context" "errors" "log" "mtusi2026lab7/internal/adapter/redis" "mtusi2026lab7/internal/application" "mtusi2026lab7/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) CreateQueuedAttachment( ctx context.Context, attachment domain.Attachment, job domain.AttachmentJob, ) (domain.Attachment, error) { queueRepository, ok := r.Repository.(application.AttachmentQueueRepository) if !ok { return domain.Attachment{}, errors.New("attachment queue repository is not configured") } return queueRepository.CreateQueuedAttachment(ctx, attachment, job) } 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)