Add activity tracker server, Hyprland agent and Gitea image publishing
Test and publish / test (push) Successful in 2m38s
Test and publish / publish (push) Failing after 2m30s

The Go API on PostgreSQL ingests desktop, browser, presence, manual and
Health Auto Export events and serves activities and daily goal summaries.
The Hyprland agent records window focus, idle and lock intervals.

The CI workflow publishes adam-french.co.uk/adamf/activity-tracker to the
Gitea registry and rolls the web_server stack onto it. The image probes
itself through a new `tracker healthcheck` command, because distroless
has no wget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 20:38:12 +01:00
co-authored by Claude Opus 5.5
parent 0cbbb76dee
commit f4ce04875c
29 changed files with 2810 additions and 0 deletions
+156
View File
@@ -0,0 +1,156 @@
package ingest
import (
"fmt"
"strings"
"time"
)
// Health Auto Export (iOS) REST automation payload (JSON export format).
// Only the fields we use are declared.
type HAEPayload struct {
Data struct {
Metrics []HAEMetric `json:"metrics"`
Workouts []HAEWorkout `json:"workouts"`
} `json:"data"`
}
type HAEMetric struct {
Name string `json:"name"`
Units string `json:"units"`
Data []map[string]any `json:"data"`
}
type HAEWorkout struct {
ID string `json:"id"`
Name string `json:"name"`
Start string `json:"start"`
End string `json:"end"`
Location string `json:"location"`
Distance map[string]any `json:"distance"`
Energy map[string]any `json:"activeEnergyBurned"`
}
const (
haeSource = "health"
haeTimeLayout = "2006-01-02 15:04:05 -0700"
)
// NormalizeHAE converts workouts and sleep into activities, and every other
// quantity metric into samples. Entries that can't be parsed are skipped
// rather than failing the whole export.
func NormalizeHAE(p HAEPayload) ([]Activity, []Sample, error) {
var acts []Activity
var samples []Sample
for _, w := range p.Data.Workouts {
start, err1 := parseHAETime(w.Start)
end, err2 := parseHAETime(w.End)
if err1 != nil || err2 != nil || end.Before(start) {
continue
}
id := w.ID
if id == "" {
id = fmt.Sprintf("workout|%s|%s", w.Name, w.Start)
}
attrs := map[string]any{"name": w.Name}
if w.Location != "" {
attrs["location"] = w.Location
}
if w.Distance != nil {
attrs["distance"] = w.Distance
}
if w.Energy != nil {
attrs["active_energy"] = w.Energy
}
acts = append(acts, Activity{
Source: haeSource,
Kind: workoutKind(w.Name),
Label: w.Name,
StartedAt: start,
EndedAt: end,
Attrs: attrs,
ExternalID: id,
})
}
for _, m := range p.Data.Metrics {
if m.Name == "sleep_analysis" {
acts = append(acts, sleepActivities(m)...)
continue
}
for _, d := range m.Data {
date, _ := d["date"].(string)
qty, ok := d["qty"].(float64)
ts, err := parseHAETime(date)
if !ok || err != nil {
continue
}
src, _ := d["source"].(string)
samples = append(samples, Sample{
Source: haeSource,
Metric: m.Name,
TS: ts,
Value: qty,
Unit: m.Units,
ExternalID: fmt.Sprintf("%s|%s|%s", m.Name, date, src),
})
}
}
if len(acts) == 0 && len(samples) == 0 {
return nil, nil, fmt.Errorf("payload contains no usable workouts or metrics")
}
return acts, samples, nil
}
// sleepActivities handles the aggregated sleep_analysis format, which has
// sleepStart/sleepEnd instead of a qty.
func sleepActivities(m HAEMetric) []Activity {
var out []Activity
for _, d := range m.Data {
s, _ := d["sleepStart"].(string)
e, _ := d["sleepEnd"].(string)
start, err1 := parseHAETime(s)
end, err2 := parseHAETime(e)
if err1 != nil || err2 != nil || end.Before(start) {
continue
}
attrs := map[string]any{}
for _, k := range []string{"asleep", "inBed", "core", "deep", "rem", "awake"} {
if v, ok := d[k]; ok {
attrs[k] = v
}
}
out = append(out, Activity{
Source: haeSource,
Kind: "sleep",
Label: "sleep",
StartedAt: start,
EndedAt: end,
Attrs: attrs,
ExternalID: "sleep|" + s,
})
}
return out
}
func workoutKind(name string) string {
n := strings.ToLower(name)
switch {
case strings.Contains(n, "walk"), strings.Contains(n, "hik"):
return "walk"
case strings.Contains(n, "run"):
return "run"
default:
return "workout"
}
}
func parseHAETime(s string) (time.Time, error) {
t, err := time.Parse(haeTimeLayout, s)
if err != nil {
return t, err
}
return t.UTC(), nil
}
+129
View File
@@ -0,0 +1,129 @@
// Package ingest defines the wire format collectors upload and normalises it
// into activities and samples ready for storage.
package ingest
import (
"fmt"
"strings"
"time"
)
const (
MaxBatch = 1000
maxDuration = 7 * 24 * time.Hour
maxFutureSkew = 5 * time.Minute
maxLabelLength = 512
maxIDLength = 128
)
// Event is a single interval as sent by a collector. ID is generated by the
// collector and makes re-uploads idempotent.
type Event struct {
ID string `json:"id"`
Kind string `json:"kind"`
Label string `json:"label"`
StartedAt time.Time `json:"started_at"`
EndedAt time.Time `json:"ended_at"`
Attrs map[string]any `json:"attrs,omitempty"`
}
type Batch struct {
Events []Event `json:"events"`
}
// Activity is a normalised interval ready to be stored.
type Activity struct {
Source string
Kind string
Label string
StartedAt time.Time
EndedAt time.Time
Attrs map[string]any
ExternalID string
}
// Sample is a normalised point-in-time metric ready to be stored.
type Sample struct {
Source string
Metric string
TS time.Time
Value float64
Unit string
ExternalID string
}
// Spec describes which kinds an endpoint accepts and the source its
// activities are stored under.
type Spec struct {
Source string
Kinds map[string]bool // nil accepts any kind
}
var (
Desktop = Spec{Source: "hyprland", Kinds: set("app_focus", "idle", "locked")}
Browser = Spec{Source: "browser", Kinds: set("tab_focus", "idle")}
Presence = Spec{Source: "presence", Kinds: set("at_desk", "in_bed", "away")}
Manual = Spec{Source: "manual"}
)
func set(kinds ...string) map[string]bool {
m := make(map[string]bool, len(kinds))
for _, k := range kinds {
m[k] = true
}
return m
}
// Normalize validates every event in the batch and converts it to activities.
// The whole batch is rejected if any event is invalid.
func (s Spec) Normalize(b Batch, now time.Time) ([]Activity, error) {
if len(b.Events) == 0 {
return nil, fmt.Errorf("batch has no events")
}
if len(b.Events) > MaxBatch {
return nil, fmt.Errorf("batch has %d events, max is %d", len(b.Events), MaxBatch)
}
out := make([]Activity, 0, len(b.Events))
for i, e := range b.Events {
if err := s.validate(e, now); err != nil {
return nil, fmt.Errorf("event %d: %w", i, err)
}
attrs := e.Attrs
if attrs == nil {
attrs = map[string]any{}
}
out = append(out, Activity{
Source: s.Source,
Kind: e.Kind,
Label: strings.TrimSpace(e.Label),
StartedAt: e.StartedAt.UTC(),
EndedAt: e.EndedAt.UTC(),
Attrs: attrs,
ExternalID: e.ID,
})
}
return out, nil
}
func (s Spec) validate(e Event, now time.Time) error {
switch {
case e.ID == "" || len(e.ID) > maxIDLength:
return fmt.Errorf("id must be 1-%d characters", maxIDLength)
case e.Kind == "":
return fmt.Errorf("kind is required")
case s.Kinds != nil && !s.Kinds[e.Kind]:
return fmt.Errorf("kind %q not accepted by this endpoint", e.Kind)
case len(e.Label) > maxLabelLength:
return fmt.Errorf("label longer than %d characters", maxLabelLength)
case e.StartedAt.IsZero() || e.EndedAt.IsZero():
return fmt.Errorf("started_at and ended_at are required")
case e.EndedAt.Before(e.StartedAt):
return fmt.Errorf("ended_at is before started_at")
case e.EndedAt.Sub(e.StartedAt) > maxDuration:
return fmt.Errorf("interval longer than %s", maxDuration)
case e.EndedAt.After(now.Add(maxFutureSkew)):
return fmt.Errorf("ended_at is in the future")
}
return nil
}
+72
View File
@@ -0,0 +1,72 @@
package ingest
import (
"encoding/json"
"strings"
"testing"
"time"
)
func TestNormalizeValidation(t *testing.T) {
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
ok := Event{ID: "1", Kind: "app_focus", Label: "kitty", StartedAt: now.Add(-time.Hour), EndedAt: now}
tests := []struct {
name string
mutate func(*Event)
wantErr string
}{
{"valid", func(e *Event) {}, ""},
{"missing id", func(e *Event) { e.ID = "" }, "id"},
{"wrong kind", func(e *Event) { e.Kind = "tab_focus" }, "not accepted"},
{"reversed", func(e *Event) { e.EndedAt = e.StartedAt.Add(-time.Second) }, "before"},
{"future", func(e *Event) { e.EndedAt = now.Add(time.Hour) }, "future"},
{"too long", func(e *Event) { e.StartedAt = now.Add(-8 * 24 * time.Hour) }, "longer"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := ok
tt.mutate(&e)
acts, err := Desktop.Normalize(Batch{Events: []Event{e}}, now)
if tt.wantErr == "" {
if err != nil || len(acts) != 1 || acts[0].Source != "hyprland" {
t.Fatalf("got %+v, %v", acts, err)
}
return
}
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("got err %v, want containing %q", err, tt.wantErr)
}
})
}
}
func TestNormalizeHAE(t *testing.T) {
raw := `{"data":{
"workouts":[{"id":"W1","name":"Outdoor Walk","start":"2026-10-14 07:00:00 -0700","end":"2026-10-14 07:45:00 -0700","location":"Outdoor"}],
"metrics":[
{"name":"step_count","units":"count","data":[{"date":"2026-10-14 07:00:00 -0700","qty":812,"source":"iPhone"},{"date":"bad"}]},
{"name":"sleep_analysis","units":"hr","data":[{"sleepStart":"2026-10-13 23:10:00 -0700","sleepEnd":"2026-10-14 06:40:00 -0700","asleep":7.1}]}
]}}`
var p HAEPayload
if err := json.Unmarshal([]byte(raw), &p); err != nil {
t.Fatal(err)
}
acts, samples, err := NormalizeHAE(p)
if err != nil {
t.Fatal(err)
}
if len(acts) != 2 || len(samples) != 1 {
t.Fatalf("got %d activities, %d samples", len(acts), len(samples))
}
walk := acts[0]
if walk.Kind != "walk" || walk.ExternalID != "W1" || walk.EndedAt.Sub(walk.StartedAt) != 45*time.Minute {
t.Errorf("walk: %+v", walk)
}
if walk.StartedAt.Hour() != 14 { // 07:00 -0700 is 14:00 UTC
t.Errorf("start not converted to UTC: %v", walk.StartedAt)
}
if acts[1].Kind != "sleep" || samples[0].Value != 812 {
t.Errorf("sleep %+v, sample %+v", acts[1], samples[0])
}
}