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 == "" {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"ccp/internal/auth"
|
||||
"ccp/internal/store"
|
||||
"ccp/internal/summary"
|
||||
"ccp/internal/testdb"
|
||||
)
|
||||
|
||||
@@ -171,12 +172,80 @@ func TestSamplesReportsAndSettings(t *testing.T) {
|
||||
if code != http.StatusOK || len(out["samples"].([]any)) != 1 {
|
||||
t.Fatalf("range summary: %d %v", code, out)
|
||||
}
|
||||
code, out = do(t, "PUT", srv.URL+"/api/v1/notifications/config", "", `{"enabled":true,"ntfy_topic":"goals","retention_days":30}`)
|
||||
ntfyBody := make(chan string, 1)
|
||||
ntfy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
ntfyBody <- string(body)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
t.Cleanup(ntfy.Close)
|
||||
config := `{"enabled":true,"ntfy_server":"` + ntfy.URL + `","ntfy_topic":"goals","retention_days":30}`
|
||||
code, out = do(t, "PUT", srv.URL+"/api/v1/notifications/config", "", config)
|
||||
if code != http.StatusOK || out["ntfy_topic"] != "goals" {
|
||||
t.Fatalf("notification config: %d %v", code, out)
|
||||
}
|
||||
code, out = do(t, "POST", srv.URL+"/api/v1/notifications/goals/check", "", "")
|
||||
if code != http.StatusOK || out["sent"] != 1.0 || out["at_risk"] != 1.0 {
|
||||
t.Fatalf("goal notification: %d %v", code, out)
|
||||
}
|
||||
select {
|
||||
case body := <-ntfyBody:
|
||||
if !strings.Contains(body, "Goal at risk") {
|
||||
t.Fatalf("ntfy body = %q", body)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("timed out waiting for ntfy request")
|
||||
}
|
||||
code, out = do(t, "POST", srv.URL+"/api/v1/notifications/goals/check", "", "")
|
||||
if code != http.StatusOK || out["sent"] != 0.0 || out["at_risk"] != 1.0 {
|
||||
t.Fatalf("duplicate goal notification: %d %v", code, out)
|
||||
}
|
||||
code, out = do(t, "GET", srv.URL+"/api/v1/health/collectors", "", "")
|
||||
collectors := out["collectors"].([]any)
|
||||
if code != http.StatusOK || len(collectors) != 1 {
|
||||
t.Fatalf("collector health: %d %v", code, out)
|
||||
}
|
||||
collector := collectors[0].(map[string]any)
|
||||
if collector["status"] != "healthy" || collector["activity_count"] != 0.0 || collector["sample_count"] != 1.0 {
|
||||
t.Fatalf("collector health entry: %v", collector)
|
||||
}
|
||||
code, out = do(t, "POST", srv.URL+"/api/v1/reports", "", `{"period_start":"`+ts.Format(time.RFC3339)+`","period_end":"`+ts.Add(time.Hour).Format(time.RFC3339)+`","model":"test","body":"summary"}`)
|
||||
if code != http.StatusCreated || out["id"] == nil {
|
||||
t.Fatalf("report create: %d %v", code, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateNtfyServer(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{"https", "https://ntfy.example", true},
|
||||
{"http", "http://127.0.0.1:8080/ntfy", true},
|
||||
{"relative", "ntfy.example", false},
|
||||
{"unsupported scheme", "ftp://ntfy.example", false},
|
||||
{"missing host", "https:///topic", false},
|
||||
{"malformed", "https://[::1", false},
|
||||
{"userinfo", "https://user:[email protected]", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := validateNtfyServer(tc.value)
|
||||
if (err == nil) != tc.valid {
|
||||
t.Fatalf("validateNtfyServer(%q) error = %v, valid = %v", tc.value, err, tc.valid)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoalAtRisk(t *testing.T) {
|
||||
if !goalAtRisk(summary.GoalResult{Goal: store.Goal{Op: ">=", TargetS: 100}, ActualS: 49}, 0.5) {
|
||||
t.Error("goal below elapsed-day pace should be at risk")
|
||||
}
|
||||
if goalAtRisk(summary.GoalResult{Goal: store.Goal{Op: ">=", TargetS: 100}, ActualS: 50}, 0.5) {
|
||||
t.Error("goal on elapsed-day pace should not be at risk")
|
||||
}
|
||||
if !goalAtRisk(summary.GoalResult{Goal: store.Goal{Op: "<=", TargetS: 100}, ActualS: 101}, 0.1) {
|
||||
t.Error("over-limit goal should be at risk")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE goal_notifications (
|
||||
goal_id bigint NOT NULL REFERENCES goals (id) ON DELETE CASCADE,
|
||||
notification_date date NOT NULL,
|
||||
sent_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (goal_id, notification_date)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE goal_notifications;
|
||||
@@ -39,6 +39,14 @@ type Device struct {
|
||||
RevokedAt *time.Time `json:"revoked_at"`
|
||||
}
|
||||
|
||||
// CollectorHealth is the device status and all-time ingestion counters used by
|
||||
// the admin health view.
|
||||
type CollectorHealth struct {
|
||||
Device Device
|
||||
ActivityCount int64
|
||||
SampleCount int64
|
||||
}
|
||||
|
||||
// HashKey returns the stored representation of an API key.
|
||||
func HashKey(key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
@@ -76,6 +84,23 @@ func (s *Store) ListDevices(ctx context.Context) ([]Device, error) {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Store) CollectorHealth(ctx context.Context) ([]CollectorHealth, error) {
|
||||
rows, err := s.pool.Query(ctx, `SELECT d.id, d.name, d.kind, d.created_at,
|
||||
d.last_seen_at, d.revoked_at,
|
||||
(SELECT count(*) FROM activities a WHERE a.device_id = d.id),
|
||||
(SELECT count(*) FROM samples sm WHERE sm.device_id = d.id)
|
||||
FROM devices d ORDER BY d.id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pgx.CollectRows(rows, func(r pgx.CollectableRow) (CollectorHealth, error) {
|
||||
var h CollectorHealth
|
||||
err := r.Scan(&h.Device.ID, &h.Device.Name, &h.Device.Kind, &h.Device.CreatedAt,
|
||||
&h.Device.LastSeenAt, &h.Device.RevokedAt, &h.ActivityCount, &h.SampleCount)
|
||||
return h, err
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Store) RevokeDevice(ctx context.Context, name string) error {
|
||||
tag, err := s.pool.Exec(ctx,
|
||||
`UPDATE devices SET revoked_at = now() WHERE name = $1 AND revoked_at IS NULL`, name)
|
||||
@@ -549,6 +574,20 @@ func (s *Store) UpdateNotificationSettings(ctx context.Context, settings Notific
|
||||
return settings, err
|
||||
}
|
||||
|
||||
func (s *Store) GoalNotificationSent(ctx context.Context, goalID int64, date time.Time) (bool, error) {
|
||||
var sent bool
|
||||
err := s.pool.QueryRow(ctx, `SELECT EXISTS (
|
||||
SELECT 1 FROM goal_notifications WHERE goal_id = $1 AND notification_date = $2::date
|
||||
)`, goalID, date.Format(time.DateOnly)).Scan(&sent)
|
||||
return sent, err
|
||||
}
|
||||
|
||||
func (s *Store) RecordGoalNotification(ctx context.Context, goalID int64, date time.Time) error {
|
||||
_, err := s.pool.Exec(ctx, `INSERT INTO goal_notifications (goal_id, notification_date)
|
||||
VALUES ($1, $2::date) ON CONFLICT (goal_id, notification_date) DO NOTHING`, goalID, date.Format(time.DateOnly))
|
||||
return err
|
||||
}
|
||||
|
||||
// PurgeBefore applies the privacy retention policy to all user data tables.
|
||||
func (s *Store) PurgeBefore(ctx context.Context, before time.Time) (int64, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
|
||||
Reference in New Issue
Block a user