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)
}
}