summaryrefslogtreecommitdiff
path: root/internal/notifier/notifier.go
blob: 5fa193638dd26c609c0f6fc143010a455fc047af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package notifier

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"codeberg.org/snonux/gorum/internal/config"
)

func Start(ctx context.Context, conf config.Config, scoreCh <-chan string) {
	changedCh := make(chan email, 1)
	errorCh := make(chan email, 1)

	update := func(ch chan email, email email) {
		// Replace (update) current element in the channel.
		if cap(ch) == len(ch) {
			<-ch
		}
		ch <- email
	}

	go func() {
		go sendEmail(ctx, "change report", conf, changedCh)
		go sendEmail(ctx, "error report", conf, errorCh)

		for scoresStr := range scoreCh {
			if err := persistToDisk(conf, scoresStr); err != nil {
				update(errorCh, email{"GORUM error", err.Error()})
			}
			update(changedCh, email{"GORUM changed", scoresStr})
		}
	}()
}

func sendEmail(ctx context.Context, what string, conf config.Config, ch <-chan email) {
	throttleDuration := time.Duration(conf.MailThrottle)

	for {
		select {
		case email := <-ch:
			if err := email.send(conf); err != nil {
				log.Println(err)
			}
		case <-ctx.Done():
			return
		}

		select {
		case <-time.After(throttleDuration):
			log.Println("notifier:", what, "slept some seconds", throttleDuration)
		case <-ctx.Done():
			return
		}
	}
}

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

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