Add goal notifications and collector health
This commit is contained in:
@@ -7,10 +7,12 @@ import (
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -76,6 +78,8 @@ func New(s *store.Store, admin auth.Checker, loc *time.Location, log *slog.Logge
|
||||
api.Handle("POST /reports", srv.adminAPI(http.HandlerFunc(srv.createReport)))
|
||||
api.Handle("GET /notifications/status", srv.adminAPI(http.HandlerFunc(srv.notificationStatus)))
|
||||
api.Handle("PUT /notifications/config", srv.adminAPI(http.HandlerFunc(srv.updateNotificationConfig)))
|
||||
api.Handle("POST /notifications/goals/check", srv.adminAPI(http.HandlerFunc(srv.checkGoalNotifications)))
|
||||
api.Handle("GET /health/collectors", srv.adminAPI(http.HandlerFunc(srv.collectorHealth)))
|
||||
api.Handle("POST /privacy/purge", srv.adminAPI(http.HandlerFunc(srv.purgePrivacyData)))
|
||||
mux.Handle("/api/v1/", http.StripPrefix("/api/v1", api))
|
||||
|
||||
@@ -555,6 +559,12 @@ func (s *Server) updateNotificationConfig(w http.ResponseWriter, r *http.Request
|
||||
if settings.NtfyServer == "" {
|
||||
settings.NtfyServer = "https://ntfy.sh"
|
||||
}
|
||||
var err error
|
||||
settings.NtfyServer, err = validateNtfyServer(settings.NtfyServer)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if settings.RetentionDays < 0 || (settings.Enabled && settings.NtfyTopic == "") {
|
||||
writeError(w, http.StatusBadRequest, "retention_days must be non-negative and enabled requires ntfy_topic")
|
||||
return
|
||||
@@ -567,6 +577,164 @@ func (s *Server) updateNotificationConfig(w http.ResponseWriter, r *http.Request
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
func (s *Server) checkGoalNotifications(w http.ResponseWriter, r *http.Request) {
|
||||
now := s.now().In(s.loc)
|
||||
from, to := summary.DayBounds(now, s.loc)
|
||||
totals, err := s.store.Totals(r.Context(), from, to)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
goals, err := s.store.Goals(r.Context())
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
results := summary.Evaluate(totals, goals)
|
||||
elapsed := float64(now.Sub(from)) / float64(to.Sub(from))
|
||||
if elapsed < 0 {
|
||||
elapsed = 0
|
||||
}
|
||||
if elapsed > 1 {
|
||||
elapsed = 1
|
||||
}
|
||||
|
||||
settings, err := s.store.NotificationSettings(r.Context())
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
response := map[string]any{
|
||||
"date": from.Format(time.DateOnly),
|
||||
"evaluated": len(results),
|
||||
"at_risk": 0,
|
||||
"sent": 0,
|
||||
"configured": settings.Enabled && settings.NtfyTopic != "",
|
||||
"errors": []string{},
|
||||
}
|
||||
ntfyServer, err := validateNtfyServer(settings.NtfyServer)
|
||||
if err != nil {
|
||||
if settings.Enabled && settings.NtfyTopic != "" {
|
||||
writeError(w, http.StatusInternalServerError, "invalid configured ntfy server")
|
||||
return
|
||||
}
|
||||
ntfyServer = settings.NtfyServer
|
||||
}
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
for _, result := range results {
|
||||
if result.Met || !goalAtRisk(result, elapsed) {
|
||||
continue
|
||||
}
|
||||
response["at_risk"] = response["at_risk"].(int) + 1
|
||||
if !settings.Enabled || settings.NtfyTopic == "" {
|
||||
continue
|
||||
}
|
||||
sent, err := s.store.GoalNotificationSent(r.Context(), result.ID, from)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
if sent {
|
||||
continue
|
||||
}
|
||||
body := fmt.Sprintf("Goal at risk: %s%s, actual %s of %s", result.Kind,
|
||||
formatGoalLabel(result.Label), durationString(result.ActualS), durationString(result.TargetS))
|
||||
req, err := http.NewRequestWithContext(r.Context(), http.MethodPost,
|
||||
ntfyServer+"/"+url.PathEscape(settings.NtfyTopic),
|
||||
strings.NewReader(body))
|
||||
if err == nil {
|
||||
req.Header.Set("Content-Type", "text/plain; charset=utf-8")
|
||||
req.Header.Set("Title", "Goal at risk")
|
||||
req.Header.Set("Priority", "warning")
|
||||
resp, requestErr := client.Do(req)
|
||||
if requestErr == nil {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
if err := s.store.RecordGoalNotification(r.Context(), result.ID, from); err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
response["sent"] = response["sent"].(int) + 1
|
||||
continue
|
||||
}
|
||||
requestErr = fmt.Errorf("ntfy returned %s", resp.Status)
|
||||
}
|
||||
err = requestErr
|
||||
}
|
||||
response["errors"] = append(response["errors"].([]string), err.Error())
|
||||
}
|
||||
writeJSON(w, http.StatusOK, response)
|
||||
}
|
||||
|
||||
func validateNtfyServer(raw string) (string, error) {
|
||||
server := strings.TrimRight(strings.TrimSpace(raw), "/")
|
||||
u, err := url.Parse(server)
|
||||
if err != nil || u.Scheme == "" || u.Host == "" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return "", fmt.Errorf("ntfy_server must be an absolute http or https URL")
|
||||
}
|
||||
if u.Scheme != "http" && u.Scheme != "https" {
|
||||
return "", fmt.Errorf("ntfy_server must be an absolute http or https URL")
|
||||
}
|
||||
return server, nil
|
||||
}
|
||||
|
||||
func goalAtRisk(result summary.GoalResult, elapsed float64) bool {
|
||||
if result.Op == ">=" {
|
||||
return result.TargetS > 0 && float64(result.ActualS) < float64(result.TargetS)*elapsed
|
||||
}
|
||||
return result.ActualS > result.TargetS
|
||||
}
|
||||
|
||||
func formatGoalLabel(label string) string {
|
||||
if label == "" {
|
||||
return ""
|
||||
}
|
||||
return " (" + label + ")"
|
||||
}
|
||||
|
||||
func durationString(seconds int64) string {
|
||||
return (time.Duration(seconds) * time.Second).String()
|
||||
}
|
||||
|
||||
func (s *Server) collectorHealth(w http.ResponseWriter, r *http.Request) {
|
||||
health, err := s.store.CollectorHealth(r.Context())
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
now := s.now()
|
||||
collectors := make([]map[string]any, 0, len(health))
|
||||
for _, h := range health {
|
||||
status := "healthy"
|
||||
var age any
|
||||
if h.Device.RevokedAt != nil {
|
||||
status = "revoked"
|
||||
} else if h.Device.LastSeenAt == nil {
|
||||
status = "never_seen"
|
||||
} else {
|
||||
seconds := int64(now.Sub(*h.Device.LastSeenAt).Seconds())
|
||||
if seconds < 0 {
|
||||
seconds = 0
|
||||
}
|
||||
age = seconds
|
||||
if seconds > int64((48 * time.Hour).Seconds()) {
|
||||
status = "stale"
|
||||
}
|
||||
}
|
||||
collectors = append(collectors, map[string]any{
|
||||
"id": h.Device.ID, "name": h.Device.Name, "kind": h.Device.Kind,
|
||||
"last_seen": h.Device.LastSeenAt, "age_s": age, "status": status,
|
||||
"activity_count": h.ActivityCount, "sample_count": h.SampleCount,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"collectors": collectors})
|
||||
}
|
||||
|
||||
func (s *Server) purgePrivacyData(w http.ResponseWriter, r *http.Request) {
|
||||
cutoff := r.URL.Query().Get("before")
|
||||
if cutoff == "" {
|
||||
|
||||
Reference in New Issue
Block a user