smon/notification/pkg.go

64 lines
1.2 KiB
Go
Raw Permalink Normal View History

2024-05-05 10:10:04 +02:00
package notification
import (
// External
werr "git.gibonuddevalla.se/go/wrappederror"
// Standard
"log/slog"
"slices"
)
type Service interface {
SetLogger(*slog.Logger)
GetPrio() int
GetType() string
2024-05-05 20:16:28 +02:00
Send(int, []byte) error
2024-05-05 10:10:04 +02:00
}
type Manager struct {
services []Service
logger *slog.Logger
}
func NewManager(logger *slog.Logger) (nm Manager) {
nm.services = []Service{}
nm.logger = logger
return
}
func (nm *Manager) AddService(service Service) {
nm.services = append(nm.services, service)
slices.SortFunc(nm.services, func(a, b Service) int {
if a.GetPrio() < b.GetPrio() {
return -1
}
if a.GetPrio() > b.GetPrio() {
return 1
}
return 0
})
}
2024-05-05 20:16:28 +02:00
func (nm *Manager) Send(problemID int, msg []byte, fn func(*Service, error)) (err error) {
for i, service := range nm.services {
2024-05-05 10:10:04 +02:00
nm.logger.Info("notification", "service", service.GetType(), "prio", service.GetPrio())
2024-05-05 20:16:28 +02:00
if err = service.Send(problemID, msg); err == nil {
fn(&nm.services[i], nil)
2024-05-05 10:10:04 +02:00
break
} else {
data := struct {
2024-05-05 20:16:28 +02:00
ProblemID int
2024-05-05 10:10:04 +02:00
Msg []byte
}{
2024-05-05 20:16:28 +02:00
problemID,
2024-05-05 10:10:04 +02:00
msg,
}
werr.Wrap(err).WithData(data).Log()
2024-05-05 20:16:28 +02:00
fn(&nm.services[i], err)
2024-05-05 10:10:04 +02:00
}
}
return
}