From cc103043b43f77ba014c947459dedc3258b93bc6 Mon Sep 17 00:00:00 2001 From: highperfocused Date: Sat, 8 Mar 2025 21:24:00 +0100 Subject: [PATCH] implement trending system initialization and background updates --- relay/main.go | 4 ++++ relay/trending/kinds.go | 37 +++++++++++++++++++++++++++++++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/relay/main.go b/relay/main.go index be77293..c3c1fcf 100644 --- a/relay/main.go +++ b/relay/main.go @@ -48,6 +48,10 @@ func main() { panic(err) } + // Initialize trending system to start background calculations + fmt.Println("Initializing trending system...") + trending.Initialize(db.DB.DB) + relay.StoreEvent = append(relay.StoreEvent, db.SaveEvent) relay.QueryEvents = append(relay.QueryEvents, db.QueryEvents) relay.DeleteEvent = append(relay.DeleteEvent, db.DeleteEvent) diff --git a/relay/trending/kinds.go b/relay/trending/kinds.go index ca394f9..96be3f9 100644 --- a/relay/trending/kinds.go +++ b/relay/trending/kinds.go @@ -3,6 +3,7 @@ package trending import ( "database/sql" "encoding/json" + "fmt" "time" "git.highperfocused.tech/highperfocused/lumina-relay/relay/cache" @@ -19,16 +20,48 @@ type Post struct { } var ( - trendingCache = cache.New() - cacheDuration = 5 * time.Minute + trendingCache = cache.New() + cacheDuration = 35 * time.Minute // Slightly longer than update interval + updateInterval = 30 * time.Minute ) +// Initialize sets up the background updating of trending calculations +// This should be called once at application startup +func Initialize(db *sql.DB) { + // Perform initial calculation + if _, err := calculateTrendingKind20(db); err != nil { + fmt.Printf("Error in initial trending calculation: %v\n", err) + } + + // Set up periodic updates + go func() { + ticker := time.NewTicker(updateInterval) + defer ticker.Stop() + + for range ticker.C { + if _, err := calculateTrendingKind20(db); err != nil { + fmt.Printf("Error updating trending data: %v\n", err) + } else { + fmt.Printf("Successfully updated trending data at %s\n", time.Now().Format(time.RFC3339)) + } + } + }() +} + // GetTrendingKind20 returns the top 20 trending posts of kind 20 from the last 24 hours +// It returns cached results that are updated periodically in the background func GetTrendingKind20(db *sql.DB) ([]Post, error) { if cached, ok := trendingCache.Get("trending_kind_20"); ok { return cached.([]Post), nil } + // If cache is empty (which shouldn't happen with background updates), + // calculate on demand + return calculateTrendingKind20(db) +} + +// calculateTrendingKind20 performs the actual calculation and updates the cache +func calculateTrendingKind20(db *sql.DB) ([]Post, error) { query := ` WITH reactions AS ( SELECT