diff options
Diffstat (limited to 'internal/notifier/notifier.go')
| -rw-r--r-- | internal/notifier/notifier.go | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/internal/notifier/notifier.go b/internal/notifier/notifier.go new file mode 100644 index 0000000..24447a9 --- /dev/null +++ b/internal/notifier/notifier.go @@ -0,0 +1,60 @@ +package notifier + +import ( + "context" + "fmt" + "os" + + "codeberg.org/snonux/gorum/internal/config" +) + +type Notifier struct{} + +func New() Notifier { + return Notifier{} +} + +func (notifier Notifier) Start(ctx context.Context, conf config.Config, scoreCh <-chan string) { + go func() { + for scoresStr := range scoreCh { + if err := notifier.persist(conf, scoresStr); err != nil { + emailNotifyError(conf, err) + } + } + }() +} + +func (notifier Notifier) persist(conf config.Config, scoresStr string) error { + if err := emailNotify(conf, "GORUM: Quorum changed", scoresStr); err != nil { + return err + } + + 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) +} + +// Create tmp file first, and then, once written, rename it. +func writeFileViaTmp(filePath, content string) error { + tmpFilePath := fmt.Sprintf("%s.tmp", filePath) + + fd, err := os.Create(tmpFilePath) + if err != nil { + return err + } + defer fd.Close() + + if _, err := fd.WriteString(content); err != nil { + return err + } + + if err := fd.Sync(); err != nil { + return err + } + + return os.Rename(tmpFilePath, filePath) +} |
