Fix location races, run database tests in CI, add make check
Test and publish / test (push) Has been cancelled
Test and publish / publish (push) Has been cancelled

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]>
This commit is contained in:
2026-10-14 22:48:41 +01:00
co-authored by Claude Opus 5.5
parent 0be97384fa
commit cfe17ecf5d
13 changed files with 285 additions and 80 deletions
+6 -2
View File
@@ -61,8 +61,12 @@ func ServeControl(ctx context.Context, out chan<- ControlEvent) error {
fmt.Fprintf(conn, "unknown command %q\n", cmd)
return
}
out <- ControlEvent{Command: cmd, At: time.Now()}
fmt.Fprintln(conn, "ok")
select {
case out <- ControlEvent{Command: cmd, At: time.Now()}:
fmt.Fprintln(conn, "ok")
case <-ctx.Done(): // the agent stopped reading
fmt.Fprintln(conn, "shutting down")
}
}()
}
}
+4 -18
View File
@@ -195,9 +195,7 @@ func (s *Server) ingestEvents(spec ingest.Spec) http.HandlerFunc {
// 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.
// or defaults to home. ingest.Destination decides where the device ends up.
func (s *Server) ingestLocation(w http.ResponseWriter, r *http.Request) {
event := r.PathValue("event")
if event != "arrive" && event != "leave" {
@@ -223,25 +221,13 @@ func (s *Server) ingestLocation(w http.ResponseWriter, r *http.Request) {
return
}
dev := deviceFrom(r.Context()).ID
cur, err := s.store.CurrentPlace(r.Context(), dev)
place, changed, err := s.store.MoveTo(r.Context(), deviceFrom(r.Context()).ID, e.At,
func(cur string) string { return ingest.Destination(event, e.Place, cur) })
if err != nil {
s.internalError(w, r, err)
return
}
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, map[string]any{"place": target, "changed": changed})
writeJSON(w, http.StatusOK, map[string]any{"place": place, "changed": changed})
}
func (s *Server) activities(w http.ResponseWriter, r *http.Request) {
+4 -24
View File
@@ -7,40 +7,20 @@ import (
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"ccp/internal/auth"
"ccp/internal/migrations"
"ccp/internal/store"
"ccp/internal/testdb"
)
// Requires a disposable database, e.g. the one from deploy/docker-compose.yml:
//
// TEST_DATABASE_URL=postgres://tracker:tracker@localhost:5432/tracker go test ./internal/api
// Needs TEST_DATABASE_URL; see internal/testdb.
func setup(t *testing.T) (*httptest.Server, string) {
url := os.Getenv("TEST_DATABASE_URL")
if url == "" {
t.Skip("TEST_DATABASE_URL not set")
}
t.Parallel()
ctx := context.Background()
pool, err := pgxpool.New(ctx, url)
if err != nil {
t.Fatal(err)
}
t.Cleanup(pool.Close)
if err := migrations.Up(ctx, pool); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `TRUNCATE activities, samples, goals, devices RESTART IDENTITY`); err != nil {
t.Fatal(err)
}
st := store.New(pool)
st := store.New(testdb.New(t))
_, key, err := st.CreateDevice(ctx, "test", "hyprland")
if err != nil {
t.Fatal(err)
+16
View File
@@ -61,3 +61,19 @@ func TestNormalizeLocation(t *testing.T) {
}
}
}
func TestDestination(t *testing.T) {
tests := []struct{ event, place, cur, want string }{
{"arrive", "gym", "", "gym"},
{"arrive", "gym", "home", "gym"},
{"leave", "home", "home", Away},
{"leave", "home", "", Away},
{"leave", "home", "gym", "gym"}, // stale leave: stay at the gym
{"leave", "home", Away, Away},
}
for _, tt := range tests {
if got := Destination(tt.event, tt.place, tt.cur); got != tt.want {
t.Errorf("Destination(%q, %q, %q) = %q, want %q", tt.event, tt.place, tt.cur, got, tt.want)
}
}
}
+14
View File
@@ -46,3 +46,17 @@ func NormalizeLocation(e LocationEvent, now time.Time) (LocationEvent, error) {
}
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
}
+19 -23
View File
@@ -119,50 +119,48 @@ func (s *Store) InsertActivities(ctx context.Context, deviceID int64, acts []ing
}
// 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) {
// open place interval at `at` and opens one labelled dest(current place).
// dest is called under the device's lock, so concurrent events see each
// other's moves. Moving to the place the device is already in changes
// nothing, so repeated geofence triggers are harmless. It returns the place
// the device is now in and whether anything changed.
func (s *Store) MoveTo(ctx context.Context, deviceID int64, at time.Time, dest func(cur string) string) (string, bool, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return false, err
return "", false, err
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, deviceID); err != nil {
return false, err
return "", false, err
}
cur, err := currentPlace(ctx, tx, deviceID)
if err != nil {
return false, err
return "", false, err
}
label := dest(cur.Label)
if cur.ID != 0 {
if cur.Label == label {
return false, nil
return label, 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
return "", false, err
}
}
// Each open interval is closed exactly once, so the one this move closes
// identifies it. (A timestamp wouldn't: clamped events can share one.)
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
fmt.Sprintf("move|%d|%d", deviceID, cur.ID)); 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
return label, true, tx.Commit(ctx)
}
type openPlace struct {
@@ -171,11 +169,9 @@ type openPlace struct {
StartedAt time.Time
}
func currentPlace(ctx context.Context, q interface {
QueryRow(context.Context, string, ...any) pgx.Row
}, deviceID int64) (openPlace, error) {
func currentPlace(ctx context.Context, tx pgx.Tx, deviceID int64) (openPlace, error) {
var p openPlace
err := q.QueryRow(ctx,
err := tx.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)
+86
View File
@@ -0,0 +1,86 @@
package store
import (
"context"
"sync"
"testing"
"time"
"ccp/internal/ingest"
"ccp/internal/testdb"
)
func setup(t *testing.T) (*Store, int64) {
t.Parallel()
s := New(testdb.New(t))
d, _, err := s.CreateDevice(context.Background(), "phone", "location")
if err != nil {
t.Fatal(err)
}
return s, d.ID
}
func to(place string) func(string) string { return func(string) string { return place } }
func places(t *testing.T, s *Store) []string {
t.Helper()
acts, err := s.Activities(context.Background(), ActivityFilter{
From: time.Now().Add(-48 * time.Hour), To: time.Now().Add(time.Hour), Kind: ingest.PlaceKind, Limit: 100,
})
if err != nil {
t.Fatal(err)
}
var out []string
for _, a := range acts {
out = append(out, a.Label)
}
return out
}
// Events older than the open interval are clamped to its start, so several
// moves can share a timestamp. They must still get distinct external IDs.
func TestMoveToClampedTimestamps(t *testing.T) {
s, dev := setup(t)
ctx := context.Background()
t0 := time.Now().Add(-time.Hour).Truncate(time.Second)
if _, _, err := s.MoveTo(ctx, dev, t0, to("home")); err != nil {
t.Fatal(err)
}
for _, p := range []string{ingest.Away, "home", ingest.Away, "home"} {
if _, changed, err := s.MoveTo(ctx, dev, t0.Add(-time.Minute), to(p)); err != nil || !changed {
t.Fatalf("move to %s: changed=%v err=%v", p, changed, err)
}
}
if got := places(t, s); len(got) != 5 || got[4] != "home" {
t.Errorf("places = %v", got)
}
}
// A leave and an arrive racing each other must agree on the order they ran
// in: whichever runs second sees the first's move.
func TestMoveToConcurrent(t *testing.T) {
s, dev := setup(t)
ctx := context.Background()
if _, _, err := s.MoveTo(ctx, dev, time.Now().Add(-time.Hour), to("home")); err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
for _, ev := range [][2]string{{"leave", "home"}, {"arrive", "gym"}} {
wg.Go(func() {
if _, _, err := s.MoveTo(ctx, dev, time.Now(), func(cur string) string {
return ingest.Destination(ev[0], ev[1], cur)
}); err != nil {
t.Error(err)
}
})
}
wg.Wait()
// home→away→gym or home→gym (the leave then being stale); never ending away.
got := places(t, s)
if got[len(got)-1] != "gym" {
t.Errorf("places = %v, want to end at gym", got)
}
}
+65
View File
@@ -0,0 +1,65 @@
// Package testdb gives a test its own freshly migrated PostgreSQL database,
// so database tests never touch real data and can run in parallel.
//
// TEST_DATABASE_URL names a server and a role that may CREATE DATABASE, e.g.
// the compose Postgres (`make up`). Without it, tests that need a database
// are skipped:
//
// TEST_DATABASE_URL=postgres://tracker:tracker@localhost:5432/tracker?sslmode=disable go test ./...
package testdb
import (
"context"
"crypto/rand"
"encoding/hex"
"os"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"ccp/internal/migrations"
)
// New creates an empty, migrated database for t and drops it when t ends.
func New(t testing.TB) *pgxpool.Pool {
t.Helper()
url := os.Getenv("TEST_DATABASE_URL")
if url == "" {
t.Skip("TEST_DATABASE_URL not set")
}
ctx := context.Background()
admin, err := pgx.Connect(ctx, url)
if err != nil {
t.Fatalf("testdb: connect: %v", err)
}
b := make([]byte, 6)
rand.Read(b)
name := "tracker_test_" + hex.EncodeToString(b)
if _, err := admin.Exec(ctx, "CREATE DATABASE "+name); err != nil {
admin.Close(ctx)
t.Fatalf("testdb: %v", err)
}
t.Cleanup(func() {
if _, err := admin.Exec(ctx, "DROP DATABASE "+name+" WITH (FORCE)"); err != nil {
t.Errorf("testdb: drop %s: %v", name, err)
}
admin.Close(ctx)
})
cfg, err := pgxpool.ParseConfig(url)
if err != nil {
t.Fatalf("testdb: %v", err)
}
cfg.ConnConfig.Database = name
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatalf("testdb: %v", err)
}
t.Cleanup(pool.Close) // registered last, so it runs before the drop
if err := migrations.Up(ctx, pool); err != nil {
t.Fatalf("testdb: %v", err)
}
return pool
}