Files
ccp/internal/api/api.go
T
adamf 453cef40af
Test and publish / test (push) Successful in 1m40s
Test and publish / publish (push) Successful in 3m45s
Add goal notifications and collector health
2026-10-23 20:45:51 +01:00

919 lines
29 KiB
Go

// Package api exposes the HTTP ingest and query endpoints.
package api
import (
"context"
"encoding/base64"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"math"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5/pgconn"
"ccp/internal/auth"
"ccp/internal/ingest"
"ccp/internal/store"
"ccp/internal/summary"
"ccp/internal/web"
)
const maxEventBody = 5 << 20 // 5 MiB
type Server struct {
store *store.Store
admin auth.Checker
loc *time.Location
log *slog.Logger
now func() time.Time
}
// New builds the HTTP handler. Collectors authenticate with per-device bearer
// keys; the dashboard pages and the routes behind them need the main site's
// admin session, which admin checks.
func New(s *store.Store, admin auth.Checker, loc *time.Location, log *slog.Logger) http.Handler {
srv := &Server{store: s, admin: admin, loc: loc, log: log, now: time.Now}
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
mux.HandleFunc("GET /readyz", srv.ready)
mux.HandleFunc("GET /tracker.user.js", web.UserScript)
mux.Handle("GET /assets/", web.Assets())
// The Vue app's routes; it sends visitors between them itself.
mux.Handle("GET /{$}", srv.adminPage(http.HandlerFunc(web.App)))
mux.Handle("GET /setup", srv.adminPage(http.HandlerFunc(web.App)))
api := http.NewServeMux()
api.Handle("POST /desktop/events", srv.device(srv.ingestEvents(ingest.Desktop)))
api.Handle("POST /browser/events", srv.device(srv.ingestEvents(ingest.Browser)))
api.Handle("POST /presence/events", srv.device(srv.ingestEvents(ingest.Presence)))
api.Handle("POST /manual/events", srv.device(srv.ingestEvents(ingest.Manual)))
api.Handle("POST /samples", srv.device(http.HandlerFunc(srv.ingestSamples)))
api.Handle("POST /samples/events", srv.device(http.HandlerFunc(srv.ingestSamples)))
api.Handle("GET /samples", srv.deviceOrAdmin(http.HandlerFunc(srv.samples)))
api.Handle("POST /location/{event}", srv.device(http.HandlerFunc(srv.ingestLocation)))
api.Handle("POST /location/{event}/{place}", srv.device(http.HandlerFunc(srv.ingestLocation)))
api.Handle("GET /activities", srv.deviceOrAdmin(http.HandlerFunc(srv.activities)))
api.Handle("GET /activities/export", srv.adminAPI(http.HandlerFunc(srv.exportActivities)))
api.Handle("GET /summary/daily", srv.deviceOrAdmin(http.HandlerFunc(srv.dailySummary)))
api.Handle("GET /summary/range", srv.deviceOrAdmin(http.HandlerFunc(srv.rangeSummary)))
api.Handle("GET /goals", srv.adminAPI(http.HandlerFunc(srv.listGoals)))
api.Handle("POST /goals", srv.adminAPI(http.HandlerFunc(srv.createGoal)))
api.Handle("PUT /goals/{id}", srv.adminAPI(http.HandlerFunc(srv.updateGoal)))
api.Handle("DELETE /goals/{id}", srv.adminAPI(http.HandlerFunc(srv.deleteGoal)))
api.Handle("GET /devices", srv.adminAPI(http.HandlerFunc(srv.listDevices)))
api.Handle("POST /devices", srv.adminAPI(http.HandlerFunc(srv.createDevice)))
api.Handle("DELETE /devices/{name}", srv.adminAPI(http.HandlerFunc(srv.revokeDevice)))
api.Handle("GET /reports", srv.adminAPI(http.HandlerFunc(srv.listReports)))
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))
return srv.logRequests(mux)
}
// ---- middleware ----
type ctxKey struct{}
func deviceFrom(ctx context.Context) store.Device {
d, _ := ctx.Value(ctxKey{}).(store.Device)
return d
}
// device requires a collector's bearer key and records its device on the
// context, since ingested rows belong to a device.
func (s *Server) device(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || key == "" {
writeError(w, http.StatusUnauthorized, "missing bearer token")
return
}
dev, err := s.store.DeviceByKey(r.Context(), key)
if errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusUnauthorized, "invalid api key")
return
}
if err != nil {
s.internalError(w, r, err)
return
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, dev)))
})
}
// deviceOrAdmin admits a bearer key, or without one the site's admin session.
func (s *Server) deviceOrAdmin(next http.Handler) http.Handler {
withKey := s.device(next)
withSession := s.adminAPI(next)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "" {
withKey.ServeHTTP(w, r)
} else {
withSession.ServeHTTP(w, r)
}
})
}
func (s *Server) adminAPI(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !s.admin.IsAdmin(w, r) {
writeError(w, http.StatusUnauthorized, "admin access required")
return
}
next.ServeHTTP(w, r)
})
}
// adminPage sends visitors without the site's admin session to its login
// page, which returns them here afterwards. The redirect is made in the
// browser because only it knows the /tracker/ prefix nginx strips.
func (s *Server) adminPage(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !s.admin.IsAdmin(w, r) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusUnauthorized)
w.Write(web.LoginRedirect)
return
}
next.ServeHTTP(w, r)
})
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
func (s *Server) logRequests(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
if r.URL.Path == "/healthz" || r.URL.Path == "/readyz" {
return
}
s.log.Info("request", "method", r.Method, "path", r.URL.Path,
"status", rec.status, "duration", time.Since(start))
})
}
// ---- handlers ----
func (s *Server) ready(w http.ResponseWriter, r *http.Request) {
if err := s.store.Ping(r.Context()); err != nil {
writeError(w, http.StatusServiceUnavailable, "database unavailable")
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ready"})
}
type ingestResult struct {
Received int `json:"received"`
Inserted int64 `json:"inserted"`
}
func (s *Server) ingestEvents(spec ingest.Spec) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var b ingest.Batch
if !s.decode(w, r, maxEventBody, &b) {
return
}
acts, err := spec.Normalize(b, s.now())
if err != nil {
writeError(w, http.StatusUnprocessableEntity, err.Error())
return
}
n, err := s.store.InsertActivities(r.Context(), deviceFrom(r.Context()).ID, acts)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, ingestResult{Received: len(acts), Inserted: n})
}
}
type sampleRequest struct {
ID string `json:"id"`
Source string `json:"source"`
Metric string `json:"metric"`
TS time.Time `json:"ts"`
Value float64 `json:"value"`
Unit string `json:"unit"`
}
func (s *Server) ingestSamples(w http.ResponseWriter, r *http.Request) {
var req struct {
Samples []sampleRequest `json:"samples"`
}
if !s.decode(w, r, maxEventBody, &req) {
return
}
if len(req.Samples) == 0 || len(req.Samples) > ingest.MaxBatch {
writeError(w, http.StatusBadRequest, "samples must contain 1-1000 items")
return
}
samples := make([]store.Sample, 0, len(req.Samples))
for i, in := range req.Samples {
in.ID, in.Source, in.Metric, in.Unit = strings.TrimSpace(in.ID), strings.TrimSpace(in.Source), strings.TrimSpace(in.Metric), strings.TrimSpace(in.Unit)
if in.ID == "" || in.Source == "" || in.Metric == "" || in.TS.IsZero() || !isFinite(in.Value) {
writeError(w, http.StatusUnprocessableEntity, "sample "+strconv.Itoa(i)+" has invalid id, source, metric, ts, or value")
return
}
if in.TS.After(s.now().Add(5 * time.Minute)) {
writeError(w, http.StatusUnprocessableEntity, "sample timestamp is in the future")
return
}
samples = append(samples, store.Sample{ExternalID: in.ID, Source: in.Source, Metric: in.Metric, TS: in.TS.UTC(), Value: in.Value, Unit: in.Unit})
}
n, err := s.store.InsertSamples(r.Context(), deviceFrom(r.Context()).ID, samples)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"received": len(samples), "inserted": n})
}
func isFinite(v float64) bool { return !math.IsNaN(v) && !math.IsInf(v, 0) }
func (s *Server) samples(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
now := s.now()
f := store.SampleFilter{From: now.Add(-24 * time.Hour), To: now, Source: q.Get("source"), Metric: q.Get("metric"), Limit: 1000}
var err error
if v := q.Get("from"); v != "" {
if f.From, err = time.Parse(time.RFC3339, v); err != nil {
writeError(w, http.StatusBadRequest, "from must be RFC3339")
return
}
}
if v := q.Get("to"); v != "" {
if f.To, err = time.Parse(time.RFC3339, v); err != nil {
writeError(w, http.StatusBadRequest, "to must be RFC3339")
return
}
}
if v := q.Get("limit"); v != "" {
if f.Limit, err = strconv.Atoi(v); err != nil || f.Limit < 1 || f.Limit > 10000 {
writeError(w, http.StatusBadRequest, "limit must be 1-10000")
return
}
}
if v := q.Get("cursor"); v != "" {
var c activityCursor
b, decodeErr := base64.RawURLEncoding.DecodeString(v)
if decodeErr != nil || json.Unmarshal(b, &c) != nil || c.ID < 1 || c.StartedAt.IsZero() {
writeError(w, http.StatusBadRequest, "cursor is invalid")
return
}
f.After = &store.SampleCursor{TS: c.StartedAt, ID: c.ID}
}
items, next, err := s.store.SamplesPage(r.Context(), f)
if err != nil {
s.internalError(w, r, err)
return
}
out := map[string]any{"samples": items}
if next != nil {
out["next_cursor"] = encodeActivityCursor(activityCursor{StartedAt: next.TS, ID: next.ID})
}
writeJSON(w, http.StatusOK, out)
}
// ingestLocation takes an arrive or leave from a phone geofence automation.
// The place comes from the path (/arrive/gym), ?place=, the body's "place",
// or defaults to home. ingest.Destination decides where the device ends up.
func (s *Server) ingestLocation(w http.ResponseWriter, r *http.Request) {
event := r.PathValue("event")
if event != "arrive" && event != "leave" {
writeError(w, http.StatusNotFound, "event must be arrive or leave")
return
}
var e ingest.LocationEvent
r.Body = http.MaxBytesReader(w, r.Body, 4<<10)
if err := json.NewDecoder(r.Body).Decode(&e); err != nil && !errors.Is(err, io.EOF) {
writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
return
}
// A path or ?place= is easier to set up in Shortcuts than a JSON body.
if p := r.URL.Query().Get("place"); p != "" {
e.Place = p
}
if p := r.PathValue("place"); p != "" {
e.Place = p
}
e, err := ingest.NormalizeLocation(e, s.now())
if err != nil {
writeError(w, http.StatusUnprocessableEntity, err.Error())
return
}
place, changed, err := s.store.MoveTo(r.Context(), deviceFrom(r.Context()).ID, e.At,
func(cur string) string { return ingest.Destination(event, e.Place, cur) })
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"place": place, "changed": changed})
}
func (s *Server) activities(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
now := s.now()
f := store.ActivityFilter{
From: now.Add(-24 * time.Hour),
To: now,
Source: q.Get("source"),
Kind: q.Get("kind"),
Limit: 1000,
}
var err error
if v := q.Get("from"); v != "" {
if f.From, err = time.Parse(time.RFC3339, v); err != nil {
writeError(w, http.StatusBadRequest, "from must be RFC3339")
return
}
}
if v := q.Get("to"); v != "" {
if f.To, err = time.Parse(time.RFC3339, v); err != nil {
writeError(w, http.StatusBadRequest, "to must be RFC3339")
return
}
}
if v := q.Get("limit"); v != "" {
if f.Limit, err = strconv.Atoi(v); err != nil || f.Limit < 1 || f.Limit > 10000 {
writeError(w, http.StatusBadRequest, "limit must be 1-10000")
return
}
}
var cursor *store.ActivityCursor
if v := q.Get("cursor"); v != "" {
var payload activityCursor
decoded, decodeErr := base64.RawURLEncoding.DecodeString(v)
if decodeErr != nil || json.Unmarshal(decoded, &payload) != nil || payload.ID < 1 || payload.StartedAt.IsZero() {
writeError(w, http.StatusBadRequest, "cursor is invalid")
return
}
cursor = &store.ActivityCursor{StartedAt: payload.StartedAt, ID: payload.ID}
f.After = cursor
}
acts, next, err := s.store.ActivitiesPage(r.Context(), f)
if err != nil {
s.internalError(w, r, err)
return
}
out := map[string]any{"activities": acts}
if next != nil {
out["next_cursor"] = encodeActivityCursor(activityCursor{StartedAt: next.StartedAt, ID: next.ID})
}
writeJSON(w, http.StatusOK, out)
}
type activityCursor struct {
StartedAt time.Time `json:"started_at"`
ID int64 `json:"id"`
}
func encodeActivityCursor(c activityCursor) string {
b, _ := json.Marshal(c)
return base64.RawURLEncoding.EncodeToString(b)
}
func (s *Server) exportActivities(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
now := s.now()
f := store.ActivityFilter{From: now.Add(-24 * time.Hour), To: now, Source: q.Get("source"), Kind: q.Get("kind"), Limit: 10000}
var err error
if v := q.Get("from"); v != "" {
if f.From, err = time.Parse(time.RFC3339, v); err != nil {
writeError(w, http.StatusBadRequest, "from must be RFC3339")
return
}
}
if v := q.Get("to"); v != "" {
if f.To, err = time.Parse(time.RFC3339, v); err != nil {
writeError(w, http.StatusBadRequest, "to must be RFC3339")
return
}
}
var acts []store.StoredActivity
for {
page, next, pageErr := s.store.ActivitiesPage(r.Context(), f)
if pageErr != nil {
s.internalError(w, r, pageErr)
return
}
acts = append(acts, page...)
if next == nil {
break
}
f.After = next
}
if q.Get("format") == "json" {
w.Header().Set("Content-Disposition", "attachment; filename=activities.json")
writeJSON(w, http.StatusOK, map[string]any{"activities": acts})
return
}
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Header().Set("Content-Disposition", "attachment; filename=activities.csv")
cw := csv.NewWriter(w)
_ = cw.Write([]string{"id", "device", "source", "kind", "label", "started_at", "ended_at", "duration_s", "attrs"})
for _, a := range acts {
attrs, _ := json.Marshal(a.Attrs)
_ = cw.Write([]string{strconv.FormatInt(a.ID, 10), a.Device, a.Source, a.Kind, a.Label, a.StartedAt.Format(time.RFC3339Nano), a.EndedAt.Format(time.RFC3339Nano), strconv.Itoa(a.DurationS), string(attrs)})
}
cw.Flush()
}
func (s *Server) dailySummary(w http.ResponseWriter, r *http.Request) {
day := s.now().In(s.loc)
if v := r.URL.Query().Get("date"); v != "" {
var err error
if day, err = time.ParseInLocation(time.DateOnly, v, s.loc); err != nil {
writeError(w, http.StatusBadRequest, "date must be YYYY-MM-DD")
return
}
}
from, to := summary.DayBounds(day, 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
}
writeJSON(w, http.StatusOK, summary.Build(from.Format(time.DateOnly), from, to, totals, goals))
}
func (s *Server) rangeSummary(w http.ResponseWriter, r *http.Request) {
from, to, ok := s.parseRange(w, r)
if !ok {
return
}
totals, err := s.store.Totals(r.Context(), from, to)
if err != nil {
s.internalError(w, r, err)
return
}
samples, err := s.store.SampleSummary(r.Context(), from, to)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"from": from, "to": to, "totals": totals, "samples": samples})
}
func (s *Server) parseRange(w http.ResponseWriter, r *http.Request) (time.Time, time.Time, bool) {
now := s.now()
from, to := now.Add(-24*time.Hour), now
var err error
if v := r.URL.Query().Get("from"); v != "" {
from, err = time.Parse(time.RFC3339, v)
if err != nil {
writeError(w, http.StatusBadRequest, "from must be RFC3339")
return time.Time{}, time.Time{}, false
}
}
if v := r.URL.Query().Get("to"); v != "" {
to, err = time.Parse(time.RFC3339, v)
if err != nil {
writeError(w, http.StatusBadRequest, "to must be RFC3339")
return time.Time{}, time.Time{}, false
}
}
if !from.Before(to) {
writeError(w, http.StatusBadRequest, "from must be before to")
return time.Time{}, time.Time{}, false
}
return from, to, true
}
func (s *Server) listReports(w http.ResponseWriter, r *http.Request) {
reports, err := s.store.Reports(r.Context())
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"reports": reports})
}
func (s *Server) createReport(w http.ResponseWriter, r *http.Request) {
var report store.Report
if !s.decode(w, r, 1<<20, &report) {
return
}
if report.PeriodStart.IsZero() || report.PeriodEnd.IsZero() || !report.PeriodStart.Before(report.PeriodEnd) || strings.TrimSpace(report.Model) == "" || report.Body == "" {
writeError(w, http.StatusBadRequest, "period_start, period_end, model, and body are required")
return
}
report.Model, report.PromptHash = strings.TrimSpace(report.Model), strings.TrimSpace(report.PromptHash)
created, err := s.store.CreateReport(r.Context(), report)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusCreated, created)
}
func (s *Server) notificationStatus(w http.ResponseWriter, r *http.Request) {
settings, err := s.store.NotificationSettings(r.Context())
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"configured": settings.Enabled && settings.NtfyTopic != "", "settings": settings})
}
func (s *Server) updateNotificationConfig(w http.ResponseWriter, r *http.Request) {
var settings store.NotificationSettings
if !s.decode(w, r, 16<<10, &settings) {
return
}
settings.NtfyServer, settings.NtfyTopic = strings.TrimRight(strings.TrimSpace(settings.NtfyServer), "/"), strings.TrimSpace(settings.NtfyTopic)
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
}
updated, err := s.store.UpdateNotificationSettings(r.Context(), settings)
if err != nil {
s.internalError(w, r, err)
return
}
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 == "" {
writeError(w, http.StatusBadRequest, "before must be RFC3339")
return
}
before, err := time.Parse(time.RFC3339, cutoff)
if err != nil {
writeError(w, http.StatusBadRequest, "before must be RFC3339")
return
}
n, err := s.store.PurgeBefore(r.Context(), before)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"deleted": n, "before": before})
}
func (s *Server) listGoals(w http.ResponseWriter, r *http.Request) {
goals, err := s.store.Goals(r.Context())
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"goals": goals})
}
type goalRequest struct {
Kind string `json:"kind"`
Label string `json:"label"`
Op string `json:"op"`
TargetS int64 `json:"target_s"`
Period string `json:"period"`
}
func (s *Server) decodeGoal(w http.ResponseWriter, r *http.Request) (store.Goal, bool) {
var req goalRequest
if !s.decode(w, r, 4<<10, &req) {
return store.Goal{}, false
}
req.Kind, req.Label, req.Op, req.Period = strings.TrimSpace(req.Kind), strings.TrimSpace(req.Label), strings.TrimSpace(req.Op), strings.TrimSpace(req.Period)
if req.Kind == "" || (req.Op != ">=" && req.Op != "<=") || req.TargetS < 0 || (req.Period != "" && req.Period != "day") {
writeError(w, http.StatusBadRequest, "kind, op (>= or <=), target_s >= 0, and period=day are required")
return store.Goal{}, false
}
return store.Goal{Kind: req.Kind, Label: req.Label, Op: req.Op, TargetS: req.TargetS}, true
}
func (s *Server) createGoal(w http.ResponseWriter, r *http.Request) {
goal, ok := s.decodeGoal(w, r)
if !ok {
return
}
goal, err := s.store.CreateGoal(r.Context(), goal)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusCreated, goal)
}
func (s *Server) updateGoal(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || id < 1 {
writeError(w, http.StatusBadRequest, "id must be a positive integer")
return
}
goal, ok := s.decodeGoal(w, r)
if !ok {
return
}
goal.ID = id
goal, err = s.store.UpdateGoal(r.Context(), goal)
if errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusNotFound, "goal not found")
return
}
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, goal)
}
func (s *Server) deleteGoal(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || id < 1 {
writeError(w, http.StatusBadRequest, "id must be a positive integer")
return
}
if err := s.store.DeleteGoal(r.Context(), id); errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusNotFound, "goal not found")
return
} else if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
}
func (s *Server) listDevices(w http.ResponseWriter, r *http.Request) {
devs, err := s.store.ListDevices(r.Context())
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"devices": devs})
}
// createDevice registers a collector and returns its API key, the only time
// the key is ever shown.
func (s *Server) createDevice(w http.ResponseWriter, r *http.Request) {
var req struct {
Name string `json:"name"`
Kind string `json:"kind"`
}
if !s.decode(w, r, 4<<10, &req) {
return
}
req.Name, req.Kind = strings.TrimSpace(req.Name), strings.TrimSpace(req.Kind)
if req.Name == "" || req.Kind == "" {
writeError(w, http.StatusBadRequest, "name and kind are required")
return
}
dev, key, err := s.store.CreateDevice(r.Context(), req.Name, req.Kind)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
writeError(w, http.StatusConflict, "a device with that name already exists")
return
}
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"device": dev, "key": key})
}
func (s *Server) revokeDevice(w http.ResponseWriter, r *http.Request) {
err := s.store.RevokeDevice(r.Context(), r.PathValue("name"))
if errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusNotFound, "no active device with that name")
return
}
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "revoked"})
}
// ---- helpers ----
func (s *Server) decode(w http.ResponseWriter, r *http.Request, limit int64, v any) bool {
r.Body = http.MaxBytesReader(w, r.Body, limit)
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
writeError(w, http.StatusRequestEntityTooLarge, "request body too large")
} else {
writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
}
return false
}
return true
}
func (s *Server) internalError(w http.ResponseWriter, r *http.Request, err error) {
s.log.Error("request failed", "path", r.URL.Path, "err", err)
writeError(w, http.StatusInternalServerError, "internal error")
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}