feat(cache): add read-through cache layer across all app services
Introduce a generic read-through caching infrastructure and wire it into all major tenant app services to reduce database load on hot read paths. Key changes: - Add `DeletePrefix` to Cache interface with memory (prefix scan) and Redis (SCAN + DEL) implementations - New `readthrough.go`: generic `LoadJSON` / `LoadJSONWithEmpty` helpers backed by singleflight to prevent cache stampedes; supports jittered TTL - New `cache_support.go`: centralized cache key builders and invalidation helpers for all entities (workspace, brand, prompt rules, schedule tasks, articles) - Wire optional cache into ArticleService, BrandService, WorkspaceService, PromptRuleService, ScheduleTaskService, TemplateService, MediaService, PromptGenerateService via `WithCache()` builder pattern - ScheduleDispatchWorker invalidates schedule task cache after dispatching - ArticleService gains a new `Detail` endpoint with empty-result caching - Update cmd entrypoints and transport handlers to propagate cache
This commit is contained in:
@@ -6,8 +6,10 @@ import (
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"github.com/geo-platform/tenant-api/internal/shared/auth"
|
||||
sharedcache "github.com/geo-platform/tenant-api/internal/shared/cache"
|
||||
"github.com/geo-platform/tenant-api/internal/shared/response"
|
||||
"github.com/geo-platform/tenant-api/internal/tenant/domain"
|
||||
"github.com/geo-platform/tenant-api/internal/tenant/repository"
|
||||
@@ -17,88 +19,99 @@ type WorkspaceService struct {
|
||||
repo repository.WorkspaceRepository
|
||||
templates repository.TemplateRepository
|
||||
supportedPlatformCount int
|
||||
cache sharedcache.Cache
|
||||
cacheGroup singleflight.Group
|
||||
}
|
||||
|
||||
func NewWorkspaceService(repo repository.WorkspaceRepository, templates repository.TemplateRepository) *WorkspaceService {
|
||||
return &WorkspaceService{repo: repo, templates: templates, supportedPlatformCount: 5}
|
||||
}
|
||||
|
||||
func (s *WorkspaceService) WithCache(c sharedcache.Cache) *WorkspaceService {
|
||||
s.cache = c
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *WorkspaceService) Overview(ctx context.Context) (*domain.WorkspaceOverview, error) {
|
||||
actor := auth.MustActor(ctx)
|
||||
articleCount, err := s.repo.CountArticlesByTenant(ctx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to count articles")
|
||||
}
|
||||
publishedCount, err := s.repo.CountPublishedArticlesByTenant(ctx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to count published articles")
|
||||
}
|
||||
brandCount, err := s.repo.CountBrandsByTenant(ctx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to count brands")
|
||||
}
|
||||
return sharedcache.LoadJSON(ctx, s.cache, &s.cacheGroup, workspaceOverviewCacheKey(actor.TenantID), defaultCacheTTL(), func(loadCtx context.Context) (*domain.WorkspaceOverview, error) {
|
||||
articleCount, err := s.repo.CountArticlesByTenant(loadCtx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to count articles")
|
||||
}
|
||||
publishedCount, err := s.repo.CountPublishedArticlesByTenant(loadCtx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to count published articles")
|
||||
}
|
||||
brandCount, err := s.repo.CountBrandsByTenant(loadCtx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to count brands")
|
||||
}
|
||||
|
||||
return &domain.WorkspaceOverview{
|
||||
ArticleCount: articleCount,
|
||||
PublishedCount: publishedCount,
|
||||
BrandCount: brandCount,
|
||||
SupportedPlatformCount: s.supportedPlatformCount,
|
||||
}, nil
|
||||
return &domain.WorkspaceOverview{
|
||||
ArticleCount: articleCount,
|
||||
PublishedCount: publishedCount,
|
||||
BrandCount: brandCount,
|
||||
SupportedPlatformCount: s.supportedPlatformCount,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *WorkspaceService) RecentArticles(ctx context.Context) ([]domain.RecentArticle, error) {
|
||||
actor := auth.MustActor(ctx)
|
||||
return sharedcache.LoadJSON(ctx, s.cache, &s.cacheGroup, workspaceRecentArticlesCacheKey(actor.TenantID), defaultCacheTTL(), func(loadCtx context.Context) ([]domain.RecentArticle, error) {
|
||||
rows, err := s.repo.GetRecentArticles(loadCtx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to fetch recent articles")
|
||||
}
|
||||
|
||||
rows, err := s.repo.GetRecentArticles(ctx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to fetch recent articles")
|
||||
}
|
||||
|
||||
articles := make([]domain.RecentArticle, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
articles = append(articles, domain.RecentArticle{
|
||||
ID: row.ID,
|
||||
GenerateStatus: row.GenerateStatus,
|
||||
PublishStatus: row.PublishStatus,
|
||||
SourceType: row.SourceType,
|
||||
GenerationMode: row.GenerationMode,
|
||||
CreatedAt: row.CreatedAt,
|
||||
Title: row.Title,
|
||||
WordCount: row.WordCount,
|
||||
SourceLabel: row.SourceLabel,
|
||||
TemplateName: row.TemplateName,
|
||||
})
|
||||
}
|
||||
return articles, nil
|
||||
articles := make([]domain.RecentArticle, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
articles = append(articles, domain.RecentArticle{
|
||||
ID: row.ID,
|
||||
GenerateStatus: row.GenerateStatus,
|
||||
PublishStatus: row.PublishStatus,
|
||||
SourceType: row.SourceType,
|
||||
GenerationMode: row.GenerationMode,
|
||||
CreatedAt: row.CreatedAt,
|
||||
Title: row.Title,
|
||||
WordCount: row.WordCount,
|
||||
SourceLabel: row.SourceLabel,
|
||||
TemplateName: row.TemplateName,
|
||||
})
|
||||
}
|
||||
return articles, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *WorkspaceService) QuotaSummary(ctx context.Context) (*domain.QuotaSummary, error) {
|
||||
actor := auth.MustActor(ctx)
|
||||
|
||||
balance, err := s.repo.GetQuotaSummary(ctx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to get quota balance")
|
||||
}
|
||||
|
||||
plan, err := s.repo.GetActivePlanForTenant(ctx, actor.TenantID)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return &domain.QuotaSummary{Balance: balance}, nil
|
||||
return sharedcache.LoadJSON(ctx, s.cache, &s.cacheGroup, workspaceQuotaSummaryCacheKey(actor.TenantID), defaultCacheTTL(), func(loadCtx context.Context) (*domain.QuotaSummary, error) {
|
||||
balance, err := s.repo.GetQuotaSummary(loadCtx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to get quota balance")
|
||||
}
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to get active plan")
|
||||
}
|
||||
|
||||
var policy map[string]int
|
||||
_ = json.Unmarshal(plan.QuotaPolicyJSON, &policy)
|
||||
total := policy["article_generation"]
|
||||
plan, err := s.repo.GetActivePlanForTenant(loadCtx, actor.TenantID)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return &domain.QuotaSummary{Balance: balance}, nil
|
||||
}
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to get active plan")
|
||||
}
|
||||
|
||||
return &domain.QuotaSummary{
|
||||
PlanCode: plan.PlanCode,
|
||||
PlanName: plan.PlanName,
|
||||
TotalQuota: total,
|
||||
UsedQuota: total - balance,
|
||||
Balance: balance,
|
||||
}, nil
|
||||
var policy map[string]int
|
||||
_ = json.Unmarshal(plan.QuotaPolicyJSON, &policy)
|
||||
total := policy["article_generation"]
|
||||
|
||||
return &domain.QuotaSummary{
|
||||
PlanCode: plan.PlanCode,
|
||||
PlanName: plan.PlanName,
|
||||
TotalQuota: total,
|
||||
UsedQuota: total - balance,
|
||||
Balance: balance,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
type TemplateCard struct {
|
||||
@@ -113,24 +126,25 @@ type TemplateCard struct {
|
||||
|
||||
func (s *WorkspaceService) TemplateCards(ctx context.Context) ([]TemplateCard, error) {
|
||||
actor := auth.MustActor(ctx)
|
||||
|
||||
rows, err := s.templates.ListTemplates(ctx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to fetch templates")
|
||||
}
|
||||
|
||||
cards := make([]TemplateCard, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
card := TemplateCard{
|
||||
ID: row.ID,
|
||||
Scope: row.Scope,
|
||||
TemplateKey: row.TemplateKey,
|
||||
TemplateName: row.TemplateName,
|
||||
OriginType: row.OriginType,
|
||||
PromptVisibility: effectivePromptVisibility(&row, actor.TenantID),
|
||||
return sharedcache.LoadJSON(ctx, s.cache, &s.cacheGroup, workspaceTemplateCardsCacheKey(actor.TenantID), defaultCacheTTL(), func(loadCtx context.Context) ([]TemplateCard, error) {
|
||||
rows, err := s.templates.ListTemplates(loadCtx, actor.TenantID)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to fetch templates")
|
||||
}
|
||||
_ = json.Unmarshal(row.CardConfigJSON, &card.CardConfigJSON)
|
||||
cards = append(cards, card)
|
||||
}
|
||||
return cards, nil
|
||||
|
||||
cards := make([]TemplateCard, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
card := TemplateCard{
|
||||
ID: row.ID,
|
||||
Scope: row.Scope,
|
||||
TemplateKey: row.TemplateKey,
|
||||
TemplateName: row.TemplateName,
|
||||
OriginType: row.OriginType,
|
||||
PromptVisibility: effectivePromptVisibility(&row, actor.TenantID),
|
||||
}
|
||||
_ = json.Unmarshal(row.CardConfigJSON, &card.CardConfigJSON)
|
||||
cards = append(cards, card)
|
||||
}
|
||||
return cards, nil
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user