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:
+83
-16
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user