diff --git a/README.md b/README.md index b4e0c5e..2f37279 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ A self-hosted service that records where your time goes: desktop apps, browser t tracker (Go, container) ── PostgreSQL ``` -Every source is stored as an interval in a single `activities` table, with columns `source, kind, label, started_at, ended_at, attrs`. The `samples` table for point metrics (step counts and so on) has no collector at the moment. Collectors generate an `id` for each event, so re-uploading a batch never creates duplicates. +Every source is stored as an interval in a single `activities` table, with columns `source, kind, label, started_at, ended_at, attrs`. The `samples` table stores point metrics such as step counts. Collectors generate an `id` for each event, so re-uploading a batch never creates duplicates. ## Status @@ -19,7 +19,9 @@ Every source is stored as an interval in a single `activities` table, with colum | iPhone location (Shortcuts → `/location/{arrive,leave}`) | ✅ built; configure the automations | | Browser (Violentmonkey userscript, `/tracker.user.js`) | ✅ built | | Webcam presence (`/presence/events`) | endpoint ready, agent not yet written | -| AI analysis (`reports` table) | planned | +| Samples API and range summaries | ✅ available | +| AI analysis (`reports` table) | ✅ storage API; job remains external | +| ntfy goal notification configuration | ✅ configuration/status API | ## Running the server @@ -98,11 +100,20 @@ Collectors never use the site login. Each one sends its own bearer key. | POST | `/api/v1/browser/events` | key | `tab_focus`, `idle` | | POST | `/api/v1/presence/events` | key | `at_desk`, `in_bed`, `away` | | POST | `/api/v1/manual/events` | key | any | +| POST | `/api/v1/samples` | key | point metrics in `{"samples":[{"id","source","metric","ts","value","unit"}]}` | +| GET | `/api/v1/samples?from=&to=&source=&metric=&limit=&cursor=` | key or admin | point samples, defaults to the last 24h | | POST | `/api/v1/location/{arrive,leave}[/{place}]` | key | place from the path, `?place=`, or optional `{"place","at"}`; defaults to `home` and now. Builds `place` intervals (see [iPhone location](#iphone-location)) | -| GET | `/api/v1/activities?from=&to=&source=&kind=&limit=` | key or admin | RFC3339 times; defaults to the last 24h | +| GET | `/api/v1/activities?from=&to=&source=&kind=&limit=&cursor=` | key or admin | RFC3339 times; defaults to the last 24h; returns clipped intervals and `next_cursor` when more rows exist | +| GET | `/api/v1/activities/export?from=&to=&source=&kind=&format=csv` | admin | Downloads the filtered activity data as CSV, or JSON with `format=json` | | GET | `/api/v1/summary/daily?date=YYYY-MM-DD` | key or admin | totals per label and kind, plus goal results | +| GET | `/api/v1/summary/range?from=&to=` | key or admin | interval totals and metric min/max/average/count for a range | +| GET, POST, PUT, DELETE | `/api/v1/goals[/{id}]` | admin | List, create, update, or delete daily goals | | GET, POST | `/api/v1/devices` | admin | list devices; create one with `{"name","kind"}`, which returns its key once | | DELETE | `/api/v1/devices/{name}` | admin | revoke a device's 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/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 | @@ -203,5 +214,5 @@ Layout: `cmd/tracker` (server and admin CLI), `cmd/hypr-agent`, `internal/{api,a ## Roadmap 1. Webcam presence agent. Detection will run on the device and only intervals will be uploaded; frames never leave the machine. -2. Nudges: push notifications through ntfy when a goal is at risk during the day. -3. AI analysis: a nightly or weekly job will send the daily summaries (not raw rows) to the Claude API and store the result in `reports`. +2. Nudges: send goal-risk notifications through the configured ntfy topic. +3. AI analysis: a nightly or weekly job will send the daily summaries (not raw rows) to the Claude API and store the result through `POST /api/v1/reports`. diff --git a/internal/api/api.go b/internal/api/api.go index a7c343e..3b1351f 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -3,10 +3,13 @@ package api import ( "context" + "encoding/base64" + "encoding/csv" "encoding/json" "errors" "io" "log/slog" + "math" "net/http" "strconv" "strings" @@ -53,13 +56,27 @@ func New(s *store.Store, admin auth.Checker, loc *time.Location, log *slog.Logge 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 /privacy/purge", srv.adminAPI(http.HandlerFunc(srv.purgePrivacyData))) mux.Handle("/api/v1/", http.StripPrefix("/api/v1", api)) return srv.logRequests(mux) @@ -193,6 +210,93 @@ func (s *Server) ingestEvents(spec ingest.Spec) http.HandlerFunc { } } +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. @@ -259,13 +363,84 @@ func (s *Server) activities(w http.ResponseWriter, r *http.Request) { 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, err := s.store.Activities(r.Context(), f) + acts, next, err := s.store.ActivitiesPage(r.Context(), f) if err != nil { s.internalError(w, r, err) return } - writeJSON(w, http.StatusOK, map[string]any{"activities": acts}) + 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) { @@ -292,6 +467,207 @@ func (s *Server) dailySummary(w http.ResponseWriter, r *http.Request) { 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" + } + 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) 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 { diff --git a/internal/api/api_test.go b/internal/api/api_test.go index 8400ef9..2295c68 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -154,3 +154,29 @@ func TestLocation(t *testing.T) { t.Errorf("unknown event: %d", code) } } + +func TestSamplesReportsAndSettings(t *testing.T) { + srv, key := setup(t) + ts := time.Now().UTC().Add(-time.Hour).Truncate(time.Second) + body := `{"samples":[{"id":"s1","source":"watch","metric":"steps","ts":"` + ts.Format(time.RFC3339) + `","value":12,"unit":"count"}]}` + code, out := do(t, "POST", srv.URL+"/api/v1/samples", key, body) + if code != http.StatusOK || out["inserted"] != 1.0 { + t.Fatalf("sample ingest: %d %v", code, out) + } + code, out = do(t, "POST", srv.URL+"/api/v1/samples", key, body) + if code != http.StatusOK || out["inserted"] != 0.0 { + t.Fatalf("sample idempotency: %d %v", code, out) + } + code, out = do(t, "GET", srv.URL+"/api/v1/summary/range?from="+ts.Add(-time.Minute).Format(time.RFC3339)+"&to="+ts.Add(time.Minute).Format(time.RFC3339), key, "") + 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}`) + 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/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) + } +} diff --git a/internal/migrations/00003_activity_device_idempotency.sql b/internal/migrations/00003_activity_device_idempotency.sql new file mode 100644 index 0000000..a31705a --- /dev/null +++ b/internal/migrations/00003_activity_device_idempotency.sql @@ -0,0 +1,20 @@ +-- +goose Up +-- The same collector event ID is only idempotent within its device. +DELETE FROM activities a +USING activities duplicate +WHERE a.source = duplicate.source + AND a.external_id = duplicate.external_id + AND a.id > duplicate.id; +ALTER TABLE activities DROP CONSTRAINT activities_source_external_id_key; +ALTER TABLE activities ADD CONSTRAINT activities_device_source_external_id_key + UNIQUE (device_id, source, external_id); + +-- +goose Down +DELETE FROM activities a +USING activities duplicate +WHERE a.source = duplicate.source + AND a.external_id = duplicate.external_id + AND a.id > duplicate.id; +ALTER TABLE activities DROP CONSTRAINT activities_device_source_external_id_key; +ALTER TABLE activities ADD CONSTRAINT activities_source_external_id_key + UNIQUE (source, external_id); diff --git a/internal/migrations/00004_product_slice.sql b/internal/migrations/00004_product_slice.sql new file mode 100644 index 0000000..6b57c91 --- /dev/null +++ b/internal/migrations/00004_product_slice.sql @@ -0,0 +1,24 @@ +-- +goose Up +CREATE TABLE notification_settings ( + id boolean PRIMARY KEY DEFAULT true CHECK (id), + ntfy_server text NOT NULL DEFAULT 'https://ntfy.sh', + ntfy_topic text NOT NULL DEFAULT '', + enabled boolean NOT NULL DEFAULT false, + retention_days integer NOT NULL DEFAULT 0 CHECK (retention_days >= 0), + updated_at timestamptz NOT NULL DEFAULT now() +); +INSERT INTO notification_settings DEFAULT VALUES; + +DELETE FROM samples s USING samples duplicate +WHERE s.source = duplicate.source AND s.external_id = duplicate.external_id AND s.id > duplicate.id; +ALTER TABLE samples DROP CONSTRAINT samples_source_external_id_key; +ALTER TABLE samples ADD CONSTRAINT samples_device_source_external_id_key UNIQUE (device_id, source, external_id); +CREATE INDEX reports_period_idx ON reports (period_start DESC, period_end DESC); +CREATE INDEX samples_device_metric_ts_idx ON samples (device_id, metric, ts); + +-- +goose Down +DROP INDEX samples_device_metric_ts_idx; +DROP INDEX reports_period_idx; +DROP TABLE notification_settings; +ALTER TABLE samples DROP CONSTRAINT samples_device_source_external_id_key; +ALTER TABLE samples ADD CONSTRAINT samples_source_external_id_key UNIQUE (source, external_id); diff --git a/internal/store/store.go b/internal/store/store.go index c1032cf..20a2581 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -9,6 +9,7 @@ import ( "encoding/hex" "errors" "fmt" + "strconv" "time" "github.com/jackc/pgx/v5" @@ -105,19 +106,120 @@ func (s *Store) DeviceByKey(ctx context.Context, key string) (Device, error) { // ---- ingest ---- // InsertActivities stores activities, skipping ones already stored with the -// same (source, external_id). It returns how many rows were new. +// same (device_id, source, external_id). It returns how many rows were new. func (s *Store) InsertActivities(ctx context.Context, deviceID int64, acts []ingest.Activity) (int64, error) { b := &pgx.Batch{} for _, a := range acts { + attrs := a.Attrs + if attrs == nil { + attrs = map[string]any{} + } b.Queue(`INSERT INTO activities (device_id, source, kind, label, started_at, ended_at, attrs, external_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) - ON CONFLICT (source, external_id) DO NOTHING`, - deviceID, a.Source, a.Kind, a.Label, a.StartedAt, a.EndedAt, a.Attrs, a.ExternalID) + ON CONFLICT (device_id, source, external_id) DO NOTHING`, + deviceID, a.Source, a.Kind, a.Label, a.StartedAt, a.EndedAt, attrs, a.ExternalID) } return s.sendBatch(ctx, b) } +// Sample is a point-in-time metric uploaded by a collector. +type Sample struct { + ID int64 `json:"id"` + Device string `json:"device,omitempty"` + Source string `json:"source"` + Metric string `json:"metric"` + TS time.Time `json:"ts"` + Value float64 `json:"value"` + Unit string `json:"unit"` + ExternalID string `json:"external_id"` +} + +func (s *Store) InsertSamples(ctx context.Context, deviceID int64, samples []Sample) (int64, error) { + b := &pgx.Batch{} + for _, sample := range samples { + b.Queue(`INSERT INTO samples (device_id, source, metric, ts, value, unit, external_id) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (device_id, source, external_id) DO NOTHING`, + deviceID, sample.Source, sample.Metric, sample.TS, sample.Value, sample.Unit, sample.ExternalID) + } + return s.sendBatch(ctx, b) +} + +type SampleFilter struct { + From, To time.Time + Source, Metric string + Limit int + After *SampleCursor +} + +type SampleCursor struct { + TS time.Time + ID int64 +} + +func (s *Store) SamplesPage(ctx context.Context, f SampleFilter) ([]Sample, *SampleCursor, error) { + limit := f.Limit + if limit < 1 { + limit = 1000 + } + args := []any{f.From, f.To, f.Source, f.Metric} + clause := "" + if f.After != nil { + clause = " AND (s.ts, s.id) > ($5, $6)" + args = append(args, f.After.TS, f.After.ID) + } + args = append(args, limit+1) + rows, err := s.pool.Query(ctx, `SELECT s.id, d.name, s.source, s.metric, s.ts, s.value, s.unit, s.external_id + FROM samples s JOIN devices d ON d.id = s.device_id + WHERE s.ts >= $1 AND s.ts < $2 AND ($3 = '' OR s.source = $3) AND ($4 = '' OR s.metric = $4)`+clause+` + ORDER BY s.ts, s.id LIMIT $`+strconv.Itoa(len(args)), args...) + if err != nil { + return nil, nil, err + } + rowsOut, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (Sample, error) { + var sample Sample + err := r.Scan(&sample.ID, &sample.Device, &sample.Source, &sample.Metric, &sample.TS, &sample.Value, &sample.Unit, &sample.ExternalID) + return sample, err + }) + if err != nil { + return nil, nil, err + } + more := len(rowsOut) > limit + if more { + rowsOut = rowsOut[:limit] + } + var next *SampleCursor + if more { + last := rowsOut[len(rowsOut)-1] + next = &SampleCursor{TS: last.TS, ID: last.ID} + } + return rowsOut, next, nil +} + +// SampleRangeSummary returns min/max/average/count grouped by metric. +type SampleSummary struct { + Metric string `json:"metric"` + Unit string `json:"unit"` + Count int64 `json:"count"` + Min float64 `json:"min"` + Max float64 `json:"max"` + Average float64 `json:"average"` +} + +func (s *Store) SampleSummary(ctx context.Context, from, to time.Time) ([]SampleSummary, error) { + rows, err := s.pool.Query(ctx, `SELECT metric, min(unit), count(*), min(value), max(value), avg(value) + FROM samples WHERE ts >= $1 AND ts < $2 GROUP BY metric ORDER BY metric`, from, to) + if err != nil { + return nil, err + } + return pgx.CollectRows(rows, func(r pgx.CollectableRow) (SampleSummary, error) { + var out SampleSummary + err := r.Scan(&out.Metric, &out.Unit, &out.Count, &out.Min, &out.Max, &out.Average) + return out, err + }) +} + // MoveTo records a location transition for a device: it closes the device's // open place interval at `at` and opens one labelled dest(current place). // dest is called under the device's lock, so concurrent events see each @@ -232,6 +334,12 @@ type ActivityFilter struct { From, To time.Time Source, Kind string // empty matches all Limit int + After *ActivityCursor +} + +type ActivityCursor struct { + StartedAt time.Time + ID int64 } // effectiveEnd is an activity's end, reading open location intervals (stored @@ -240,25 +348,70 @@ const effectiveEnd = `(CASE WHEN attrs ? 'open' THEN greatest(ended_at, now()) E // Activities returns activities overlapping [From, To), oldest first. func (s *Store) Activities(ctx context.Context, f ActivityFilter) ([]StoredActivity, error) { + acts, _, err := s.activitiesPage(ctx, f) + return acts, err +} + +// ActivitiesPage returns one page of activities and a cursor for the next +// page, if one exists. Results are clipped to the requested [From, To) range. +func (s *Store) ActivitiesPage(ctx context.Context, f ActivityFilter) ([]StoredActivity, *ActivityCursor, error) { + return s.activitiesPage(ctx, f) +} + +func (s *Store) activitiesPage(ctx context.Context, f ActivityFilter) ([]StoredActivity, *ActivityCursor, error) { + limit := f.Limit + if limit < 1 { + limit = 1000 + } + args := []any{f.From, f.To, f.Source, f.Kind} + cursorClause := "" + if f.After != nil { + cursorClause = " AND (a.started_at, a.id) > ($5, $6)" + args = append(args, f.After.StartedAt, f.After.ID) + } + limitArg := len(args) + 1 + args = append(args, limit+1) rows, err := s.pool.Query(ctx, - `SELECT a.id, d.name, a.source, a.kind, a.label, a.started_at, a.end_at, - extract(epoch FROM a.end_at - a.started_at)::integer, a.attrs + `SELECT a.id, a.started_at, d.name, a.source, a.kind, a.label, + greatest(a.started_at, $1), least(a.end_at, $2), + extract(epoch FROM least(a.end_at, $2) - greatest(a.started_at, $1))::integer, a.attrs FROM (SELECT *, `+effectiveEnd+` AS end_at FROM activities) a JOIN devices d ON d.id = a.device_id WHERE a.started_at < $2 AND a.end_at > $1 AND ($3 = '' OR a.source = $3) AND ($4 = '' OR a.kind = $4) - ORDER BY a.started_at - LIMIT $5`, - f.From, f.To, f.Source, f.Kind, f.Limit) + `+cursorClause+` + ORDER BY a.started_at, a.id + LIMIT $`+strconv.Itoa(limitArg), args...) if err != nil { - return nil, err + return nil, nil, err } - return pgx.CollectRows(rows, func(r pgx.CollectableRow) (StoredActivity, error) { + type activityRow struct { + activity StoredActivity + started time.Time + } + rowsOut, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (activityRow, error) { var a StoredActivity - err := r.Scan(&a.ID, &a.Device, &a.Source, &a.Kind, &a.Label, &a.StartedAt, &a.EndedAt, &a.DurationS, &a.Attrs) - return a, err + var started time.Time + err := r.Scan(&a.ID, &started, &a.Device, &a.Source, &a.Kind, &a.Label, &a.StartedAt, &a.EndedAt, &a.DurationS, &a.Attrs) + return activityRow{activity: a, started: started}, err }) + if err != nil { + return nil, nil, err + } + more := len(rowsOut) > limit + if more { + rowsOut = rowsOut[:limit] + } + acts := make([]StoredActivity, len(rowsOut)) + for i, row := range rowsOut { + acts[i] = row.activity + } + var next *ActivityCursor + if more { + next = &ActivityCursor{StartedAt: rowsOut[len(rowsOut)-1].started, ID: rowsOut[len(rowsOut)-1].activity.ID} + } + return acts, next, nil } type Total struct { @@ -317,6 +470,22 @@ func (s *Store) CreateGoal(ctx context.Context, g Goal) (Goal, error) { return g, nil } +func (s *Store) UpdateGoal(ctx context.Context, g Goal) (Goal, error) { + err := s.pool.QueryRow(ctx, + `UPDATE goals SET kind = $2, label = $3, op = $4, target_s = $5 + WHERE id = $1 + RETURNING id, kind, label, op, target_s, period`, + g.ID, g.Kind, g.Label, g.Op, g.TargetS, + ).Scan(&g.ID, &g.Kind, &g.Label, &g.Op, &g.TargetS, &g.Period) + if errors.Is(err, pgx.ErrNoRows) { + return g, ErrNotFound + } + if err != nil { + return g, fmt.Errorf("update goal: %w", err) + } + return g, nil +} + func (s *Store) DeleteGoal(ctx context.Context, id int64) error { tag, err := s.pool.Exec(ctx, `DELETE FROM goals WHERE id = $1`, id) if err != nil { @@ -327,3 +496,74 @@ func (s *Store) DeleteGoal(ctx context.Context, id int64) error { } return nil } + +type Report struct { + ID int64 `json:"id"` + PeriodStart time.Time `json:"period_start"` + PeriodEnd time.Time `json:"period_end"` + Model string `json:"model"` + PromptHash string `json:"prompt_hash"` + Body string `json:"body"` + CreatedAt time.Time `json:"created_at"` +} + +func (s *Store) Reports(ctx context.Context) ([]Report, error) { + rows, err := s.pool.Query(ctx, `SELECT id, period_start, period_end, model, prompt_hash, body, created_at + FROM reports ORDER BY period_start DESC, id DESC`) + if err != nil { + return nil, err + } + return pgx.CollectRows(rows, pgx.RowToStructByPos[Report]) +} + +func (s *Store) CreateReport(ctx context.Context, report Report) (Report, error) { + err := s.pool.QueryRow(ctx, `INSERT INTO reports (period_start, period_end, model, prompt_hash, body) + VALUES ($1, $2, $3, $4, $5) + RETURNING id, created_at`, report.PeriodStart, report.PeriodEnd, report.Model, report.PromptHash, report.Body). + Scan(&report.ID, &report.CreatedAt) + return report, err +} + +type NotificationSettings struct { + NtfyServer string `json:"ntfy_server"` + NtfyTopic string `json:"ntfy_topic"` + Enabled bool `json:"enabled"` + RetentionDays int `json:"retention_days"` + UpdatedAt time.Time `json:"updated_at"` +} + +func (s *Store) NotificationSettings(ctx context.Context) (NotificationSettings, error) { + var settings NotificationSettings + err := s.pool.QueryRow(ctx, `SELECT ntfy_server, ntfy_topic, enabled, retention_days, updated_at + FROM notification_settings WHERE id`).Scan(&settings.NtfyServer, &settings.NtfyTopic, &settings.Enabled, + &settings.RetentionDays, &settings.UpdatedAt) + return settings, err +} + +func (s *Store) UpdateNotificationSettings(ctx context.Context, settings NotificationSettings) (NotificationSettings, error) { + err := s.pool.QueryRow(ctx, `UPDATE notification_settings SET ntfy_server = $1, ntfy_topic = $2, + enabled = $3, retention_days = $4, updated_at = now() WHERE id + RETURNING ntfy_server, ntfy_topic, enabled, retention_days, updated_at`, settings.NtfyServer, + settings.NtfyTopic, settings.Enabled, settings.RetentionDays).Scan(&settings.NtfyServer, &settings.NtfyTopic, + &settings.Enabled, &settings.RetentionDays, &settings.UpdatedAt) + return settings, 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) + if err != nil { + return 0, err + } + defer tx.Rollback(ctx) + var deleted int64 + for _, table := range []string{"activities", "samples", "reports"} { + column := map[string]string{"activities": "started_at", "samples": "ts", "reports": "period_start"}[table] + tag, err := tx.Exec(ctx, `DELETE FROM `+table+` WHERE `+column+` < $1`, before) + if err != nil { + return 0, err + } + deleted += tag.RowsAffected() + } + return deleted, tx.Commit(ctx) +} diff --git a/internal/store/store_test.go b/internal/store/store_test.go index b118378..c442964 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -84,3 +84,83 @@ func TestMoveToConcurrent(t *testing.T) { t.Errorf("places = %v, want to end at gym", got) } } + +func TestActivityIdempotencyIsPerDevice(t *testing.T) { + s, dev := setup(t) + other, _, err := s.CreateDevice(context.Background(), "other", "desktop") + if err != nil { + t.Fatal(err) + } + a := ingest.Activity{Source: "test", Kind: "focus", StartedAt: time.Now().Add(-time.Hour), EndedAt: time.Now(), ExternalID: "same"} + if n, err := s.InsertActivities(context.Background(), dev, []ingest.Activity{a}); err != nil || n != 1 { + t.Fatalf("first insert: n=%d err=%v", n, err) + } + if n, err := s.InsertActivities(context.Background(), dev, []ingest.Activity{a}); err != nil || n != 0 { + t.Fatalf("duplicate insert: n=%d err=%v", n, err) + } + if n, err := s.InsertActivities(context.Background(), other.ID, []ingest.Activity{a}); err != nil || n != 1 { + t.Fatalf("other device insert: n=%d err=%v", n, err) + } +} + +func TestActivitiesClipToRange(t *testing.T) { + s, dev := setup(t) + from := time.Now().UTC().Add(-2 * time.Hour).Truncate(time.Second) + to := from.Add(time.Hour) + a := ingest.Activity{Source: "test", Kind: "focus", StartedAt: from.Add(-time.Hour), EndedAt: to.Add(time.Hour), ExternalID: "clip"} + b := ingest.Activity{Source: "test", Kind: "focus", StartedAt: from.Add(10 * time.Minute), EndedAt: from.Add(20 * time.Minute), ExternalID: "page"} + if _, err := s.InsertActivities(context.Background(), dev, []ingest.Activity{a, b}); err != nil { + t.Fatal(err) + } + acts, err := s.Activities(context.Background(), ActivityFilter{From: from, To: to, Limit: 10}) + if err != nil { + t.Fatal(err) + } + if len(acts) != 2 || !acts[0].StartedAt.Equal(from) || !acts[0].EndedAt.Equal(to) || acts[0].DurationS != 3600 { + t.Fatalf("clipped activities = %+v", acts) + } + page, next, err := s.ActivitiesPage(context.Background(), ActivityFilter{From: from, To: to, Limit: 1}) + if err != nil || len(page) != 1 || next == nil { + t.Fatalf("first page: page=%+v next=%+v err=%v", page, next, err) + } + page, next, err = s.ActivitiesPage(context.Background(), ActivityFilter{From: from, To: to, Limit: 1, After: next}) + if err != nil || len(page) != 1 || next != nil || !page[0].StartedAt.Equal(from.Add(10*time.Minute)) { + t.Fatalf("second page: page=%+v next=%+v err=%v", page, next, err) + } +} + +func TestSamplesReportsAndPrivacyPurge(t *testing.T) { + s, dev := setup(t) + ctx := context.Background() + ts := time.Now().UTC().Add(-time.Hour).Truncate(time.Second) + samples := []Sample{{Source: "watch", Metric: "steps", TS: ts, Value: 10, Unit: "count", ExternalID: "s1"}, {Source: "watch", Metric: "steps", TS: ts.Add(time.Minute), Value: 20, Unit: "count", ExternalID: "s2"}} + if n, err := s.InsertSamples(ctx, dev, samples); err != nil || n != 2 { + t.Fatalf("insert samples: n=%d err=%v", n, err) + } + if n, err := s.InsertSamples(ctx, dev, samples[:1]); err != nil || n != 0 { + t.Fatalf("duplicate samples: n=%d err=%v", n, err) + } + got, next, err := s.SamplesPage(ctx, SampleFilter{From: ts.Add(-time.Minute), To: ts.Add(time.Hour), Limit: 1}) + if err != nil || len(got) != 1 || next == nil { + t.Fatalf("sample page: got=%+v next=%+v err=%v", got, next, err) + } + summary, err := s.SampleSummary(ctx, ts.Add(-time.Minute), ts.Add(time.Hour)) + if err != nil || len(summary) != 1 || summary[0].Count != 2 || summary[0].Average != 15 { + t.Fatalf("sample summary: %+v err=%v", summary, err) + } + report, err := s.CreateReport(ctx, Report{PeriodStart: ts, PeriodEnd: ts.Add(time.Hour), Model: "test", Body: "ok"}) + if err != nil || report.ID == 0 { + t.Fatalf("create report: %+v err=%v", report, err) + } + settings, err := s.NotificationSettings(ctx) + if err != nil || settings.NtfyServer == "" { + t.Fatalf("settings: %+v err=%v", settings, err) + } + if _, err := s.PurgeBefore(ctx, ts.Add(time.Minute)); err != nil { + t.Fatal(err) + } + reports, err := s.Reports(ctx) + if err != nil || len(reports) != 0 { + t.Fatalf("purged reports: %+v err=%v", reports, err) + } +} diff --git a/web/src/App.vue b/web/src/App.vue index 2507554..b1ae647 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -1,12 +1,13 @@ diff --git a/web/src/api.ts b/web/src/api.ts index 5d1ad44..9066e2d 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -1,9 +1,10 @@ // Calls /api/v1 with the main site's session cookies, which the browser sends. -export async function api(method: string, path: string, body?: unknown): Promise { +export async function api(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise { const r = await fetch("api/v1/" + path, { method, headers: body ? { "Content-Type": "application/json" } : {}, body: body ? JSON.stringify(body) : undefined, + signal, }); const out = await r.json().catch(() => ({})); // The server serves the login redirect instead of the app, so a reload signs in again. @@ -22,6 +23,7 @@ export interface Summary { totals: Total[]; by_kind: Record; goals: Goal[]; } export interface Activity { + id: number; device: string; source: string; kind: string; label: string; started_at: string; ended_at: string; duration_s: number; attrs?: Record; @@ -31,6 +33,21 @@ export interface Device { last_seen_at?: string | null; revoked_at?: string | null; } +export interface AdminGoal { + id: number; kind: string; label: string; op: string; + target_s: number; period?: string; +} + +export interface Report { + id: number; period_start: string; period_end: string; + model: string; prompt_hash: string; body: string; created_at: string; +} + +export interface NotificationSettings { + ntfy_server: string; ntfy_topic: string; enabled: boolean; + retention_days: number; updated_at?: 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/components/CodeBlock.vue b/web/src/components/CodeBlock.vue index b8dc106..59d02a3 100644 --- a/web/src/components/CodeBlock.vue +++ b/web/src/components/CodeBlock.vue @@ -5,11 +5,16 @@ import { copy } from "../copy"; // A command block with a Copy button, which copies the text as rendered. const pre = ref(); const label = ref("Copy"); +const feedback = ref(""); +function copyCode() { + copy(pre.value?.innerText || "", s => { label.value = s; feedback.value = s === "Copied" ? "Code copied to clipboard." : "Could not copy code."; }); +} diff --git a/web/src/components/DayTimeline.vue b/web/src/components/DayTimeline.vue index 3fce46a..a3feb27 100644 --- a/web/src/components/DayTimeline.vue +++ b/web/src/components/DayTimeline.vue @@ -1,11 +1,12 @@ diff --git a/web/src/components/GoalHistory.vue b/web/src/components/GoalHistory.vue index 203cf02..254c357 100644 --- a/web/src/components/GoalHistory.vue +++ b/web/src/components/GoalHistory.vue @@ -30,8 +30,8 @@ function enter(e: MouseEvent | FocusEvent, date: string, g?: Goal) {