Files
ccp/internal/ingest/location.go
T
adamfandClaude Opus 5.5 cfe17ecf5d
Test and publish / test (push) Has been cancelled
Test and publish / publish (push) Has been cancelled
Fix location races, run database tests in CI, add make check
Location: a leave decided its destination before taking the device lock,
so a "leave home" racing an "arrive gym" could undo the arrival. The
decision (now ingest.Destination) runs inside MoveTo under the lock.
Transition external IDs were device|label|time, which collided (500) when
out-of-order events were clamped to the same start; they now name the
interval being closed.

hypr-agent: a control command arriving during shutdown no longer blocks
its goroutine forever.

Tests: internal/testdb gives each database test its own throwaway
database, so they run in parallel and no longer truncate the dev data.
New store tests cover both location bugs. CI starts a Postgres container
so these tests actually run, and adds gofmt, staticcheck (pinned as a go
tool) and -race. `make check` runs the same locally.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 22:48:41 +01:00

63 lines
1.8 KiB
Go

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
}
// Destination is where a device moves on an arrive or leave event for place,
// given the place it is in now ("" if none yet). 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 Destination(event, place, cur string) string {
if event == "arrive" {
return place
}
if cur != "" && cur != place {
return cur
}
return Away
}