Add goal notifications and collector health
Test and publish / test (push) Successful in 1m40s
Test and publish / publish (push) Successful in 3m45s

This commit is contained in:
2026-10-23 20:45:51 +01:00
parent 667091efb0
commit 453cef40af
8 changed files with 375 additions and 3 deletions
+2
View File
@@ -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 |
+168
View File
@@ -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 == "" {
+70 -1
View File
@@ -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
View File
@@ -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)
+12
View File
@@ -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);
+2
View File
@@ -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; }
+72 -2
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { api, type AdminGoal, type Device, type NotificationSettings, type Report } from "../api";
import { api, type AdminGoal, type CollectorHealth, type Device, type GoalNotificationResult, type NotificationSettings, type Report } from "../api";
import CodeBlock from "../components/CodeBlock.vue";
import Collector from "../components/Collector.vue";
import KeyBox from "../components/KeyBox.vue";
@@ -25,6 +25,13 @@ const reports = ref<Report[]>([]);
const notifications = reactive<NotificationSettings>({ ntfy_server: "https://ntfy.sh", ntfy_topic: "", enabled: false, retention_days: 0 });
const purgeBefore = ref(new Date(Date.now() - 90 * 86400000).toISOString().slice(0, 10));
const privacyBusy = ref(false);
const collectorHealth = ref<CollectorHealth[]>([]);
const collectorHealthLoaded = ref(false);
const collectorHealthBusy = ref(false);
const collectorHealthError = ref("");
const notificationCheckBusy = ref(false);
const notificationCheck = ref<GoalNotificationResult | null>(null);
const notificationCheckError = ref("");
// Which collector sections are open: the browser's by default, and the one a
// #section in the URL names.
@@ -93,16 +100,50 @@ async function loadGoals() {
}
async function loadAdminData() {
try {
const [notification, reportList] = await Promise.all([
const [notification, reportList, health] = await Promise.all([
api<{ settings: NotificationSettings }>("GET", "notifications/status"),
api<{ reports: Report[] }>("GET", "reports"),
api<{ collectors: CollectorHealth[] }>("GET", "health/collectors"),
]);
Object.assign(notifications, notification.settings);
reports.value = reportList.reports;
collectorHealth.value = health.collectors;
collectorHealthLoaded.value = true;
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
}
onMounted(() => { loadDevices(); loadGoals(); loadAdminData(); });
function healthStatus(health: CollectorHealth) {
return health.status === "healthy" ? { label: "Healthy", cls: "good" }
: health.status === "stale" ? { label: "Stale", cls: "warn" }
: health.status === "never_seen" ? { label: "Never seen", cls: "warn" }
: { label: "Revoked", cls: "bad" };
}
function healthAge(seconds: number | null) {
return seconds === null ? "never" : ago(new Date(Date.now() - seconds * 1000).toISOString());
}
async function refreshCollectorHealth() {
collectorHealthBusy.value = true;
collectorHealthError.value = "";
try {
collectorHealth.value = (await api<{ collectors: CollectorHealth[] }>("GET", "health/collectors")).collectors;
collectorHealthLoaded.value = true;
} catch (e) { collectorHealthError.value = (e as Error).message; }
finally { collectorHealthBusy.value = false; }
}
async function checkGoalNotifications() {
notificationCheckBusy.value = true;
notificationCheckError.value = "";
notificationCheck.value = null;
try {
notificationCheck.value = await api<GoalNotificationResult>("POST", "notifications/goals/check");
} catch (e) { notificationCheckError.value = (e as Error).message; }
finally { notificationCheckBusy.value = false; }
}
// A readable name that isn't taken yet (names stay taken after revoking).
function suggestName(kind: string) {
let stem = ({ location: "iphone", manual: "script" } as Record<string, string>)[kind] || kind;
@@ -399,6 +440,14 @@ docker exec activity-tracker tracker goal list
<label>Retention days <span class="muted">(0 = keep forever)</span><input v-model.number="notifications.retention_days" type="number" min="0"></label>
<button class="primary" :disabled="privacyBusy">Save settings</button>
</form>
<div class="notification-check">
<div class="row spread"><div><h3>Check goal risks</h3><p class="muted small-text">Evaluate today's goals now and send notifications for goals behind pace.</p></div><button class="primary" :disabled="notificationCheckBusy" @click="checkGoalNotifications">{{ notificationCheckBusy ? "Checking…" : "Check and send" }}</button></div>
<p v-if="notificationCheckError" class="small-text err" role="alert">{{ notificationCheckError }}</p>
<p v-else-if="notificationCheck" class="small-text ok" role="status" aria-live="polite">
Checked {{ notificationCheck.evaluated }} goal{{ notificationCheck.evaluated === 1 ? "" : "s" }}: {{ notificationCheck.at_risk }} at risk, {{ notificationCheck.sent }} notification{{ notificationCheck.sent === 1 ? "" : "s" }} sent{{ notificationCheck.configured ? "" : " (notifications are not configured)" }}.
<span v-if="notificationCheck.errors.length" class="err"> {{ notificationCheck.errors.join(" ") }}</span>
</p>
</div>
<div class="privacy-tools">
<h3>Delete old records</h3>
<p class="muted small-text">This permanently deletes activities, samples, and reports before the selected date.</p>
@@ -415,4 +464,25 @@ docker exec activity-tracker tracker goal list
</article>
</div>
</section>
<section class="card" aria-labelledby="collector-health-title">
<div class="row spread"><h2 id="collector-health-title">Collector health</h2><div class="row"><span class="badge">Admin only</span><button class="small" :disabled="collectorHealthBusy" @click="refreshCollectorHealth">{{ collectorHealthBusy ? "Refreshing…" : "Refresh" }}</button></div></div>
<p class="muted small-text">Last upload and all-time ingestion counts for each collector.</p>
<p v-if="collectorHealthError" class="small-text err" role="alert">{{ collectorHealthError }}</p>
<div class="tablewrap"><table>
<caption class="sr-only">Collector health and ingestion counts</caption>
<thead><tr><th scope="col">Name</th><th scope="col">Health</th><th scope="col">Last upload</th><th scope="col">Activities</th><th scope="col">Samples</th></tr></thead>
<tbody v-if="!collectorHealthLoaded"><tr><td colspan="5" class="muted">Loading…</td></tr></tbody>
<tbody v-else>
<tr v-for="collector in collectorHealth" :key="collector.id">
<td class="label">{{ collector.name }} <span class="badge">{{ collector.kind }}</span></td>
<td><span class="status-dot" :class="healthStatus(collector).cls"></span>{{ healthStatus(collector).label }}</td>
<td class="time">{{ healthAge(collector.age_s) }}</td>
<td class="num">{{ collector.activity_count }}</td>
<td class="num">{{ collector.sample_count }}</td>
</tr>
<tr v-if="!collectorHealth.length"><td colspan="5" class="muted">No collectors registered.</td></tr>
</tbody>
</table></div>
</section>
</template>