RezinaLMS-BackEnd/internal/services/questions/catalog_cache.go
2026-10-19 17:59:34 +03:00

50 lines
1.3 KiB
Go

package questions
import (
"Rezina-Backend/internal/domain"
"context"
"sync"
"time"
)
const activeCatalogTTL = 2 * time.Minute
type activeCatalogCache struct {
mu sync.RWMutex
defs []domain.QuestionTypeDefinition
expiresAt time.Time
}
func (s *Service) invalidateActiveCatalogCache() {
s.catalogCache.mu.Lock()
s.catalogCache.defs = nil
s.catalogCache.expiresAt = time.Time{}
s.catalogCache.mu.Unlock()
}
func (s *Service) ActiveQuestionTypeDefinitionCatalog(ctx context.Context) ([]domain.QuestionTypeDefinition, error) {
now := time.Now()
s.catalogCache.mu.RLock()
if len(s.catalogCache.defs) > 0 && now.Before(s.catalogCache.expiresAt) {
out := append([]domain.QuestionTypeDefinition(nil), s.catalogCache.defs...)
s.catalogCache.mu.RUnlock()
return out, nil
}
s.catalogCache.mu.RUnlock()
s.catalogCache.mu.Lock()
defer s.catalogCache.mu.Unlock()
if len(s.catalogCache.defs) > 0 && time.Now().Before(s.catalogCache.expiresAt) {
return append([]domain.QuestionTypeDefinition(nil), s.catalogCache.defs...), nil
}
active := "ACTIVE"
catalog, _, err := s.questionStore.ListQuestionTypeDefinitions(ctx, &active, true, nil, 0, 0)
if err != nil {
return nil, err
}
s.catalogCache.defs = catalog
s.catalogCache.expiresAt = time.Now().Add(activeCatalogTTL)
return append([]domain.QuestionTypeDefinition(nil), catalog...), nil
}