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
+17 -15
View File
@@ -1,22 +1,22 @@
# Activity Tracker # Activity Tracker
A self-hosted service that records where your time goes: desktop apps, browser tabs, walks and workouts, and desk/bed presence. Each device runs a small collector that uploads timestamped intervals to a Go API backed by PostgreSQL. A daily summary checks your totals against goals such as "≤ 1h of YouTube" or "≥ 1h outside". A self-hosted service that records where your time goes: desktop apps, browser tabs, time at home and away, and desk/bed presence. Each device runs a small collector that uploads timestamped intervals to a Go API backed by PostgreSQL. A daily summary checks your totals against goals such as "≤ 1h of YouTube" or "≥ 1h outside".
``` ```
[hypr-agent] [browser ext] [webcam agent] [Health Auto Export] [hypr-agent] [browser ext] [webcam agent] [iOS Shortcuts]
└────────── HTTPS + Bearer API key (batched JSON) ─────────┘ └────────── HTTPS + Bearer API key (batched JSON) ─────────┘
│ │
tracker (Go, container) ── PostgreSQL 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`. Point metrics such as step counts go in `samples`. 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 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.
## Status ## Status
| Collector | Status | | Collector | Status |
|---|---| |---|---|
| Hyprland (`cmd/hypr-agent`) | ✅ built | | Hyprland (`cmd/hypr-agent`) | ✅ built |
| Apple Health (Health Auto Export → `/health/hae`) | ✅ endpoint built; configure the app | | iPhone location (Shortcuts → `/location/{arrive,leave}`) | ✅ built; configure the automations |
| Browser (Violentmonkey userscript, `/tracker.user.js`) | ✅ built | | Browser (Violentmonkey userscript, `/tracker.user.js`) | ✅ built |
| Webcam presence (`/presence/events`) | endpoint ready, agent not yet written | | Webcam presence (`/presence/events`) | endpoint ready, agent not yet written |
| AI analysis (`reports` table) | planned | | AI analysis (`reports` table) | planned |
@@ -98,7 +98,7 @@ 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/browser/events` | key | `tab_focus`, `idle` |
| POST | `/api/v1/presence/events` | key | `at_desk`, `in_bed`, `away` | | POST | `/api/v1/presence/events` | key | `at_desk`, `in_bed`, `away` |
| POST | `/api/v1/manual/events` | key | any | | POST | `/api/v1/manual/events` | key | any |
| POST | `/api/v1/health/hae` | key | Health Auto Export JSON. Workouts and sleep become activities; other metrics become samples | | 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=` | key or admin | RFC3339 times; defaults to the last 24h |
| GET | `/api/v1/summary/daily?date=YYYY-MM-DD` | key or admin | totals per label and kind, plus goal results | | GET | `/api/v1/summary/daily?date=YYYY-MM-DD` | key or admin | totals per label and kind, plus goal results |
| GET, POST | `/api/v1/devices` | admin | list devices; create one with `{"name","kind"}`, which returns its key once | | GET, POST | `/api/v1/devices` | admin | list devices; create one with `{"name","kind"}`, which returns its key once |
@@ -164,16 +164,19 @@ The setup page has these steps with your URL filled in.
Closed intervals are queued in the script's storage and uploaded every minute by one tab at a time. If a tab is closed or crashes mid-interval, another tab recovers its last checkpoint (at most 5s lost). It runs on every `http`/`https` page and on local `file://` pages, which are labelled `file` (in Chrome, enable **Allow access to file URLs** for Violentmonkey). It can't see browser pages such as `about:`, `chrome://` or the new tab page, extension stores, or the built-in PDF viewer, so time there isn't recorded. The Hyprland agent still counts it as browser `app_focus`. Closed intervals are queued in the script's storage and uploaded every minute by one tab at a time. If a tab is closed or crashes mid-interval, another tab recovers its last checkpoint (at most 5s lost). It runs on every `http`/`https` page and on local `file://` pages, which are labelled `file` (in Chrome, enable **Allow access to file URLs** for Violentmonkey). It can't see browser pages such as `about:`, `chrome://` or the new tab page, extension stores, or the built-in PDF viewer, so time there isn't recorded. The Hyprland agent still counts it as browser `app_focus`.
## Apple Health ## iPhone location
In the Health Auto Export iOS app, create a **REST API** automation with these settings: The free Shortcuts app reports when you arrive at and leave each place. Apple doesn't let you import automations, so you set them up on the phone. One shared shortcut holds the URL and key, so each automation is only two actions. The setup page shows the same steps with your key and place names filled in.
- URL: `https://tracker.example.com/api/v1/health/hae`
- Header: `Authorization: Bearer <key>`. Create the key with `--kind health`.
- Format: JSON
- Data: Workouts, plus metrics such as Step Count and Sleep Analysis
- Sync cadence: hourly
Walking and hiking workouts are stored with the kind `walk`, running workouts as `run`, and any other workout as `workout`. 1. Create a key with kind `location` on the setup page.
2. Once: make a shortcut named `Tracker` with one **Get Contents of URL** action. The URL is `https://www.adam-french.co.uk/tracker/api/v1/location/` followed by the **Shortcut Input** variable, the Method is `POST`, and the Header is `Authorization: Bearer <key>`.
3. For each place, make two personal automations (iOS 17 or later, **Run Immediately**). The first is **Arrive** at the address, with a **Text** action `arrive/<place>` followed by **Run Shortcut → Tracker**. The second is the same for **Leave**, with `leave/<place>`.
The endpoint is `POST /api/v1/location/{arrive,leave}/{place}`. `?place=` and a `{"place"}` body also work, and with no place given it means `home`.
Each device has one open `place` interval at a time, labelled with the place (lower-cased; `home` if none is given) or `away` between places. An arrive or leave closes the open interval and starts the next one. The open interval is stored with `ended_at = started_at` (marked `attrs.open`), and queries and summaries count it as running until now. Arriving where you already are does nothing, and a leave for a place you aren't in is ignored, so duplicate or late geofence triggers can't corrupt the timeline. A missed trigger stretches the previous interval until the next one arrives.
To track time outside: `tracker goal add --kind place --label away --op '>=' --target 1h`.
## Development ## Development
@@ -189,5 +192,4 @@ Layout: `cmd/tracker` (server and admin CLI), `cmd/hypr-agent`, `internal/{api,a
1. Webcam presence agent. Detection will run on the device and only intervals will be uploaded; frames never leave the machine. 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. 2. Nudges: push notifications through ntfy when a goal is at risk during the day.
3. Location: an OwnTracks or Home Assistant geofence will provide reliable "time outside" intervals. 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`.
4. 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`.
+1 -1
View File
@@ -165,7 +165,7 @@ func apikeyCmd(ctx context.Context, st *store.Store, args []string) error {
} }
fs := flag.NewFlagSet("apikey "+args[0], flag.ContinueOnError) fs := flag.NewFlagSet("apikey "+args[0], flag.ContinueOnError)
name := fs.String("name", "", "device name, e.g. laptop-hypr") name := fs.String("name", "", "device name, e.g. laptop-hypr")
kind := fs.String("kind", "", "collector kind, e.g. hyprland, browser, health, presence") kind := fs.String("kind", "", "collector kind, e.g. hyprland, browser, location, presence")
if err := fs.Parse(args[1:]); err != nil { if err := fs.Parse(args[1:]); err != nil {
return err return err
} }
+38 -13
View File
@@ -5,6 +5,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"io"
"log/slog" "log/slog"
"net/http" "net/http"
"strconv" "strconv"
@@ -20,10 +21,7 @@ import (
"ccp/internal/web" "ccp/internal/web"
) )
const ( const maxEventBody = 5 << 20 // 5 MiB
maxEventBody = 5 << 20 // 5 MiB
maxHAEBody = 50 << 20 // Health Auto Export payloads can be large
)
type Server struct { type Server struct {
store *store.Store 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 /browser/events", srv.device(srv.ingestEvents(ingest.Browser)))
api.Handle("POST /presence/events", srv.device(srv.ingestEvents(ingest.Presence))) 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 /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 /activities", srv.deviceOrAdmin(http.HandlerFunc(srv.activities)))
api.Handle("GET /summary/daily", srv.deviceOrAdmin(http.HandlerFunc(srv.dailySummary))) api.Handle("GET /summary/daily", srv.deviceOrAdmin(http.HandlerFunc(srv.dailySummary)))
api.Handle("GET /devices", srv.adminAPI(http.HandlerFunc(srv.listDevices))) 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 { type ingestResult struct {
Received int `json:"received"` Received int `json:"received"`
Inserted int64 `json:"inserted"` Inserted int64 `json:"inserted"`
Samples int64 `json:"samples_inserted,omitempty"`
} }
func (s *Server) ingestEvents(spec ingest.Spec) http.HandlerFunc { 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) { // ingestLocation takes an arrive or leave from a phone geofence automation.
var p ingest.HAEPayload // The place comes from the path (/arrive/gym), ?place=, the body's "place",
if !s.decode(w, r, maxHAEBody, &p) { // 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 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 { if err != nil {
writeError(w, http.StatusUnprocessableEntity, err.Error()) writeError(w, http.StatusUnprocessableEntity, err.Error())
return return
} }
dev := deviceFrom(r.Context()).ID 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 { if err != nil {
s.internalError(w, r, err) s.internalError(w, r, err)
return 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 { if err != nil {
s.internalError(w, r, err) s.internalError(w, r, err)
return 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) { 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) 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 // 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 package ingest
import ( import (
@@ -42,16 +42,6 @@ type Activity struct {
ExternalID string 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 // Spec describes which kinds an endpoint accepts and the source its
// activities are stored under. // activities are stored under.
type Spec struct { type Spec struct {
+17 -26
View File
@@ -1,7 +1,6 @@
package ingest package ingest
import ( import (
"encoding/json"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -41,32 +40,24 @@ func TestNormalizeValidation(t *testing.T) {
} }
} }
func TestNormalizeHAE(t *testing.T) { func TestNormalizeLocation(t *testing.T) {
raw := `{"data":{ now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
"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":[ e, err := NormalizeLocation(LocationEvent{}, now)
{"name":"step_count","units":"count","data":[{"date":"2026-10-14 07:00:00 -0700","qty":812,"source":"iPhone"},{"date":"bad"}]}, if err != nil || e.Place != "home" || !e.At.Equal(now) {
{"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}]} t.Fatalf("defaults: got %+v, %v", e, err)
]}}`
var p HAEPayload
if err := json.Unmarshal([]byte(raw), &p); err != nil {
t.Fatal(err)
} }
acts, samples, err := NormalizeHAE(p) e, err = NormalizeLocation(LocationEvent{Place: " Gym "}, now)
if err != nil { if err != nil || e.Place != "gym" {
t.Fatal(err) t.Fatalf("got %+v, %v", e, err)
} }
if len(acts) != 2 || len(samples) != 1 { for _, bad := range []LocationEvent{
t.Fatalf("got %d activities, %d samples", len(acts), len(samples)) {Place: "Away"},
} {At: now.Add(time.Hour)},
walk := acts[0] {At: now.Add(-8 * 24 * time.Hour)},
if walk.Kind != "walk" || walk.ExternalID != "W1" || walk.EndedAt.Sub(walk.StartedAt) != 45*time.Minute { } {
t.Errorf("walk: %+v", walk) if _, err := NormalizeLocation(bad, now); err == nil {
} t.Errorf("%+v: want error", bad)
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])
} }
} }
+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) return s.sendBatch(ctx, b)
} }
// InsertSamples stores samples with the same idempotency rules as activities. // MoveTo records a location transition for a device: it closes the device's
func (s *Store) InsertSamples(ctx context.Context, deviceID int64, samples []ingest.Sample) (int64, error) { // open place interval at `at` and opens one labelled `label`. Moving to the
b := &pgx.Batch{} // place the device is already in changes nothing, so repeated geofence
for _, m := range samples { // triggers are harmless. It reports whether anything changed.
b.Queue(`INSERT INTO samples func (s *Store) MoveTo(ctx context.Context, deviceID int64, label string, at time.Time) (bool, error) {
(device_id, source, metric, ts, value, unit, external_id) tx, err := s.pool.Begin(ctx)
VALUES ($1, $2, $3, $4, $5, $6, $7) if err != nil {
ON CONFLICT (source, external_id) DO NOTHING`, return false, err
deviceID, m.Source, m.Metric, m.TS, m.Value, m.Unit, m.ExternalID)
} }
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) { func (s *Store) sendBatch(ctx context.Context, b *pgx.Batch) (int64, error) {
@@ -177,12 +238,18 @@ type ActivityFilter struct {
Limit int 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. // Activities returns activities overlapping [From, To), oldest first.
func (s *Store) Activities(ctx context.Context, f ActivityFilter) ([]StoredActivity, error) { func (s *Store) Activities(ctx context.Context, f ActivityFilter) ([]StoredActivity, error) {
rows, err := s.pool.Query(ctx, 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 `SELECT a.id, d.name, a.source, a.kind, a.label, a.started_at, a.end_at,
FROM activities a JOIN devices d ON d.id = a.device_id extract(epoch FROM a.end_at - a.started_at)::integer, a.attrs
WHERE a.started_at < $2 AND a.ended_at > $1 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 ($3 = '' OR a.source = $3)
AND ($4 = '' OR a.kind = $4) AND ($4 = '' OR a.kind = $4)
ORDER BY a.started_at 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) { func (s *Store) Totals(ctx context.Context, from, to time.Time) ([]Total, error) {
rows, err := s.pool.Query(ctx, rows, err := s.pool.Query(ctx,
`SELECT source, kind, label, `SELECT source, kind, label,
sum(extract(epoch FROM least(ended_at, $2) - greatest(started_at, $1)))::bigint AS seconds sum(extract(epoch FROM least(end_at, $2) - greatest(started_at, $1)))::bigint AS seconds
FROM activities FROM (SELECT *, `+effectiveEnd+` AS end_at FROM activities) a
WHERE started_at < $2 AND ended_at > $1 WHERE started_at < $2 AND end_at > $1
GROUP BY source, kind, label GROUP BY source, kind, label
ORDER BY seconds DESC`, ORDER BY seconds DESC`,
from, to) from, to)