Replace Apple Health ingest with iPhone location geofences

POST /api/v1/location/{arrive,leave} records place intervals (home or a
named place, and away in between) from Shortcuts automations. A stale
"leave" for a place the device has already left is ignored. The Health
Auto Export endpoint and its normalizer are removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 22:06:25 +01:00
co-authored by Claude Opus 5.5
parent 230840cabd
commit 67638cdef0
10 changed files with 269 additions and 238 deletions
+38 -13
View File
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"strconv"
@@ -20,10 +21,7 @@ import (
"ccp/internal/web"
)
const (
maxEventBody = 5 << 20 // 5 MiB
maxHAEBody = 50 << 20 // Health Auto Export payloads can be large
)
const maxEventBody = 5 << 20 // 5 MiB
type Server struct {
store *store.Store
@@ -54,7 +52,8 @@ 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 /health/hae", srv.device(http.HandlerFunc(srv.ingestHAE)))
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 /summary/daily", srv.deviceOrAdmin(http.HandlerFunc(srv.dailySummary)))
api.Handle("GET /devices", srv.adminAPI(http.HandlerFunc(srv.listDevices)))
@@ -171,7 +170,6 @@ func (s *Server) ready(w http.ResponseWriter, r *http.Request) {
type ingestResult struct {
Received int `json:"received"`
Inserted int64 `json:"inserted"`
Samples int64 `json:"samples_inserted,omitempty"`
}
func (s *Server) ingestEvents(spec ingest.Spec) http.HandlerFunc {
@@ -194,28 +192,55 @@ func (s *Server) ingestEvents(spec ingest.Spec) http.HandlerFunc {
}
}
func (s *Server) ingestHAE(w http.ResponseWriter, r *http.Request) {
var p ingest.HAEPayload
if !s.decode(w, r, maxHAEBody, &p) {
// 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.
// Leaving a place only counts if the device is in it (or nowhere yet), so a
// late "leave home" after "arrive gym" doesn't undo the arrival.
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
}
acts, samples, err := ingest.NormalizeHAE(p)
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
}
dev := deviceFrom(r.Context()).ID
na, err := s.store.InsertActivities(r.Context(), dev, acts)
cur, err := s.store.CurrentPlace(r.Context(), dev)
if err != nil {
s.internalError(w, r, err)
return
}
ns, err := s.store.InsertSamples(r.Context(), dev, samples)
target := e.Place
if event == "leave" {
target = ingest.Away
if cur != "" && cur != e.Place {
target = cur
}
}
changed, err := s.store.MoveTo(r.Context(), dev, target, e.At)
if err != nil {
s.internalError(w, r, err)
return
}
writeJSON(w, http.StatusOK, ingestResult{Received: len(acts) + len(samples), Inserted: na, Samples: ns})
writeJSON(w, http.StatusOK, map[string]any{"place": target, "changed": changed})
}
func (s *Server) activities(w http.ResponseWriter, r *http.Request) {
+56
View File
@@ -118,3 +118,59 @@ func TestIngestAndSummary(t *testing.T) {
t.Fatalf("activities: %d %v", code, body)
}
}
func TestLocation(t *testing.T) {
srv, key := setup(t)
at := func(d time.Duration) string {
return `"at":"` + time.Now().UTC().Add(d).Format(time.RFC3339) + `"`
}
post := func(event, body string) map[string]any {
t.Helper()
code, out := do(t, "POST", srv.URL+"/api/v1/location/"+event, key, body)
if code != http.StatusOK {
t.Fatalf("%s %s: %d %v", event, body, code, out)
}
return out
}
// A bare POST means home, now.
if out := post("leave", `{`+at(-3*time.Hour)+`}`); out["place"] != "away" || out["changed"] != true {
t.Fatalf("first leave: %v", out)
}
if out := post("arrive?place=Gym", `{`+at(-2*time.Hour)+`}`); out["place"] != "gym" {
t.Fatalf("arrive gym: %v", out)
}
// Leaving home while at the gym is stale and changes nothing.
if out := post("leave", `{`+at(-90*time.Minute)+`}`); out["place"] != "gym" || out["changed"] != false {
t.Fatalf("stale leave: %v", out)
}
post("leave/gym", `{`+at(-time.Hour)+`}`)
post("arrive", "")
if out := post("arrive", ""); out["changed"] != false {
t.Fatalf("repeat arrive should be a no-op: %v", out)
}
code, body := do(t, "GET", srv.URL+"/api/v1/activities?kind=place", key, "")
acts := body["activities"].([]any)
if code != http.StatusOK || len(acts) != 4 {
t.Fatalf("activities: %d %v", code, body)
}
var labels []string
for _, a := range acts {
labels = append(labels, a.(map[string]any)["label"].(string))
}
if strings.Join(labels, ",") != "away,gym,away,home" {
t.Errorf("labels = %v", labels)
}
if d := acts[0].(map[string]any)["duration_s"]; d != 3600.0 {
t.Errorf("first away = %v s", d)
}
// The open home interval reads as running until now.
if end, _ := time.Parse(time.RFC3339Nano, acts[3].(map[string]any)["ended_at"].(string)); time.Since(end) > time.Minute {
t.Errorf("open interval ended at %v", end)
}
if code, _ := do(t, "POST", srv.URL+"/api/v1/location/teleport", key, ""); code != http.StatusNotFound {
t.Errorf("unknown event: %d", code)
}
}
-156
View File
@@ -1,156 +0,0 @@
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
}
+1 -11
View File
@@ -1,5 +1,5 @@
// Package ingest defines the wire format collectors upload and normalises it
// into activities and samples ready for storage.
// into activities ready for storage.
package ingest
import (
@@ -42,16 +42,6 @@ type Activity struct {
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 {
+17 -26
View File
@@ -1,7 +1,6 @@
package ingest
import (
"encoding/json"
"strings"
"testing"
"time"
@@ -41,32 +40,24 @@ func TestNormalizeValidation(t *testing.T) {
}
}
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)
func TestNormalizeLocation(t *testing.T) {
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
e, err := NormalizeLocation(LocationEvent{}, now)
if err != nil || e.Place != "home" || !e.At.Equal(now) {
t.Fatalf("defaults: got %+v, %v", e, err)
}
acts, samples, err := NormalizeHAE(p)
if err != nil {
t.Fatal(err)
e, err = NormalizeLocation(LocationEvent{Place: " Gym "}, now)
if err != nil || e.Place != "gym" {
t.Fatalf("got %+v, %v", e, 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])
for _, bad := range []LocationEvent{
{Place: "Away"},
{At: now.Add(time.Hour)},
{At: now.Add(-8 * 24 * time.Hour)},
} {
if _, err := NormalizeLocation(bad, now); err == nil {
t.Errorf("%+v: want error", bad)
}
}
}
+48
View File
@@ -0,0 +1,48 @@
package ingest
import (
"fmt"
"strings"
"time"
)
// Location transitions come from phone geofence automations (e.g. iOS
// Shortcuts "Arrive"/"Leave"), which can only report the moment of crossing.
// The store turns them into back-to-back intervals with kind "place",
// labelled by the place, or Away between places.
const (
LocationSource = "location"
PlaceKind = "place"
Away = "away"
DefaultPlace = "home"
)
// LocationEvent is the optional body of POST /location/{arrive,leave}. An
// empty body means "home, now".
type LocationEvent struct {
Place string `json:"place"`
At time.Time `json:"at"`
}
// NormalizeLocation fills defaults and validates a transition.
func NormalizeLocation(e LocationEvent, now time.Time) (LocationEvent, error) {
e.Place = strings.ToLower(strings.TrimSpace(e.Place))
if e.Place == "" {
e.Place = DefaultPlace
}
if e.At.IsZero() {
e.At = now
}
e.At = e.At.UTC()
switch {
case e.Place == Away:
return e, fmt.Errorf("%q is reserved for time between places", Away)
case len(e.Place) > maxLabelLength:
return e, fmt.Errorf("place longer than %d characters", maxLabelLength)
case e.At.After(now.Add(maxFutureSkew)):
return e, fmt.Errorf("at is in the future")
case e.At.Before(now.Add(-maxDuration)):
return e, fmt.Errorf("at is more than %s ago", maxDuration)
}
return e, nil
}
+8
View File
@@ -0,0 +1,8 @@
-- +goose Up
-- A device has at most one open location interval: the place it is in now.
-- Open intervals are stored with ended_at = started_at and read as ending now.
CREATE UNIQUE INDEX activities_open_location_idx ON activities (device_id)
WHERE source = 'location' AND attrs ? 'open';
-- +goose Down
DROP INDEX activities_open_location_idx;
+83 -16
View File
@@ -118,17 +118,78 @@ func (s *Store) InsertActivities(ctx context.Context, deviceID int64, acts []ing
return s.sendBatch(ctx, b)
}
// InsertSamples stores samples with the same idempotency rules as activities.
func (s *Store) InsertSamples(ctx context.Context, deviceID int64, samples []ingest.Sample) (int64, error) {
b := &pgx.Batch{}
for _, m := 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 (source, external_id) DO NOTHING`,
deviceID, m.Source, m.Metric, m.TS, m.Value, m.Unit, m.ExternalID)
// MoveTo records a location transition for a device: it closes the device's
// open place interval at `at` and opens one labelled `label`. Moving to the
// place the device is already in changes nothing, so repeated geofence
// triggers are harmless. It reports whether anything changed.
func (s *Store) MoveTo(ctx context.Context, deviceID int64, label string, at time.Time) (bool, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return false, err
}
return s.sendBatch(ctx, b)
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, deviceID); err != nil {
return false, err
}
cur, err := currentPlace(ctx, tx, deviceID)
if err != nil {
return false, err
}
if cur.ID != 0 {
if cur.Label == label {
return false, nil
}
// Out-of-order events would otherwise make a negative interval.
at = maxTime(at, cur.StartedAt)
if _, err := tx.Exec(ctx,
`UPDATE activities SET ended_at = $2, attrs = attrs - 'open' WHERE id = $1`,
cur.ID, at); err != nil {
return false, err
}
}
if _, err := tx.Exec(ctx, `INSERT INTO activities
(device_id, source, kind, label, started_at, ended_at, attrs, external_id)
VALUES ($1, $2, $3, $4, $5, $5, '{"open": true}', $6)`,
deviceID, ingest.LocationSource, ingest.PlaceKind, label, at,
fmt.Sprintf("%d|%s|%s", deviceID, label, at.Format(time.RFC3339Nano))); err != nil {
return false, err
}
return true, tx.Commit(ctx)
}
// CurrentPlace returns the label of the device's open place interval, or ""
// if it has none.
func (s *Store) CurrentPlace(ctx context.Context, deviceID int64) (string, error) {
cur, err := currentPlace(ctx, s.pool, deviceID)
return cur.Label, err
}
type openPlace struct {
ID int64
Label string
StartedAt time.Time
}
func currentPlace(ctx context.Context, q interface {
QueryRow(context.Context, string, ...any) pgx.Row
}, deviceID int64) (openPlace, error) {
var p openPlace
err := q.QueryRow(ctx,
`SELECT id, label, started_at FROM activities
WHERE device_id = $1 AND source = $2 AND attrs ? 'open'`,
deviceID, ingest.LocationSource).Scan(&p.ID, &p.Label, &p.StartedAt)
if errors.Is(err, pgx.ErrNoRows) {
return p, nil
}
return p, err
}
func maxTime(a, b time.Time) time.Time {
if a.After(b) {
return a
}
return b
}
func (s *Store) sendBatch(ctx context.Context, b *pgx.Batch) (int64, error) {
@@ -177,12 +238,18 @@ type ActivityFilter struct {
Limit int
}
// effectiveEnd is an activity's end, reading open location intervals (stored
// with ended_at = started_at) as running until now.
const effectiveEnd = `(CASE WHEN attrs ? 'open' THEN greatest(ended_at, now()) ELSE ended_at END)`
// Activities returns activities overlapping [From, To), oldest first.
func (s *Store) Activities(ctx context.Context, f ActivityFilter) ([]StoredActivity, error) {
rows, err := s.pool.Query(ctx,
`SELECT a.id, d.name, a.source, a.kind, a.label, a.started_at, a.ended_at, a.duration_s, a.attrs
FROM activities a JOIN devices d ON d.id = a.device_id
WHERE a.started_at < $2 AND a.ended_at > $1
`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
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
@@ -210,9 +277,9 @@ type Total struct {
func (s *Store) Totals(ctx context.Context, from, to time.Time) ([]Total, error) {
rows, err := s.pool.Query(ctx,
`SELECT source, kind, label,
sum(extract(epoch FROM least(ended_at, $2) - greatest(started_at, $1)))::bigint AS seconds
FROM activities
WHERE started_at < $2 AND ended_at > $1
sum(extract(epoch FROM least(end_at, $2) - greatest(started_at, $1)))::bigint AS seconds
FROM (SELECT *, `+effectiveEnd+` AS end_at FROM activities) a
WHERE started_at < $2 AND end_at > $1
GROUP BY source, kind, label
ORDER BY seconds DESC`,
from, to)