diff options
| author | Paul Buetow <paul@buetow.org> | 2023-11-07 23:16:57 +0200 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2023-11-07 23:16:57 +0200 |
| commit | 50326b808865ed27df587a2b49a012c0339fb998 (patch) | |
| tree | d3bc89c22d88256555926adf9b01aad826214cc9 /internal/notifier/notifier.go | |
| parent | 314aa39afda105969567c4f95b07147f372fcf98 (diff) | |
add notifier package
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) +} |
