diff --git a/README.md b/README.md index 2f37279..992d995 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,8 @@ Collectors never use the site login. Each one sends its own bearer key. | GET, POST | `/api/v1/reports` | admin | list or store nightly/weekly report output (`period_start`, `period_end`, `model`, `prompt_hash`, `body`) | | GET | `/api/v1/notifications/status` | admin | ntfy configuration and whether nudges are configured | | PUT | `/api/v1/notifications/config` | admin | set ntfy server/topic, enabled flag, and optional retention days | +| POST | `/api/v1/notifications/goals/check` | admin | evaluate today's goals and send ntfy alerts for unmet goals behind pace | +| GET | `/api/v1/health/collectors` | admin | collector last-seen age/status and activity/sample ingestion counts | | POST | `/api/v1/privacy/purge?before=RFC3339` | admin | permanently delete old activities, samples, and reports | | GET | `/`, `/setup` | admin | the dashboard app | | GET | `/tracker.user.js`, `/assets/*`, `/healthz`, `/readyz` | none | the userscript and the app's scripts hold no secrets | diff --git a/internal/api/api.go b/internal/api/api.go index 3b1351f..61c2253 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -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 == "" { diff --git a/internal/api/api_test.go b/internal/api/api_test.go index 2295c68..d94e589 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -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:pass@ntfy.example", 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") + } +} diff --git a/internal/migrations/00005_goal_notifications.sql b/internal/migrations/00005_goal_notifications.sql new file mode 100644 index 0000000..81fcb7b --- /dev/null +++ b/internal/migrations/00005_goal_notifications.sql @@ -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; diff --git a/internal/store/store.go b/internal/store/store.go index 20a2581..b7365a9 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -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) diff --git a/web/src/api.ts b/web/src/api.ts index 9066e2d..e40d474 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -48,6 +48,18 @@ export interface NotificationSettings { retention_days: number; updated_at?: string; } +export interface CollectorHealth { + id: number; name: string; kind: string; + last_seen: string | null; age_s: number | null; + status: "healthy" | "stale" | "never_seen" | "revoked"; + activity_count: number; sample_count: number; +} + +export interface GoalNotificationResult { + date: string; evaluated: number; at_risk: number; sent: number; + configured: boolean; errors: string[]; +} + export function dur(s: number): string { s = Math.round(s); const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60); diff --git a/web/src/style.css b/web/src/style.css index a04bdc7..4c3b1ef 100644 --- a/web/src/style.css +++ b/web/src/style.css @@ -104,6 +104,8 @@ li { margin:6px 0; } .data-actions { margin:10px 0 14px; } .privacy-tools { border-top:1px solid var(--line); margin-top:16px; padding-top:12px; } .privacy-tools h3 { margin-top:0; } +.notification-check { border-top:1px solid var(--line); margin-top:16px; padding-top:4px; } +.notification-check h3 { margin-bottom:2px; } .report-list { border-top:1px solid var(--line); margin-top:16px; padding-top:12px; } .report { border-bottom:1px solid var(--line); padding:8px 0; } .report:last-child { border-bottom:0; } diff --git a/web/src/views/Setup.vue b/web/src/views/Setup.vue index 28f4846..48b3d20 100644 --- a/web/src/views/Setup.vue +++ b/web/src/views/Setup.vue @@ -1,7 +1,7 @@