smon/notification/pkg.go

94 lines
1.8 KiB
Go
Raw Normal View History

2024-05-05 10:10:04 +02:00
package notification
import (
// External
werr "git.gibonuddevalla.se/go/wrappederror"
// Standard
"log/slog"
2024-06-28 15:28:52 +02:00
"net/url"
2024-05-05 10:10:04 +02:00
"slices"
)
type Service interface {
SetLogger(*slog.Logger)
GetPrio() int
GetType() string
2024-06-28 15:28:52 +02:00
SetPrio(int)
SetExists(bool) // Exists in database
Exists() bool // Exists in database
String() string
2024-05-05 20:16:28 +02:00
Send(int, []byte) error
2024-06-28 15:28:52 +02:00
Update(url.Values) error
Updated() Service
Commit()
JSON() []byte
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) {
2024-06-28 15:28:52 +02:00
service.SetExists(true)
2024-05-05 10:10:04 +02:00
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-06-28 15:28:52 +02:00
func (nm *Manager) GetService(prio int) *Service {
for _, svc := range nm.services {
if svc.GetPrio() == prio {
return &svc
}
}
return nil
}
2024-06-28 17:18:08 +02:00
func (nm *Manager) RemoveService(prioToRemove int) {
nm.services = slices.DeleteFunc(nm.services, func(svc Service) bool {
return svc.GetPrio() == prioToRemove
})
}
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-06-28 15:28:52 +02:00
Msg []byte
2024-05-05 10:10:04 +02:00
}{
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
}
2024-06-28 15:28:52 +02:00
func (nm *Manager) Services() (services []Service) {
return nm.services
}