Recursive approach with message passing through channels

This commit is contained in:
Imbus 2024-09-30 05:29:07 +02:00
parent eb0cc6d7f2
commit 7256d26f1a
2 changed files with 41 additions and 27 deletions

View file

@ -9,7 +9,7 @@
"repo": "linux"
}
],
"interval": 5,
"interval": 1200,
"ntfy_topic": "hee4waeNguch"
}

View file

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