RezinaLMS-BackEnd/internal/services/questions/catalog_cache.go
Yared Yemane eb1d0c68e2 Speed up API paths with batch question loads, request memoization, and soft caches.
Also replace question options on update so placement grading stays consistent with admin edits, and tune the Postgres pool defaults.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 00:06:43 -07:00

50 lines
1.3 KiB
Go

package questions
import (
"Yimaru-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
}