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]>
This commit is contained in:
@@ -8,9 +8,10 @@
|
|||||||
# the host).
|
# the host).
|
||||||
#
|
#
|
||||||
# TWO JOBS
|
# TWO JOBS
|
||||||
# test go vet + go test, as `make test`. The API tests skip themselves
|
# test gofmt, go vet, staticcheck and go test (with -race, and the
|
||||||
# here: they need TEST_DATABASE_URL, and CI has no Postgres. Then
|
# database tests against a throwaway Postgres container), as
|
||||||
# the Vue app's typecheck and build, in a node container.
|
# `make check`. Then the Vue app's typecheck and build, in a node
|
||||||
|
# container.
|
||||||
# publish main only, after test: builds deploy/Dockerfile, pushes it to
|
# publish main only, after test: builds deploy/Dockerfile, pushes it to
|
||||||
# this Gitea's container registry as :<sha> and :latest, then
|
# this Gitea's container registry as :<sha> and :latest, then
|
||||||
# pulls it into the web_server stack (its `activity-tracker`
|
# pulls it into the web_server stack (its `activity-tracker`
|
||||||
@@ -51,9 +52,25 @@ jobs:
|
|||||||
git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC"
|
git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC"
|
||||||
test -f "$SRC/go.mod"
|
test -f "$SRC/go.mod"
|
||||||
|
|
||||||
|
# A throwaway Postgres on its own network, for the database tests
|
||||||
|
# (internal/testdb gives each test its own database on it).
|
||||||
|
- name: Start Postgres
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
docker network create "ci-$SHA"
|
||||||
|
docker run -d --name "ci-pg-$SHA" --network "ci-$SHA" --network-alias pg \
|
||||||
|
-e POSTGRES_PASSWORD=ci postgres:17
|
||||||
|
for i in $(seq 1 30); do
|
||||||
|
docker exec "ci-pg-$SHA" pg_isready -U postgres -h localhost && exit 0
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
docker logs "ci-pg-$SHA"
|
||||||
|
exit 1
|
||||||
|
|
||||||
# Read-only source, and named volumes for the module and build
|
# Read-only source, and named volumes for the module and build
|
||||||
# caches so repeat runs don't download everything again.
|
# caches so repeat runs don't download everything again.
|
||||||
- name: Go - vet and test
|
- name: Go - lint and test
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
@@ -61,8 +78,10 @@ jobs:
|
|||||||
-v "$SRC":/src:ro -w /src \
|
-v "$SRC":/src:ro -w /src \
|
||||||
-v activity_tracker_ci_gomod:/go/pkg/mod \
|
-v activity_tracker_ci_gomod:/go/pkg/mod \
|
||||||
-v activity_tracker_ci_gobuild:/root/.cache/go-build \
|
-v activity_tracker_ci_gobuild:/root/.cache/go-build \
|
||||||
|
--network "ci-$SHA" \
|
||||||
|
-e TEST_DATABASE_URL='postgres://postgres:ci@pg:5432/postgres?sslmode=disable' \
|
||||||
golang:1.27 \
|
golang:1.27 \
|
||||||
sh -c 'go vet ./... && go test ./...'
|
sh -c 'test -z "$(gofmt -l .)" && go vet ./... && go tool staticcheck ./... && go test -race -count=1 ./...'
|
||||||
|
|
||||||
# Copies web/ out of the read-only source so node_modules and the
|
# Copies web/ out of the read-only source so node_modules and the
|
||||||
# build output stay in the container.
|
# build output stay in the container.
|
||||||
@@ -76,10 +95,13 @@ jobs:
|
|||||||
node:24-alpine \
|
node:24-alpine \
|
||||||
sh -c 'cp -r /src/web /web && cd /web && npm ci && npm run typecheck && npx vite build --outDir /tmp/dist'
|
sh -c 'cp -r /src/web /web && cd /web && npm ci && npm run typecheck && npx vite build --outDir /tmp/dist'
|
||||||
|
|
||||||
- name: Remove the scratch directory
|
- name: Remove the scratch directory and Postgres
|
||||||
if: always()
|
if: always()
|
||||||
shell: bash
|
shell: bash
|
||||||
run: rm -rf "$SRC"
|
run: |
|
||||||
|
rm -rf "$SRC"
|
||||||
|
docker rm -f "ci-pg-$SHA" || true
|
||||||
|
docker network rm "ci-$SHA" || true
|
||||||
|
|
||||||
publish:
|
publish:
|
||||||
needs: test
|
needs: test
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
COMPOSE := docker compose -f deploy/docker-compose.yml
|
COMPOSE := docker compose -f deploy/docker-compose.yml
|
||||||
DEV_DB := postgres://tracker:tracker@localhost:5432/tracker?sslmode=disable
|
DEV_DB := postgres://tracker:tracker@localhost:5432/tracker?sslmode=disable
|
||||||
|
|
||||||
.PHONY: web web-dev build test test-integration run up down docker migrate install-agent
|
.PHONY: web web-dev build check lint test test-integration run up down docker migrate install-agent
|
||||||
|
|
||||||
# Builds the Vue app into internal/web/dist/app, which the binary embeds.
|
# Builds the Vue app into internal/web/dist/app, which the binary embeds.
|
||||||
web:
|
web:
|
||||||
@@ -14,12 +14,21 @@ web-dev:
|
|||||||
build: web
|
build: web
|
||||||
go build -o bin/ ./cmd/...
|
go build -o bin/ ./cmd/...
|
||||||
|
|
||||||
|
# Everything CI checks. Database tests run if the compose Postgres is up
|
||||||
|
# (`make up`); each gets its own throwaway database, so your data is safe.
|
||||||
|
check: lint test-integration
|
||||||
|
cd web && { [ -d node_modules ] || npm ci; } && npm run typecheck
|
||||||
|
|
||||||
|
lint:
|
||||||
|
@test -z "$$(gofmt -l .)" || { echo "gofmt needed:"; gofmt -l .; exit 1; }
|
||||||
|
go vet ./...
|
||||||
|
go tool staticcheck ./...
|
||||||
|
|
||||||
test:
|
test:
|
||||||
go test ./...
|
go test ./...
|
||||||
|
|
||||||
# Runs the API tests against the compose Postgres (make up first).
|
|
||||||
test-integration:
|
test-integration:
|
||||||
TEST_DATABASE_URL='$(DEV_DB)' go test -count=1 ./...
|
TEST_DATABASE_URL='$(DEV_DB)' go test -race -count=1 ./...
|
||||||
|
|
||||||
run: web
|
run: web
|
||||||
AUTH_MODE=dev DEV_MODE=true DATABASE_URL='$(DEV_DB)' go run ./cmd/tracker serve
|
AUTH_MODE=dev DEV_MODE=true DATABASE_URL='$(DEV_DB)' go run ./cmd/tracker serve
|
||||||
|
|||||||
@@ -181,15 +181,24 @@ To track time outside: `tracker goal add --kind place --label away --op '>=' --t
|
|||||||
## Development
|
## Development
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
make test # unit tests
|
make check # everything CI runs: gofmt, vet, staticcheck, all tests (-race), web typecheck. Needs `make up`
|
||||||
make up && make test-integration # also runs the API tests against the compose Postgres (truncates its tables!)
|
make test # unit tests only; database tests skip themselves
|
||||||
make run # build the app, then run the server locally against the compose Postgres
|
make run # build the app, then run the server locally against the compose Postgres
|
||||||
make web-dev # with `make run` going: Vite on :5173 with hot reload, proxying /api to :8080
|
make web-dev # with `make run` going: Vite on :5173 with hot reload, proxying /api to :8080
|
||||||
```
|
```
|
||||||
|
|
||||||
The dashboard is a Vue 3 + Vite app in `web/`. `make web` (and `make build`, `make run`, the Docker build) builds it into `internal/web/dist/app`, which the binary embeds. That directory isn't committed, so a plain `go build` serves a "not built" page at `/` but everything else works, and `go test` needs no Node.
|
The dashboard is a Vue 3 + Vite app in `web/`. `make web` (and `make build`, `make run`, the Docker build) builds it into `internal/web/dist/app`, which the binary embeds. That directory isn't committed, so a plain `go build` serves a "not built" page at `/` but everything else works, and `go test` needs no Node.
|
||||||
|
|
||||||
Layout: `cmd/tracker` (server and admin CLI), `cmd/hypr-agent`, `internal/{api,auth,ingest,store,summary,migrations,config,web}` (`internal/web/tracker.user.js` is the browser collector), `web/` (dashboard app), `internal/agent/hypr`, `deploy/`.
|
Database tests call `testdb.New(t)`, which creates a fresh, migrated database for that test on the server in `TEST_DATABASE_URL` and drops it afterwards. Tests never touch your data and can run in parallel. CI starts a throwaway Postgres for them.
|
||||||
|
|
||||||
|
To add a collector that uploads intervals:
|
||||||
|
|
||||||
|
1. Add a `Spec` (source and accepted kinds) in `internal/ingest/ingest.go`.
|
||||||
|
2. Route `POST /<name>/events` to it in `internal/api/api.go`.
|
||||||
|
3. Add it to the API table above, and to the kind picker and a `<Collector>` section in `web/src/views/Setup.vue`.
|
||||||
|
4. If the kind needs a friendlier name or a fixed timeline lane, add it to `KINDS` in `web/src/api.ts` and `ORDER` in `web/src/components/DayTimeline.vue`.
|
||||||
|
|
||||||
|
Layout: `cmd/tracker` (server and admin CLI), `cmd/hypr-agent`, `internal/{api,auth,ingest,store,summary,migrations,config,web,testdb}` (`internal/web/tracker.user.js` is the browser collector), `web/` (dashboard app), `internal/agent/hypr`, `deploy/`.
|
||||||
|
|
||||||
## Roadmap
|
## Roadmap
|
||||||
|
|
||||||
|
|||||||
@@ -8,12 +8,19 @@ require (
|
|||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
||||||
github.com/mfridman/interpolate v0.0.2 // indirect
|
github.com/mfridman/interpolate v0.0.2 // indirect
|
||||||
github.com/sethvargo/go-retry v0.5.0 // indirect
|
github.com/sethvargo/go-retry v0.5.0 // indirect
|
||||||
go.uber.org/multierr v1.11.0 // indirect
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
|
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 // indirect
|
||||||
|
golang.org/x/mod v0.41.0 // indirect
|
||||||
golang.org/x/sync v0.24.0 // indirect
|
golang.org/x/sync v0.24.0 // indirect
|
||||||
golang.org/x/text v0.43.0 // indirect
|
golang.org/x/text v0.43.0 // indirect
|
||||||
|
golang.org/x/tools v0.51.0 // indirect
|
||||||
|
honnef.co/go/tools v0.8.2 // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
|
tool honnef.co/go/tools/cmd/staticcheck
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c h1:pxW6RcqyfI9/kWtOwnv/G+AzdKuy2ZrqINhenH4HyNs=
|
||||||
|
github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
||||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||||
@@ -33,14 +35,23 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
|||||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||||
|
golang.org/x/exp v0.0.0-20261011100332-faecfb24eb49 h1:pQo5TwmxKJvI8k39uYS2Gqkk8OXWxX/TMSis2Twp1AQ=
|
||||||
|
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 h1:1P7xPZEwZMoBoz0Yze5Nx2/4pxj6nw9ZqHWXqP0iRgQ=
|
||||||
|
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
|
||||||
|
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
|
||||||
|
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
|
||||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||||
|
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
|
||||||
|
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
honnef.co/go/tools v0.8.2 h1:+jPbCzuYxYrcoOvCecYUFDj+XJQRmzIhJmlbpps21Zk=
|
||||||
|
honnef.co/go/tools v0.8.2/go.mod h1:xG1Q4n+mg3bKZrO6RWFA9jFlkqplflmDRHGeuexiLDs=
|
||||||
modernc.org/libc v1.78.0 h1:Lpm+e9K6ruVYEGwWfuBO1xXtYEaXDouFOG1SuWjFDP4=
|
modernc.org/libc v1.78.0 h1:Lpm+e9K6ruVYEGwWfuBO1xXtYEaXDouFOG1SuWjFDP4=
|
||||||
modernc.org/libc v1.78.0/go.mod h1:wvxR55nOF2/66NkJoNV7/coXBTCvT3HR22rcqW6lOuA=
|
modernc.org/libc v1.78.0/go.mod h1:wvxR55nOF2/66NkJoNV7/coXBTCvT3HR22rcqW6lOuA=
|
||||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||||
|
|||||||
@@ -61,8 +61,12 @@ func ServeControl(ctx context.Context, out chan<- ControlEvent) error {
|
|||||||
fmt.Fprintf(conn, "unknown command %q\n", cmd)
|
fmt.Fprintf(conn, "unknown command %q\n", cmd)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
out <- ControlEvent{Command: cmd, At: time.Now()}
|
select {
|
||||||
|
case out <- ControlEvent{Command: cmd, At: time.Now()}:
|
||||||
fmt.Fprintln(conn, "ok")
|
fmt.Fprintln(conn, "ok")
|
||||||
|
case <-ctx.Done(): // the agent stopped reading
|
||||||
|
fmt.Fprintln(conn, "shutting down")
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-18
@@ -195,9 +195,7 @@ func (s *Server) ingestEvents(spec ingest.Spec) http.HandlerFunc {
|
|||||||
|
|
||||||
// ingestLocation takes an arrive or leave from a phone geofence automation.
|
// ingestLocation takes an arrive or leave from a phone geofence automation.
|
||||||
// The place comes from the path (/arrive/gym), ?place=, the body's "place",
|
// The place comes from the path (/arrive/gym), ?place=, the body's "place",
|
||||||
// or defaults to home.
|
// or defaults to home. ingest.Destination decides where the device ends up.
|
||||||
// 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) {
|
func (s *Server) ingestLocation(w http.ResponseWriter, r *http.Request) {
|
||||||
event := r.PathValue("event")
|
event := r.PathValue("event")
|
||||||
if event != "arrive" && event != "leave" {
|
if event != "arrive" && event != "leave" {
|
||||||
@@ -223,25 +221,13 @@ func (s *Server) ingestLocation(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dev := deviceFrom(r.Context()).ID
|
place, changed, err := s.store.MoveTo(r.Context(), deviceFrom(r.Context()).ID, e.At,
|
||||||
cur, err := s.store.CurrentPlace(r.Context(), dev)
|
func(cur string) string { return ingest.Destination(event, e.Place, cur) })
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.internalError(w, r, err)
|
s.internalError(w, r, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
target := e.Place
|
writeJSON(w, http.StatusOK, map[string]any{"place": place, "changed": changed})
|
||||||
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})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) activities(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) activities(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|||||||
@@ -7,40 +7,20 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"ccp/internal/auth"
|
"ccp/internal/auth"
|
||||||
"ccp/internal/migrations"
|
|
||||||
"ccp/internal/store"
|
"ccp/internal/store"
|
||||||
|
"ccp/internal/testdb"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Requires a disposable database, e.g. the one from deploy/docker-compose.yml:
|
// Needs TEST_DATABASE_URL; see internal/testdb.
|
||||||
//
|
|
||||||
// TEST_DATABASE_URL=postgres://tracker:tracker@localhost:5432/tracker go test ./internal/api
|
|
||||||
func setup(t *testing.T) (*httptest.Server, string) {
|
func setup(t *testing.T) (*httptest.Server, string) {
|
||||||
url := os.Getenv("TEST_DATABASE_URL")
|
t.Parallel()
|
||||||
if url == "" {
|
|
||||||
t.Skip("TEST_DATABASE_URL not set")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
pool, err := pgxpool.New(ctx, url)
|
st := store.New(testdb.New(t))
|
||||||
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)
|
|
||||||
_, key, err := st.CreateDevice(ctx, "test", "hyprland")
|
_, key, err := st.CreateDevice(ctx, "test", "hyprland")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -46,3 +46,17 @@ func NormalizeLocation(e LocationEvent, now time.Time) (LocationEvent, error) {
|
|||||||
}
|
}
|
||||||
return e, nil
|
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
@@ -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
|
// 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
|
// open place interval at `at` and opens one labelled dest(current place).
|
||||||
// place the device is already in changes nothing, so repeated geofence
|
// dest is called under the device's lock, so concurrent events see each
|
||||||
// triggers are harmless. It reports whether anything changed.
|
// other's moves. Moving to the place the device is already in changes
|
||||||
func (s *Store) MoveTo(ctx context.Context, deviceID int64, label string, at time.Time) (bool, error) {
|
// 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)
|
tx, err := s.pool.Begin(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return "", false, err
|
||||||
}
|
}
|
||||||
defer tx.Rollback(ctx)
|
defer tx.Rollback(ctx)
|
||||||
|
|
||||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, deviceID); err != nil {
|
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)
|
cur, err := currentPlace(ctx, tx, deviceID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return "", false, err
|
||||||
}
|
}
|
||||||
|
label := dest(cur.Label)
|
||||||
if cur.ID != 0 {
|
if cur.ID != 0 {
|
||||||
if cur.Label == label {
|
if cur.Label == label {
|
||||||
return false, nil
|
return label, false, nil
|
||||||
}
|
}
|
||||||
// Out-of-order events would otherwise make a negative interval.
|
// Out-of-order events would otherwise make a negative interval.
|
||||||
at = maxTime(at, cur.StartedAt)
|
at = maxTime(at, cur.StartedAt)
|
||||||
if _, err := tx.Exec(ctx,
|
if _, err := tx.Exec(ctx,
|
||||||
`UPDATE activities SET ended_at = $2, attrs = attrs - 'open' WHERE id = $1`,
|
`UPDATE activities SET ended_at = $2, attrs = attrs - 'open' WHERE id = $1`,
|
||||||
cur.ID, at); err != nil {
|
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
|
if _, err := tx.Exec(ctx, `INSERT INTO activities
|
||||||
(device_id, source, kind, label, started_at, ended_at, attrs, external_id)
|
(device_id, source, kind, label, started_at, ended_at, attrs, external_id)
|
||||||
VALUES ($1, $2, $3, $4, $5, $5, '{"open": true}', $6)`,
|
VALUES ($1, $2, $3, $4, $5, $5, '{"open": true}', $6)`,
|
||||||
deviceID, ingest.LocationSource, ingest.PlaceKind, label, at,
|
deviceID, ingest.LocationSource, ingest.PlaceKind, label, at,
|
||||||
fmt.Sprintf("%d|%s|%s", deviceID, label, at.Format(time.RFC3339Nano))); err != nil {
|
fmt.Sprintf("move|%d|%d", deviceID, cur.ID)); err != nil {
|
||||||
return false, err
|
return "", false, err
|
||||||
}
|
}
|
||||||
return true, tx.Commit(ctx)
|
return label, 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 {
|
type openPlace struct {
|
||||||
@@ -171,11 +169,9 @@ type openPlace struct {
|
|||||||
StartedAt time.Time
|
StartedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
func currentPlace(ctx context.Context, q interface {
|
func currentPlace(ctx context.Context, tx pgx.Tx, deviceID int64) (openPlace, error) {
|
||||||
QueryRow(context.Context, string, ...any) pgx.Row
|
|
||||||
}, deviceID int64) (openPlace, error) {
|
|
||||||
var p openPlace
|
var p openPlace
|
||||||
err := q.QueryRow(ctx,
|
err := tx.QueryRow(ctx,
|
||||||
`SELECT id, label, started_at FROM activities
|
`SELECT id, label, started_at FROM activities
|
||||||
WHERE device_id = $1 AND source = $2 AND attrs ? 'open'`,
|
WHERE device_id = $1 AND source = $2 AND attrs ? 'open'`,
|
||||||
deviceID, ingest.LocationSource).Scan(&p.ID, &p.Label, &p.StartedAt)
|
deviceID, ingest.LocationSource).Scan(&p.ID, &p.Label, &p.StartedAt)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user