diff options
| -rw-r--r-- | internal/notifier/notifier.go | 53 |
1 files changed, 44 insertions, 9 deletions
diff --git a/internal/notifier/notifier.go b/internal/notifier/notifier.go index 24447a9..70e6096 100644 --- a/internal/notifier/notifier.go +++ b/internal/notifier/notifier.go @@ -3,7 +3,9 @@ package notifier import ( "context" "fmt" + "log" "os" + "time" "codeberg.org/snonux/gorum/internal/config" ) @@ -15,31 +17,64 @@ func New() Notifier { } func (notifier Notifier) Start(ctx context.Context, conf config.Config, scoreCh <-chan string) { + // Email throttle channel + ch := make(chan string, 1) + go func() { for scoresStr := range scoreCh { - if err := notifier.persist(conf, scoresStr); err != nil { + if err := notifier.persistToDisk(conf, scoresStr); err != nil { + log.Println(err) + // TODO: This kind of email should be throttled, too. In case + // there are many errors! emailNotifyError(conf, err) } + if cap(ch) == len(ch) { + // Remove the curret score, and replace it with a new score + <-ch + ch <- scoresStr + } + } + }() + + // Throttle how quickly quorum changes are sent out via email. + go func() { + throttleDuration := time.Duration(conf.MailThrottle) + + for { + select { + case scoresStr := <-ch: + if err := notifier.sendEmail(conf, scoresStr); err != nil { + log.Println(err) + } + case <-ctx.Done(): + return + } + + log.Println("notifier: sleeping some seconds before next E-Mail notification", throttleDuration) + select { + case <-time.After(throttleDuration): + case <-ctx.Done(): + return + } + } }() } -func (notifier Notifier) persist(conf config.Config, scoresStr string) error { - if err := emailNotify(conf, "GORUM: Quorum changed", scoresStr); err != nil { - return err - } +func (notifier Notifier) sendEmail(conf config.Config, scoresStr string) error { + return emailNotify(conf, "GORUM: Quorum changed", scoresStr) +} +func (notifier Notifier) persistToDisk(conf config.Config, scoresStr string) error { if _, err := os.Stat(conf.StateDir); os.IsNotExist(err) { if err := os.MkdirAll(conf.StateDir, 0755); err != nil { return err } } - - return writeFileViaTmp(fmt.Sprintf("%s/%s", conf.StateDir, conf.ScoreFile), scoresStr) + return notifier.writeFileViaTmp(fmt.Sprintf("%s/%s", conf.StateDir, conf.ScoreFile), scoresStr) } -// Create tmp file first, and then, once written, rename it. -func writeFileViaTmp(filePath, content string) error { +func (Notifier) writeFileViaTmp(filePath, content string) error { tmpFilePath := fmt.Sprintf("%s.tmp", filePath) fd, err := os.Create(tmpFilePath) |
