From 7256d26f1a075284e61c40114781616b9ebf81b2 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Mon, 30 Sep 2024 05:29:07 +0200 Subject: [PATCH] Recursive approach with message passing through channels --- config.json | 2 +- src/main.go | 66 ++++++++++++++++++++++++++++++++--------------------- 2 files changed, 41 insertions(+), 27 deletions(-) diff --git a/config.json b/config.json index 8fbd882..92042bf 100644 --- a/config.json +++ b/config.json @@ -9,7 +9,7 @@ "repo": "linux" } ], - "interval": 5, + "interval": 1200, "ntfy_topic": "hee4waeNguch" } diff --git a/src/main.go b/src/main.go index 12c1596..1ea0b1f 100644 --- a/src/main.go +++ b/src/main.go @@ -2,9 +2,43 @@ package main import ( "log" + "math/rand" "time" ) +type RepoUpdate struct { + repo RepoConfig + Tag string +} + +func notifierThread(c chan RepoUpdate, n Notifier) { + update := <-c + log.Printf("New tag stored for %s: %s", update.repo.Repo, update.Tag) + if n.Notify(update.repo, update.Tag) { + log.Printf("Notified for %s/%s: %s", update.repo.Owner, update.repo.Repo, update.Tag) + } + notifierThread(c, n) +} + +func repoThread(c chan RepoUpdate, repo RepoConfig, avgInterval int, db Db) { + log.Println("Checking", repo.Repo) + tag, err := repo.GetLatestTag() + isNewVersion, err_2 := db.CheckAndStore(repo.Owner, repo.Repo) + + if err != nil { + log.Printf("Failed to fetch latest tag for %s: %v", repo.Repo, err) + } else if err_2 != nil { + log.Printf("Failed to store latest tag for %s: %v", repo.Repo, err_2) + } else if isNewVersion { + c <- RepoUpdate{repo, tag.Name} + } + + sleepTime := time.Duration(rand.Intn(avgInterval)) * time.Second + time.Sleep(sleepTime) + + repoThread(c, repo, avgInterval, db) +} + func main() { // Load configuration config, err := loadConfig("config.json") @@ -20,32 +54,12 @@ func main() { notifier := NtfyNotifier{Topic: config.NtfyTopic} - // Main loop - for { - for _, repo := range config.Repos { - tag, err := repo.GetLatestTag() - if err != nil { - log.Printf("Failed to get latest tag for %s: %v", repo.Repo, err) - continue - } - if tag.Name == "" { - log.Printf("No tags found for %s", repo.Repo) - continue - } + c := make(chan RepoUpdate) - // Check and store tag - stored, err := db.CheckAndStore(repo.Repo, tag.Name) - if err != nil { - log.Printf("Failed to store tag for %s: %v", repo.Repo, err) - continue - } - if stored { - log.Printf("New tag stored for %s: %s", repo.Repo, tag.Name) - if notifier.Notify(repo, tag.Name) { - log.Printf("Notified for %s/%s: %s", repo.Owner, repo.Repo, tag.Name) - } - } - } - time.Sleep(time.Duration(config.Interval) * time.Second) + // Spawn a goroutine for each repository + for _, repo := range config.Repos { + go repoThread(c, repo, config.Interval, db) } + + notifierThread(c, notifier) }