implement trending system initialization and background updates

This commit is contained in:
highperfocused 2025-03-08 21:24:00 +01:00
parent cabc153ee8
commit cc103043b4
2 changed files with 39 additions and 2 deletions

View File

@ -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)

View File

@ -3,6 +3,7 @@ package trending
import (
"database/sql"
"encoding/json"
"fmt"
"time"
"git.highperfocused.tech/highperfocused/lumina-relay/relay/cache"
@ -20,15 +21,47 @@ type Post struct {
var (
trendingCache = cache.New()
cacheDuration = 5 * time.Minute
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