From f4ce04875ce3dc4b2df27b24f08f7342e610a50a Mon Sep 17 00:00:00 2001 From: Adam French Date: Wed, 14 Oct 2026 20:38:02 +0100 Subject: [PATCH] Add activity tracker server, Hyprland agent and Gitea image publishing The Go API on PostgreSQL ingests desktop, browser, presence, manual and Health Auto Export events and serves activities and daily goal summaries. The Hyprland agent records window focus, idle and lock intervals. The CI workflow publishes adam-french.co.uk/adamf/activity-tracker to the Gitea registry and rolls the web_server stack onto it. The image probes itself through a new `tracker healthcheck` command, because distroless has no wget. Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 2 + .gitea/workflows/ci.yaml | 120 +++++++++++++ .gitignore | 2 + Makefile | 34 ++++ README.md | 165 ++++++++++++++++++ cmd/hypr-agent/main.go | 172 +++++++++++++++++++ cmd/tracker/main.go | 256 +++++++++++++++++++++++++++ deploy/Dockerfile | 21 +++ deploy/docker-compose.yml | 35 ++++ deploy/systemd/hypr-agent.service | 19 +++ go.mod | 19 +++ go.sum | 51 ++++++ internal/agent/hypr/buffer.go | 120 +++++++++++++ internal/agent/hypr/control.go | 90 ++++++++++ internal/agent/hypr/hypr_test.go | 95 +++++++++++ internal/agent/hypr/hyprland.go | 142 +++++++++++++++ internal/agent/hypr/session.go | 115 +++++++++++++ internal/agent/hypr/uploader.go | 94 ++++++++++ internal/api/api.go | 256 +++++++++++++++++++++++++++ internal/api/api_test.go | 119 +++++++++++++ internal/config/config.go | 43 +++++ internal/ingest/hae.go | 156 +++++++++++++++++ internal/ingest/ingest.go | 129 ++++++++++++++ internal/ingest/ingest_test.go | 72 ++++++++ internal/migrations/00001_init.sql | 74 ++++++++ internal/migrations/migrations.go | 30 ++++ internal/store/store.go | 266 +++++++++++++++++++++++++++++ internal/summary/summary.go | 70 ++++++++ internal/summary/summary_test.go | 43 +++++ 29 files changed, 2810 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitea/workflows/ci.yaml create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 cmd/hypr-agent/main.go create mode 100644 cmd/tracker/main.go create mode 100644 deploy/Dockerfile create mode 100644 deploy/docker-compose.yml create mode 100644 deploy/systemd/hypr-agent.service create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/agent/hypr/buffer.go create mode 100644 internal/agent/hypr/control.go create mode 100644 internal/agent/hypr/hypr_test.go create mode 100644 internal/agent/hypr/hyprland.go create mode 100644 internal/agent/hypr/session.go create mode 100644 internal/agent/hypr/uploader.go create mode 100644 internal/api/api.go create mode 100644 internal/api/api_test.go create mode 100644 internal/config/config.go create mode 100644 internal/ingest/hae.go create mode 100644 internal/ingest/ingest.go create mode 100644 internal/ingest/ingest_test.go create mode 100644 internal/migrations/00001_init.sql create mode 100644 internal/migrations/migrations.go create mode 100644 internal/store/store.go create mode 100644 internal/summary/summary.go create mode 100644 internal/summary/summary_test.go diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..d370ee8 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,2 @@ +.git +bin diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml new file mode 100644 index 0000000..a79b3f3 --- /dev/null +++ b/.gitea/workflows/ci.yaml @@ -0,0 +1,120 @@ +# ============================================================================= +# ci.yaml — test every push; publish an image for pushes to main that pass. +# +# Modelled on job-tracker's ci.yaml and run by the same runner: a self-hosted +# act_runner on the Pi (stppi) in HOST mode, with git and docker and no other +# toolchain. So Go runs in a `docker run` container, and the source is +# fetched with plain git rather than actions/checkout (which needs Node on +# the host). +# +# TWO JOBS +# test go vet + go test, as `make test`. The API tests skip themselves +# here: they need TEST_DATABASE_URL, and CI has no Postgres. +# publish main only, after test: builds deploy/Dockerfile, pushes it to +# this Gitea's container registry as : and :latest, then +# pulls it into the web_server stack (its `activity-tracker` +# service) and waits for it to be healthy. +# +# SECRETS (repo settings -> Actions -> Secrets) +# REGISTRY_USER a Gitea user that can write packages for adamf +# REGISTRY_TOKEN that user's access token with the write:package scope +# ============================================================================= +name: Test and publish + +on: + push: + +env: + IMAGE: adam-french.co.uk/adamf/activity-tracker + +jobs: + test: + runs-on: self-hosted + env: + SHA: ${{ github.sha }} + REF: ${{ github.ref }} + REMOTE: ssh://git@localhost:2222/adamf/ccp.git + GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no" + CACHE: /home/adamf/.cache/activity-tracker-ci/repo.git + SRC: /home/adamf/.cache/activity-tracker-ci/src-${{ github.sha }} + steps: + - name: Export the pushed commit to a scratch directory + shell: bash + run: | + set -eu + mkdir -p "$(dirname "$CACHE")" + [ -d "$CACHE" ] || git init --quiet --bare "$CACHE" + git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF" + rm -rf "$SRC" + mkdir -p "$SRC" + git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC" + test -f "$SRC/go.mod" + + # Read-only source, and named volumes for the module and build + # caches so repeat runs don't download everything again. + - name: Go - vet and test + shell: bash + run: | + set -eu + docker run --rm \ + -v "$SRC":/src:ro -w /src \ + -v activity_tracker_ci_gomod:/go/pkg/mod \ + -v activity_tracker_ci_gobuild:/root/.cache/go-build \ + golang:1.27 \ + sh -c 'go vet ./... && go test ./...' + + - name: Remove the scratch directory + if: always() + shell: bash + run: rm -rf "$SRC" + + publish: + needs: test + if: github.ref == 'refs/heads/main' + runs-on: self-hosted + env: + SHA: ${{ github.sha }} + CACHE: /home/adamf/.cache/activity-tracker-ci/repo.git + SRC: /home/adamf/.cache/activity-tracker-ci/publish-${{ github.sha }} + REGISTRY_USER: ${{ secrets.REGISTRY_USER }} + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + steps: + - name: Build and push the image + shell: bash + run: | + set -eu + rm -rf "$SRC" && mkdir -p "$SRC" + git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC" + printf '%s' "$REGISTRY_TOKEN" | docker login adam-french.co.uk -u "$REGISTRY_USER" --password-stdin + # Built natively on the Pi, so the image is arm64 — the only + # platform it runs on. + docker build -f "$SRC/deploy/Dockerfile" -t "$IMAGE:$SHA" -t "$IMAGE:latest" "$SRC" + docker push "$IMAGE:$SHA" + docker push "$IMAGE:latest" + + - name: Remove the scratch directory + if: always() + shell: bash + run: rm -rf "$SRC" + + # Put the new image live, exactly as job-tracker does: pull and + # recreate only this service, under the lock web_server's deploy + # and env-apply hold while they run compose. A pinned + # ACTIVITY_TRACKER_IMAGE_TAG in the site's .env makes this a no-op. + - name: Roll the site onto the new image + working-directory: /home/adamf/deploy/web_server + env: + DOCKER_API_VERSION: "1.41" + shell: bash + run: | + set -eu + flock env-apply/run/lock sh -c 'docker compose pull activity-tracker && docker compose up -d --no-deps activity-tracker' + for i in $(seq 1 30); do + status=$(docker inspect -f '{{.State.Health.Status}}' activity-tracker) + echo "activity-tracker: $status" + [ "$status" = healthy ] && exit 0 + [ "$status" = unhealthy ] && break + sleep 5 + done + docker logs --tail 50 activity-tracker + exit 1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3ec7838 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +bin/ +*.test diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..d7e94e5 --- /dev/null +++ b/Makefile @@ -0,0 +1,34 @@ +COMPOSE := docker compose -f deploy/docker-compose.yml +DEV_DB := postgres://tracker:tracker@localhost:5432/tracker?sslmode=disable + +.PHONY: build test test-integration run up down docker migrate install-agent + +build: + go build -o bin/ ./cmd/... + +test: + go test ./... + +# Runs the API tests against the compose Postgres (make up first). +test-integration: + TEST_DATABASE_URL='$(DEV_DB)' go test -count=1 ./... + +run: + DATABASE_URL='$(DEV_DB)' go run ./cmd/tracker serve + +up: + $(COMPOSE) up -d --build + +down: + $(COMPOSE) down + +docker: + docker build -f deploy/Dockerfile -t activity-tracker . + +migrate: + DATABASE_URL='$(DEV_DB)' go run ./cmd/tracker migrate + +install-agent: + go build -o $(HOME)/.local/bin/hypr-agent ./cmd/hypr-agent + install -Dm644 deploy/systemd/hypr-agent.service $(HOME)/.config/systemd/user/hypr-agent.service + systemctl --user daemon-reload diff --git a/README.md b/README.md index e69de29..a046a25 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,165 @@ +# 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". + +``` +[hypr-agent] [browser ext] [webcam agent] [Health Auto Export] + └────────── HTTPS + Bearer API key (batched JSON) ─────────┘ + │ + 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. + +## Status + +| Collector | Status | +|---|---| +| Hyprland (`cmd/hypr-agent`) | ✅ built | +| Apple Health (Health Auto Export → `/health/hae`) | ✅ endpoint built; configure the app | +| Browser extension (`/browser/events`) | endpoint ready, extension not yet written | +| Webcam presence (`/presence/events`) | endpoint ready, agent not yet written | +| AI analysis (`reports` table) | planned | + +## Running the server + +```sh +make up # builds the image and starts tracker + a dev Postgres on :8080 / :5432 +curl localhost:8080/readyz +``` + +In production, run only the image and point it at your own database: + +```sh +docker build -f deploy/Dockerfile -t activity-tracker . +docker run -d -p 8080:8080 \ + -e DATABASE_URL='postgres://user:pass@db-host:5432/tracker' \ + -e TRACKER_TZ='Europe/London' \ + activity-tracker +``` + +| Env var | Default | | +|---|---|---| +| `DATABASE_URL` | (required) | PostgreSQL connection string | +| `LISTEN_ADDR` | `:8080` | | +| `AUTO_MIGRATE` | `true` | Apply migrations on startup. Set it to false to run `tracker migrate` yourself | +| `TRACKER_TZ` | `UTC` | Timezone that defines "a day" in summaries | + +Put the service behind your reverse proxy (Caddy, Traefik and so on) for TLS, because API keys are sent as bearer tokens. + +### Deploying to stppi + +Pushing to `main` on Gitea (`adamf/ccp`) runs `.gitea/workflows/ci.yaml` on the Pi's runner. The workflow runs the tests, pushes `adam-french.co.uk/adamf/activity-tracker:` and `:latest` to Gitea's container registry, and recreates the `activity-tracker` service in the web_server stack. The service is served at `https://www.adam-french.co.uk/tracker/`, so set collectors to `TRACKER_URL=https://www.adam-french.co.uk/tracker`. Use the `www` host because the apex redirect would turn uploaded POSTs into GETs. To hold a version, set `ACTIVITY_TRACKER_IMAGE_TAG` to a sha in web_server's `.env`. + +The repo needs the `REGISTRY_USER` and `REGISTRY_TOKEN` Actions secrets, the same ones job-tracker uses. Create its database role once on the Pi: + +```sh +docker exec db psql -U "$POSTGRES_USER" -d postgres \ + -c "CREATE ROLE tracker LOGIN PASSWORD '…'" -c "CREATE DATABASE tracker OWNER tracker" +``` + +Then run the admin commands with `docker exec activity-tracker tracker apikey create …`. + +### Admin commands + +The admin commands are built into the same binary. Inside the container, run them with `docker exec tracker …`. + +```sh +tracker apikey create --name laptop-hypr --kind hyprland # prints the key once +tracker apikey list +tracker apikey revoke --name laptop-hypr + +tracker goal add --kind tab_focus --label youtube.com --op '<=' --target 1h +tracker goal add --kind walk --op '>=' --target 30m # empty label = any walk +tracker goal list +tracker goal rm --id 2 +``` + +## API + +All `/api/v1` routes require `Authorization: Bearer `. + +| Method | Path | Accepted kinds | +|---|---|---| +| POST | `/api/v1/desktop/events` | `app_focus`, `idle`, `locked` | +| POST | `/api/v1/browser/events` | `tab_focus`, `idle` | +| POST | `/api/v1/presence/events` | `at_desk`, `in_bed`, `away` | +| POST | `/api/v1/manual/events` | any | +| POST | `/api/v1/health/hae` | Health Auto Export JSON. Workouts and sleep become activities; other metrics become samples | +| GET | `/api/v1/activities?from=&to=&source=&kind=&limit=` | RFC3339 times; defaults to the last 24h | +| GET | `/api/v1/summary/daily?date=YYYY-MM-DD` | totals per label and kind, plus goal results | +| GET | `/healthz`, `/readyz` | no auth | + +The event batch format is shared by all `*/events` endpoints. A batch holds at most 1000 events. + +```json +{"events": [ + {"id": "3f2a…", "kind": "app_focus", "label": "kitty", + "started_at": "2026-10-14T09:00:00Z", "ended_at": "2026-10-14T09:42:10Z", + "attrs": {"title": "nvim"}} +]} +``` + +The response is `{"received": 1, "inserted": 1}`. If `inserted` is lower than `received`, the missing events were duplicates. + +## Hyprland agent + +The agent follows `activewindow` events on Hyprland's event socket and records one interval for each window class and title. Focus that lasts under 2s is dropped. hypridle hooks mark idle and locked time. Pending events are kept in `$XDG_STATE_HOME/hypr-agent/buffer.jsonl` and uploaded every minute, so nothing is lost while the server is unreachable. + +```sh +tracker apikey create --name laptop-hypr --kind hyprland # on the server +make install-agent # builds into ~/.local/bin and installs the user unit +mkdir -p ~/.config/hypr-agent +cat > ~/.config/hypr-agent/env <`. 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`. + +## Development + +```sh +make test # unit tests +make up && make test-integration # also runs the API tests against the compose Postgres (truncates its tables!) +make run # run the server locally against the compose Postgres +``` + +Layout: `cmd/tracker` (server and admin CLI), `cmd/hypr-agent`, `internal/{api,ingest,store,summary,migrations,config}`, `internal/agent/hypr`, `deploy/`. + +## Roadmap + +1. Browser extension (MV3, Firefox and Chromium). It will send hostnames by default and full URLs only if you opt in. +2. Webcam presence agent. Detection will run on the device and only intervals will be uploaded; frames never leave the machine. +3. Nudges: push notifications through ntfy when a goal is at risk during the day. +4. Location: an OwnTracks or Home Assistant geofence will provide reliable "time outside" intervals. +5. 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`. diff --git a/cmd/hypr-agent/main.go b/cmd/hypr-agent/main.go new file mode 100644 index 0000000..b7b57e8 --- /dev/null +++ b/cmd/hypr-agent/main.go @@ -0,0 +1,172 @@ +// Command hypr-agent records focused-window time on Hyprland and uploads it +// to the tracker server. +// +// hypr-agent run run the collector (usually via systemd --user) +// hypr-agent idle|resume sent by hypridle on-timeout / on-resume +// hypr-agent lock|unlock sent around your screen locker +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "log/slog" + "net/http" + "os" + "os/signal" + "path/filepath" + "regexp" + "strconv" + "strings" + "syscall" + "time" + + "ccp/internal/agent/hypr" + "ccp/internal/ingest" +) + +func main() { + if len(os.Args) < 2 { + fmt.Fprintln(os.Stderr, "usage: hypr-agent run|idle|resume|lock|unlock [flags]") + os.Exit(2) + } + var err error + switch cmd := os.Args[1]; { + case cmd == "run": + err = run(os.Args[2:]) + case hypr.Commands[cmd]: + err = hypr.SendControl(cmd) + default: + err = fmt.Errorf("unknown command %q", cmd) + } + if err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } +} + +func run(args []string) error { + fs := flag.NewFlagSet("run", flag.ContinueOnError) + server := fs.String("server", os.Getenv("TRACKER_URL"), "tracker server base URL [TRACKER_URL]") + key := fs.String("key", os.Getenv("TRACKER_API_KEY"), "API key [TRACKER_API_KEY]") + keyFile := fs.String("key-file", os.Getenv("TRACKER_API_KEY_FILE"), "file containing the API key [TRACKER_API_KEY_FILE]") + titles := fs.Bool("titles", envBool("HYPR_AGENT_TITLES", true), "record window titles [HYPR_AGENT_TITLES]") + redact := fs.String("redact", os.Getenv("HYPR_AGENT_REDACT"), "regexp; matching titles are replaced with [redacted] [HYPR_AGENT_REDACT]") + minDur := fs.Duration("min-duration", 2*time.Second, "drop focus intervals shorter than this") + flush := fs.Duration("flush", time.Minute, "upload interval") + bufPath := fs.String("buffer", defaultBufferPath(), "pending-events file") + if err := fs.Parse(args); err != nil { + return err + } + + if *server == "" { + return errors.New("--server (or TRACKER_URL) is required") + } + if *keyFile != "" { + b, err := os.ReadFile(*keyFile) + if err != nil { + return err + } + *key = strings.TrimSpace(string(b)) + } + if *key == "" { + return errors.New("--key, --key-file, TRACKER_API_KEY or TRACKER_API_KEY_FILE is required") + } + var redactRe *regexp.Regexp + if *redact != "" { + var err error + if redactRe, err = regexp.Compile(*redact); err != nil { + return fmt.Errorf("--redact: %w", err) + } + } + + log := slog.New(slog.NewTextHandler(os.Stderr, nil)) + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + buf, err := hypr.OpenBuffer(*bufPath) + if err != nil { + return fmt.Errorf("open buffer: %w", err) + } + up := &hypr.Uploader{ + URL: *server, + Key: *key, + Buf: buf, + Client: &http.Client{Timeout: 15 * time.Second}, + Log: log, + } + sess := &hypr.Sessionizer{ + MinDuration: *minDur, + Emit: func(e ingest.Event) { + if err := buf.Add(e); err != nil { + log.Error("buffer event", "err", err) + } + }, + } + cleanTitle := func(f hypr.Focus) hypr.Focus { + switch { + case !*titles: + f.Title = "" + case redactRe != nil && redactRe.MatchString(f.Title): + f.Title = "[redacted]" + } + return f + } + + focus := make(chan hypr.FocusEvent, 64) + control := make(chan hypr.ControlEvent, 8) + errc := make(chan error, 2) + go func() { errc <- hypr.Listen(ctx, focus, log) }() + go func() { errc <- hypr.ServeControl(ctx, control) }() + go up.Run(ctx, *flush) + + log.Info("hypr-agent started", "server", *server, "pending", buf.Len()) +loop: + for { + select { + case <-ctx.Done(): + break loop + case err := <-errc: + if err != nil { + stop() + return err + } + case f := <-focus: + sess.Focus(f.At, cleanTitle(f.Focus)) + case c := <-control: + switch c.Command { + case "idle": + sess.Pause(c.At, "idle") + case "lock": + sess.Pause(c.At, "locked") + case "resume", "unlock": + sess.Resume(c.At) + } + } + } + + sess.Close(time.Now()) + flushCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := up.Flush(flushCtx); err != nil { + log.Warn("final upload failed; events kept for next run", "err", err, "pending", buf.Len()) + } + return nil +} + +func defaultBufferPath() string { + dir := os.Getenv("XDG_STATE_HOME") + if dir == "" { + home, _ := os.UserHomeDir() + dir = filepath.Join(home, ".local", "state") + } + return filepath.Join(dir, "hypr-agent", "buffer.jsonl") +} + +func envBool(key string, def bool) bool { + if v, err := strconv.ParseBool(os.Getenv(key)); err == nil { + return v + } + return def +} diff --git a/cmd/tracker/main.go b/cmd/tracker/main.go new file mode 100644 index 0000000..273bf9e --- /dev/null +++ b/cmd/tracker/main.go @@ -0,0 +1,256 @@ +// Command tracker runs the activity tracker server and its admin commands. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "strconv" + "syscall" + "text/tabwriter" + "time" + _ "time/tzdata" // the distroless image has no zoneinfo + + "github.com/jackc/pgx/v5/pgxpool" + + "ccp/internal/api" + "ccp/internal/config" + "ccp/internal/migrations" + "ccp/internal/store" +) + +const usage = `usage: tracker [flags] + +commands: + serve run the HTTP server + migrate apply database migrations and exit + healthcheck exit 0 if the local server is ready (for Docker HEALTHCHECK) + apikey create --name NAME --kind KIND register a device and print its API key + apikey list list devices + apikey revoke --name NAME revoke a device's API key + goal add --kind KIND [--label L] --op '>=|<=' --target DURATION + goal list + goal rm --id ID +` + +func main() { + if len(os.Args) < 2 { + fmt.Fprint(os.Stderr, usage) + os.Exit(2) + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + if err := run(ctx, os.Args[1], os.Args[2:]); err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } +} + +func run(ctx context.Context, cmd string, args []string) error { + // Handled before config.Load: the probe needs no database of its own, only + // the listen address, and the distroless image has no wget or curl to do it. + if cmd == "healthcheck" { + return healthcheck(ctx) + } + + cfg, err := config.Load() + if err != nil { + return err + } + pool, err := pgxpool.New(ctx, cfg.DatabaseURL) + if err != nil { + return fmt.Errorf("connect database: %w", err) + } + defer pool.Close() + st := store.New(pool) + + switch cmd { + case "serve": + return serve(ctx, cfg, pool, st) + case "migrate": + return migrations.Up(ctx, pool) + case "apikey": + return apikeyCmd(ctx, st, args) + case "goal": + return goalCmd(ctx, st, args) + default: + fmt.Fprint(os.Stderr, usage) + return fmt.Errorf("unknown command %q", cmd) + } +} + +func serve(ctx context.Context, cfg config.Config, pool *pgxpool.Pool, st *store.Store) error { + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + + if cfg.AutoMigrate { + if err := migrations.Up(ctx, pool); err != nil { + return err + } + log.Info("migrations applied") + } + + srv := &http.Server{ + Addr: cfg.ListenAddr, + Handler: api.New(st, cfg.Location, log), + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 60 * time.Second, + WriteTimeout: 60 * time.Second, + } + + errc := make(chan error, 1) + go func() { + log.Info("listening", "addr", cfg.ListenAddr, "tz", cfg.Location.String()) + errc <- srv.ListenAndServe() + }() + + select { + case err := <-errc: + return err + case <-ctx.Done(): + } + log.Info("shutting down") + shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return srv.Shutdown(shutdownCtx) +} + +// healthcheck asks the server in this container for /readyz, which also pings +// the database, so "healthy" means the tracker can actually store events. +func healthcheck(ctx context.Context) error { + addr := os.Getenv("LISTEN_ADDR") + if addr == "" { + addr = ":8080" + } + host, port, err := net.SplitHostPort(addr) + if err != nil { + return fmt.Errorf("LISTEN_ADDR: %w", err) + } + if host == "" || host == "0.0.0.0" || host == "::" { + host = "localhost" + } + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+net.JoinHostPort(host, port)+"/readyz", nil) + if err != nil { + return err + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + return err + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("readyz: %s", resp.Status) + } + return nil +} + +func apikeyCmd(ctx context.Context, st *store.Store, args []string) error { + if len(args) == 0 { + return errors.New("apikey needs a subcommand: create, list, revoke") + } + fs := flag.NewFlagSet("apikey "+args[0], flag.ContinueOnError) + name := fs.String("name", "", "device name, e.g. laptop-hypr") + kind := fs.String("kind", "", "collector kind, e.g. hyprland, browser, health, presence") + if err := fs.Parse(args[1:]); err != nil { + return err + } + + switch args[0] { + case "create": + if *name == "" || *kind == "" { + return errors.New("--name and --kind are required") + } + d, key, err := st.CreateDevice(ctx, *name, *kind) + if err != nil { + return err + } + fmt.Printf("device %q (id %d) created.\nAPI key (shown once): %s\n", d.Name, d.ID, key) + case "list": + devs, err := st.ListDevices(ctx) + if err != nil { + return err + } + tw := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0) + fmt.Fprintln(tw, "ID\tNAME\tKIND\tLAST SEEN\tSTATUS") + for _, d := range devs { + seen, status := "never", "active" + if d.LastSeenAt != nil { + seen = d.LastSeenAt.Local().Format(time.DateTime) + } + if d.RevokedAt != nil { + status = "revoked" + } + fmt.Fprintf(tw, "%d\t%s\t%s\t%s\t%s\n", d.ID, d.Name, d.Kind, seen, status) + } + return tw.Flush() + case "revoke": + if *name == "" { + return errors.New("--name is required") + } + if err := st.RevokeDevice(ctx, *name); err != nil { + return err + } + fmt.Printf("device %q revoked\n", *name) + default: + return fmt.Errorf("unknown apikey subcommand %q", args[0]) + } + return nil +} + +func goalCmd(ctx context.Context, st *store.Store, args []string) error { + if len(args) == 0 { + return errors.New("goal needs a subcommand: add, list, rm") + } + fs := flag.NewFlagSet("goal "+args[0], flag.ContinueOnError) + kind := fs.String("kind", "", "activity kind, e.g. tab_focus, walk, at_desk") + label := fs.String("label", "", "optional label, e.g. youtube.com (empty = any)") + op := fs.String("op", "", "'>=' (at least) or '<=' (at most)") + target := fs.Duration("target", 0, "daily target, e.g. 1h30m") + id := fs.String("id", "", "goal id") + if err := fs.Parse(args[1:]); err != nil { + return err + } + + switch args[0] { + case "add": + if *kind == "" || (*op != ">=" && *op != "<=") || *target <= 0 { + return errors.New("--kind, --op ('>=' or '<=') and --target are required") + } + g, err := st.CreateGoal(ctx, store.Goal{Kind: *kind, Label: *label, Op: *op, TargetS: int64(target.Seconds())}) + if err != nil { + return err + } + fmt.Printf("goal %d added\n", g.ID) + case "list": + goals, err := st.Goals(ctx) + if err != nil { + return err + } + tw := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0) + fmt.Fprintln(tw, "ID\tKIND\tLABEL\tOP\tTARGET/DAY") + for _, g := range goals { + fmt.Fprintf(tw, "%d\t%s\t%s\t%s\t%s\n", g.ID, g.Kind, g.Label, g.Op, time.Duration(g.TargetS)*time.Second) + } + return tw.Flush() + case "rm": + n, err := strconv.ParseInt(*id, 10, 64) + if err != nil { + return errors.New("--id must be a number") + } + if err := st.DeleteGoal(ctx, n); err != nil { + return err + } + fmt.Printf("goal %d removed\n", n) + default: + return fmt.Errorf("unknown goal subcommand %q", args[0]) + } + return nil +} diff --git a/deploy/Dockerfile b/deploy/Dockerfile new file mode 100644 index 0000000..8ac17f2 --- /dev/null +++ b/deploy/Dockerfile @@ -0,0 +1,21 @@ +# Build from the repo root: docker build -f deploy/Dockerfile -t activity-tracker . +# +# Multi-arch by construction: both base images are published for arm64, and +# the Pi's CI (.gitea/workflows/ci.yaml) builds natively there. No +# `RUN --mount` cache lines, so it also builds on the Pi's legacy builder. +FROM golang:1.27 AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/tracker ./cmd/tracker + +FROM gcr.io/distroless/static-debian12:nonroot +COPY --from=build /out/tracker /usr/local/bin/tracker +EXPOSE 8080 +# distroless has no shell or wget, so the binary probes its own /readyz +# (process up and database reachable). +HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \ + CMD ["/usr/local/bin/tracker", "healthcheck"] +ENTRYPOINT ["/usr/local/bin/tracker"] +CMD ["serve"] diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml new file mode 100644 index 0000000..4ba70fb --- /dev/null +++ b/deploy/docker-compose.yml @@ -0,0 +1,35 @@ +# Local development stack. In production, run only the `tracker` service and +# point DATABASE_URL at your external PostgreSQL. +services: + tracker: + image: activity-tracker + build: + context: .. + dockerfile: deploy/Dockerfile + environment: + DATABASE_URL: postgres://tracker:tracker@postgres:5432/tracker?sslmode=disable + TRACKER_TZ: ${TRACKER_TZ:-UTC} + ports: + - "8080:8080" + depends_on: + postgres: + condition: service_healthy + restart: unless-stopped + + postgres: + image: postgres:17 + environment: + POSTGRES_USER: tracker + POSTGRES_PASSWORD: tracker + POSTGRES_DB: tracker + ports: + - "5432:5432" + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U tracker"] + interval: 2s + retries: 15 + +volumes: + pgdata: diff --git a/deploy/systemd/hypr-agent.service b/deploy/systemd/hypr-agent.service new file mode 100644 index 0000000..af00e81 --- /dev/null +++ b/deploy/systemd/hypr-agent.service @@ -0,0 +1,19 @@ +# Install: +# cp deploy/systemd/hypr-agent.service ~/.config/systemd/user/ +# systemctl --user daemon-reload && systemctl --user enable --now hypr-agent +# +# ~/.config/hypr-agent/env must contain TRACKER_URL and TRACKER_API_KEY (or +# TRACKER_API_KEY_FILE), and optionally HYPR_AGENT_TITLES / HYPR_AGENT_REDACT. +[Unit] +Description=Hyprland activity tracker agent +PartOf=graphical-session.target +After=graphical-session.target + +[Service] +EnvironmentFile=%h/.config/hypr-agent/env +ExecStart=%h/.local/bin/hypr-agent run +Restart=on-failure +RestartSec=5 + +[Install] +WantedBy=graphical-session.target diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..35815c6 --- /dev/null +++ b/go.mod @@ -0,0 +1,19 @@ +module ccp + +go 1.27.0 + +require ( + github.com/jackc/pgx/v5 v5.11.0 + github.com/pressly/goose/v3 v3.29.0 +) + +require ( + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.3 // indirect + github.com/mfridman/interpolate v0.0.2 // indirect + github.com/sethvargo/go-retry v0.5.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/text v0.43.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..43517a1 --- /dev/null +++ b/go.sum @@ -0,0 +1,51 @@ +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/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= +github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= +github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= +github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pressly/goose/v3 v3.29.0 h1:dtEnBCT7CqkHIUCdgrXsrmeisaN8gFkRU4Y5OEwif4o= +github.com/pressly/goose/v3 v3.29.0/go.mod h1:plA4aP4+u+Q3FMTgbFbhF8TuAWpAdfWpoFGkJsIFWh0= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= +github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +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/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +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/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +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= +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= +modernc.org/libc v1.78.0 h1:Lpm+e9K6ruVYEGwWfuBO1xXtYEaXDouFOG1SuWjFDP4= +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/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/sqlite v1.60.1 h1:/blz53O951KWFOso4QQvEs/Fq6cDBKLtMVrYNSeJVKw= +modernc.org/sqlite v1.60.1/go.mod h1:1dIoEagfDE72QytD5scH1lxARtaUgKgHC/NuApA27r0= diff --git a/internal/agent/hypr/buffer.go b/internal/agent/hypr/buffer.go new file mode 100644 index 0000000..1ef4f41 --- /dev/null +++ b/internal/agent/hypr/buffer.go @@ -0,0 +1,120 @@ +package hypr + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sync" + + "ccp/internal/ingest" +) + +// Buffer holds events that haven't been uploaded yet, persisted as JSONL so +// they survive restarts and server outages. +type Buffer struct { + mu sync.Mutex + path string + pending []ingest.Event +} + +// OpenBuffer loads any events left over from a previous run. Corrupt lines +// (e.g. from a crash mid-write) are skipped. +func OpenBuffer(path string) (*Buffer, error) { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return nil, err + } + b := &Buffer{path: path} + + f, err := os.Open(path) + if errors.Is(err, os.ErrNotExist) { + return b, nil + } + if err != nil { + return nil, err + } + defer f.Close() + + sc := bufio.NewScanner(f) + sc.Buffer(make([]byte, 64*1024), 1024*1024) + for sc.Scan() { + var e ingest.Event + if json.Unmarshal(sc.Bytes(), &e) == nil && e.ID != "" { + b.pending = append(b.pending, e) + } + } + return b, sc.Err() +} + +// Add appends an event to the buffer and its file. +func (b *Buffer) Add(e ingest.Event) error { + line, err := json.Marshal(e) + if err != nil { + return err + } + b.mu.Lock() + defer b.mu.Unlock() + + f, err := os.OpenFile(b.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) + if err != nil { + return err + } + defer f.Close() + if _, err := f.Write(append(line, '\n')); err != nil { + return err + } + b.pending = append(b.pending, e) + return nil +} + +// Peek returns up to max of the oldest pending events. +func (b *Buffer) Peek(max int) []ingest.Event { + b.mu.Lock() + defer b.mu.Unlock() + n := min(max, len(b.pending)) + return append([]ingest.Event(nil), b.pending[:n]...) +} + +// Ack drops the n oldest events and rewrites the file. +func (b *Buffer) Ack(n int) error { + b.mu.Lock() + defer b.mu.Unlock() + if n > len(b.pending) { + return fmt.Errorf("ack %d of %d pending events", n, len(b.pending)) + } + b.pending = b.pending[n:] + return b.rewrite() +} + +func (b *Buffer) Len() int { + b.mu.Lock() + defer b.mu.Unlock() + return len(b.pending) +} + +// rewrite atomically replaces the file with the pending events. +func (b *Buffer) rewrite() error { + tmp := b.path + ".tmp" + f, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) + if err != nil { + return err + } + w := bufio.NewWriter(f) + enc := json.NewEncoder(w) + for _, e := range b.pending { + if err := enc.Encode(e); err != nil { + f.Close() + return err + } + } + if err := w.Flush(); err != nil { + f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(tmp, b.path) +} diff --git a/internal/agent/hypr/control.go b/internal/agent/hypr/control.go new file mode 100644 index 0000000..bf1ec96 --- /dev/null +++ b/internal/agent/hypr/control.go @@ -0,0 +1,90 @@ +package hypr + +import ( + "bufio" + "context" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "strings" + "time" +) + +// Control commands sent by hypridle hooks via `hypr-agent `. +var Commands = map[string]bool{"idle": true, "resume": true, "lock": true, "unlock": true} + +// ControlEvent is a control command stamped with when it was received. +type ControlEvent struct { + Command string + At time.Time +} + +// ControlSocketPath is where the running agent listens for control commands. +func ControlSocketPath() string { + dir := os.Getenv("XDG_RUNTIME_DIR") + if dir == "" { + dir = os.TempDir() + } + return filepath.Join(dir, "hypr-agent.sock") +} + +// ServeControl accepts one-line commands on the control socket until ctx is +// cancelled. +func ServeControl(ctx context.Context, out chan<- ControlEvent) error { + path := ControlSocketPath() + os.Remove(path) // stale socket from a previous run + ln, err := net.Listen("unix", path) + if err != nil { + return err + } + go func() { + <-ctx.Done() + ln.Close() + }() + + for { + conn, err := ln.Accept() + if err != nil { + if ctx.Err() != nil { + return nil + } + return err + } + go func() { + defer conn.Close() + conn.SetDeadline(time.Now().Add(2 * time.Second)) + line, _ := bufio.NewReader(conn).ReadString('\n') + cmd := strings.TrimSpace(line) + if !Commands[cmd] { + fmt.Fprintf(conn, "unknown command %q\n", cmd) + return + } + out <- ControlEvent{Command: cmd, At: time.Now()} + fmt.Fprintln(conn, "ok") + }() + } +} + +// SendControl sends a command to the running agent. +func SendControl(cmd string) error { + conn, err := net.DialTimeout("unix", ControlSocketPath(), 2*time.Second) + if err != nil { + return fmt.Errorf("is hypr-agent running? %w", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(2 * time.Second)) + + if _, err := fmt.Fprintln(conn, cmd); err != nil { + return err + } + reply, err := bufio.NewReader(conn).ReadString('\n') + if err != nil { + return err + } + if reply = strings.TrimSpace(reply); reply != "ok" { + return errors.New(reply) + } + return nil +} diff --git a/internal/agent/hypr/hypr_test.go b/internal/agent/hypr/hypr_test.go new file mode 100644 index 0000000..ff5e600 --- /dev/null +++ b/internal/agent/hypr/hypr_test.go @@ -0,0 +1,95 @@ +package hypr + +import ( + "path/filepath" + "testing" + "time" + + "ccp/internal/ingest" +) + +func TestParseActiveWindow(t *testing.T) { + event, data, ok := ParseLine("activewindow>>firefox,Inbox, 3 unread - Mozilla Firefox") + if !ok || event != "activewindow" { + t.Fatalf("ParseLine: got %q %v", event, ok) + } + got := ParseActiveWindow(data) + want := Focus{Class: "firefox", Title: "Inbox, 3 unread - Mozilla Firefox"} + if got != want { + t.Fatalf("got %+v, want %+v", got, want) + } + if got := ParseActiveWindow(","); got != (Focus{}) { + t.Fatalf("empty focus: got %+v", got) + } +} + +func TestSessionizer(t *testing.T) { + t0 := time.Date(2026, 10, 14, 9, 0, 0, 0, time.UTC) + at := func(sec int) time.Time { return t0.Add(time.Duration(sec) * time.Second) } + + var got []ingest.Event + s := &Sessionizer{MinDuration: 2 * time.Second, Emit: func(e ingest.Event) { got = append(got, e) }} + + kitty := Focus{Class: "kitty", Title: "nvim"} + ff := Focus{Class: "firefox", Title: "docs"} + + s.Focus(at(0), kitty) + s.Focus(at(0), kitty) // duplicate event: no new interval + s.Focus(at(60), ff) + s.Focus(at(61), kitty) // firefox for 1s: dropped as flicker + s.Pause(at(120), "idle") + s.Focus(at(130), ff) // focus change while idle is remembered, not recorded + s.Pause(at(300), "locked") + s.Resume(at(600)) + s.Close(at(660)) + + want := []struct { + kind, label string + start, end int + }{ + {"app_focus", "kitty", 0, 60}, + {"app_focus", "kitty", 61, 120}, + {"idle", "idle", 120, 300}, + {"locked", "locked", 300, 600}, + {"app_focus", "firefox", 600, 660}, + } + if len(got) != len(want) { + t.Fatalf("got %d events, want %d: %+v", len(got), len(want), got) + } + for i, w := range want { + g := got[i] + if g.Kind != w.kind || g.Label != w.label || !g.StartedAt.Equal(at(w.start)) || !g.EndedAt.Equal(at(w.end)) { + t.Errorf("event %d: got %s/%s %v-%v, want %+v", i, g.Kind, g.Label, g.StartedAt, g.EndedAt, w) + } + if g.ID == "" { + t.Errorf("event %d has no ID", i) + } + } + if got[0].Attrs["title"] != "nvim" { + t.Errorf("title not recorded: %+v", got[0].Attrs) + } +} + +func TestBufferPersists(t *testing.T) { + path := filepath.Join(t.TempDir(), "buf.jsonl") + b, err := OpenBuffer(path) + if err != nil { + t.Fatal(err) + } + for _, id := range []string{"a", "b", "c"} { + if err := b.Add(ingest.Event{ID: id, Kind: "app_focus"}); err != nil { + t.Fatal(err) + } + } + if err := b.Ack(2); err != nil { + t.Fatal(err) + } + + reopened, err := OpenBuffer(path) + if err != nil { + t.Fatal(err) + } + if ev := reopened.Peek(10); len(ev) != 1 || ev[0].ID != "c" { + t.Fatalf("after reopen got %+v, want only c", ev) + } +} diff --git a/internal/agent/hypr/hyprland.go b/internal/agent/hypr/hyprland.go new file mode 100644 index 0000000..02d317c --- /dev/null +++ b/internal/agent/hypr/hyprland.go @@ -0,0 +1,142 @@ +// Package hypr implements the Hyprland desktop collector: it follows window +// focus over Hyprland's IPC sockets, turns it into intervals, buffers them on +// disk and uploads them to the tracker server. +package hypr + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net" + "os" + "path/filepath" + "strings" + "time" +) + +// Focus is the currently focused window. An empty Class means nothing is +// focused (e.g. an empty workspace). +type Focus struct { + Class string + Title string +} + +// FocusEvent is a focus change stamped with the time it was observed. +type FocusEvent struct { + Focus + At time.Time +} + +func socketDir() (string, error) { + sig := os.Getenv("HYPRLAND_INSTANCE_SIGNATURE") + if sig == "" { + return "", errors.New("HYPRLAND_INSTANCE_SIGNATURE not set; is Hyprland running?") + } + return filepath.Join(os.Getenv("XDG_RUNTIME_DIR"), "hypr", sig), nil +} + +// ParseLine splits a socket2 line of the form "event>>data". +func ParseLine(line string) (event, data string, ok bool) { + return strings.Cut(line, ">>") +} + +// ParseActiveWindow parses the data of an "activewindow" event, "class,title". +// Titles may contain commas, so only the first one is a separator. +func ParseActiveWindow(data string) Focus { + class, title, _ := strings.Cut(data, ",") + return Focus{Class: class, Title: title} +} + +// ActiveWindow asks Hyprland (via the request socket) for the focused window. +func ActiveWindow() (Focus, error) { + dir, err := socketDir() + if err != nil { + return Focus{}, err + } + conn, err := net.DialTimeout("unix", filepath.Join(dir, ".socket.sock"), 2*time.Second) + if err != nil { + return Focus{}, err + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(2 * time.Second)) + + if _, err := conn.Write([]byte("j/activewindow")); err != nil { + return Focus{}, err + } + body, err := io.ReadAll(conn) + if err != nil { + return Focus{}, err + } + var w struct { + Class string `json:"class"` + Title string `json:"title"` + } + if err := json.Unmarshal(body, &w); err != nil { + return Focus{}, fmt.Errorf("decode activewindow: %w", err) + } + return Focus{Class: w.Class, Title: w.Title}, nil +} + +// Listen streams focus changes to out until ctx is cancelled, reconnecting to +// the event socket if the connection drops. +func Listen(ctx context.Context, out chan<- FocusEvent, log *slog.Logger) error { + dir, err := socketDir() + if err != nil { + return err + } + path := filepath.Join(dir, ".socket2.sock") + + for { + err := listenOnce(ctx, path, out) + if ctx.Err() != nil { + return nil + } + log.Warn("hyprland event socket disconnected; retrying", "err", err) + select { + case <-ctx.Done(): + return nil + case <-time.After(2 * time.Second): + } + } +} + +func listenOnce(ctx context.Context, path string, out chan<- FocusEvent) error { + var d net.Dialer + conn, err := d.DialContext(ctx, "unix", path) + if err != nil { + return err + } + defer conn.Close() + go func() { + <-ctx.Done() + conn.Close() + }() + + send := func(f Focus) { + select { + case out <- FocusEvent{Focus: f, At: time.Now()}: + case <-ctx.Done(): + } + } + // Seed with the current window so time before the first switch is counted. + if f, err := ActiveWindow(); err == nil { + send(f) + } + + sc := bufio.NewScanner(conn) + sc.Buffer(make([]byte, 64*1024), 1024*1024) + for sc.Scan() { + event, data, ok := ParseLine(sc.Text()) + if ok && event == "activewindow" { + send(ParseActiveWindow(data)) + } + } + if err := sc.Err(); err != nil { + return err + } + return io.EOF +} diff --git a/internal/agent/hypr/session.go b/internal/agent/hypr/session.go new file mode 100644 index 0000000..fd0373d --- /dev/null +++ b/internal/agent/hypr/session.go @@ -0,0 +1,115 @@ +package hypr + +import ( + "crypto/rand" + "encoding/hex" + "time" + + "ccp/internal/ingest" +) + +// Sessionizer turns a stream of focus changes and idle/lock signals into +// closed intervals. It is not safe for concurrent use. +type Sessionizer struct { + // Intervals shorter than this are dropped (alt-tab flicker). + MinDuration time.Duration + // Emit receives every completed interval. + Emit func(ingest.Event) + + last Focus // most recent focus, remembered while paused + cur *span // open focus interval + pause *span // open idle/locked interval +} + +type span struct { + kind string + focus Focus + start time.Time +} + +// Focus records that f gained focus at now. +func (s *Sessionizer) Focus(now time.Time, f Focus) { + s.last = f + if s.pause != nil { + return // resumes with this window once the pause ends + } + if s.cur != nil && s.cur.focus == f { + return + } + s.closeFocus(now) + s.openFocus(now) +} + +// Pause starts an idle or locked period ("idle" or "locked"). A different +// pause kind while already paused ends the previous one. +func (s *Sessionizer) Pause(now time.Time, kind string) { + if s.pause != nil { + if s.pause.kind == kind { + return + } + s.closePause(now) + } + s.closeFocus(now) + s.pause = &span{kind: kind, start: now} +} + +// Resume ends any pause and reopens the last focused window. +func (s *Sessionizer) Resume(now time.Time) { + if s.pause == nil { + return + } + s.closePause(now) + s.openFocus(now) +} + +// Close ends every open interval, e.g. on shutdown. +func (s *Sessionizer) Close(now time.Time) { + s.closeFocus(now) + s.closePause(now) +} + +func (s *Sessionizer) openFocus(now time.Time) { + if s.last.Class != "" { + s.cur = &span{kind: "app_focus", focus: s.last, start: now} + } +} + +func (s *Sessionizer) closeFocus(now time.Time) { + if s.cur == nil { + return + } + var attrs map[string]any + if s.cur.focus.Title != "" { + attrs = map[string]any{"title": s.cur.focus.Title} + } + s.emit(s.cur, s.cur.focus.Class, now, attrs) + s.cur = nil +} + +func (s *Sessionizer) closePause(now time.Time) { + if s.pause == nil { + return + } + s.emit(s.pause, s.pause.kind, now, nil) + s.pause = nil +} + +func (s *Sessionizer) emit(sp *span, label string, end time.Time, attrs map[string]any) { + if end.Sub(sp.start) < s.MinDuration { + return + } + s.Emit(ingest.Event{ + ID: newID(), + Kind: sp.kind, + Label: label, + StartedAt: sp.start.UTC(), + EndedAt: end.UTC(), + Attrs: attrs, + }) +} + +func newID() string { + b := make([]byte, 16) + rand.Read(b) + return hex.EncodeToString(b) +} diff --git a/internal/agent/hypr/uploader.go b/internal/agent/hypr/uploader.go new file mode 100644 index 0000000..54ad7f7 --- /dev/null +++ b/internal/agent/hypr/uploader.go @@ -0,0 +1,94 @@ +package hypr + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "strings" + "time" + + "ccp/internal/ingest" +) + +const uploadBatch = 500 + +// Uploader sends buffered events to the tracker server. +type Uploader struct { + URL string // server base URL, e.g. https://tracker.example.com + Key string + Buf *Buffer + Client *http.Client + Log *slog.Logger +} + +// Flush uploads everything in the buffer, oldest first. +func (u *Uploader) Flush(ctx context.Context) error { + for { + batch := u.Buf.Peek(uploadBatch) + if len(batch) == 0 { + return nil + } + status, err := u.post(ctx, batch) + switch { + case err != nil: + return err + case status == http.StatusBadRequest || status == http.StatusUnprocessableEntity: + // The server will never accept this batch; drop it so it + // doesn't block everything behind it. + u.Log.Error("server rejected batch; dropping it", "status", status, "events", len(batch)) + case status != http.StatusOK: + return fmt.Errorf("upload: server returned %d", status) + } + if err := u.Buf.Ack(len(batch)); err != nil { + return err + } + } +} + +func (u *Uploader) post(ctx context.Context, events []ingest.Event) (int, error) { + body, err := json.Marshal(ingest.Batch{Events: events}) + if err != nil { + return 0, err + } + url := strings.TrimRight(u.URL, "/") + "/api/v1/desktop/events" + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) + if err != nil { + return 0, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+u.Key) + + resp, err := u.Client.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) + u.Log.Warn("upload failed", "status", resp.StatusCode, "body", strings.TrimSpace(string(msg))) + } + return resp.StatusCode, nil +} + +// Run flushes every interval until ctx is cancelled, backing off up to +// 10 minutes while the server is unreachable. +func (u *Uploader) Run(ctx context.Context, interval time.Duration) { + wait := interval + for { + select { + case <-ctx.Done(): + return + case <-time.After(wait): + } + if err := u.Flush(ctx); err != nil { + wait = min(wait*2, 10*time.Minute) + u.Log.Warn("upload failed; will retry", "err", err, "pending", u.Buf.Len(), "retry_in", wait) + continue + } + wait = interval + } +} diff --git a/internal/api/api.go b/internal/api/api.go new file mode 100644 index 0000000..b1fe302 --- /dev/null +++ b/internal/api/api.go @@ -0,0 +1,256 @@ +// Package api exposes the HTTP ingest and query endpoints. +package api + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "net/http" + "strconv" + "strings" + "time" + + "ccp/internal/ingest" + "ccp/internal/store" + "ccp/internal/summary" +) + +const ( + maxEventBody = 5 << 20 // 5 MiB + maxHAEBody = 50 << 20 // Health Auto Export payloads can be large +) + +type Server struct { + store *store.Store + loc *time.Location + log *slog.Logger + now func() time.Time +} + +func New(s *store.Store, loc *time.Location, log *slog.Logger) http.Handler { + srv := &Server{store: s, loc: loc, log: log, now: time.Now} + + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) + }) + mux.HandleFunc("GET /readyz", srv.ready) + + api := http.NewServeMux() + api.HandleFunc("POST /desktop/events", srv.ingestEvents(ingest.Desktop)) + api.HandleFunc("POST /browser/events", srv.ingestEvents(ingest.Browser)) + api.HandleFunc("POST /presence/events", srv.ingestEvents(ingest.Presence)) + api.HandleFunc("POST /manual/events", srv.ingestEvents(ingest.Manual)) + api.HandleFunc("POST /health/hae", srv.ingestHAE) + api.HandleFunc("GET /activities", srv.activities) + api.HandleFunc("GET /summary/daily", srv.dailySummary) + mux.Handle("/api/v1/", http.StripPrefix("/api/v1", srv.auth(api))) + + return srv.logRequests(mux) +} + +// ---- middleware ---- + +type ctxKey struct{} + +func deviceFrom(ctx context.Context) store.Device { + d, _ := ctx.Value(ctxKey{}).(store.Device) + return d +} + +func (s *Server) auth(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + key, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + if !ok || key == "" { + writeError(w, http.StatusUnauthorized, "missing bearer token") + return + } + dev, err := s.store.DeviceByKey(r.Context(), key) + if errors.Is(err, store.ErrNotFound) { + writeError(w, http.StatusUnauthorized, "invalid api key") + return + } + if err != nil { + s.internalError(w, r, err) + return + } + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, dev))) + }) +} + +type statusRecorder struct { + http.ResponseWriter + status int +} + +func (r *statusRecorder) WriteHeader(code int) { + r.status = code + r.ResponseWriter.WriteHeader(code) +} + +func (s *Server) logRequests(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} + next.ServeHTTP(rec, r) + if r.URL.Path == "/healthz" || r.URL.Path == "/readyz" { + return + } + s.log.Info("request", "method", r.Method, "path", r.URL.Path, + "status", rec.status, "duration", time.Since(start)) + }) +} + +// ---- handlers ---- + +func (s *Server) ready(w http.ResponseWriter, r *http.Request) { + if err := s.store.Ping(r.Context()); err != nil { + writeError(w, http.StatusServiceUnavailable, "database unavailable") + return + } + writeJSON(w, http.StatusOK, map[string]string{"status": "ready"}) +} + +type ingestResult struct { + Received int `json:"received"` + Inserted int64 `json:"inserted"` + Samples int64 `json:"samples_inserted,omitempty"` +} + +func (s *Server) ingestEvents(spec ingest.Spec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var b ingest.Batch + if !s.decode(w, r, maxEventBody, &b) { + return + } + acts, err := spec.Normalize(b, s.now()) + if err != nil { + writeError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + n, err := s.store.InsertActivities(r.Context(), deviceFrom(r.Context()).ID, acts) + if err != nil { + s.internalError(w, r, err) + return + } + writeJSON(w, http.StatusOK, ingestResult{Received: len(acts), Inserted: n}) + } +} + +func (s *Server) ingestHAE(w http.ResponseWriter, r *http.Request) { + var p ingest.HAEPayload + if !s.decode(w, r, maxHAEBody, &p) { + return + } + acts, samples, err := ingest.NormalizeHAE(p) + if err != nil { + writeError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + dev := deviceFrom(r.Context()).ID + na, err := s.store.InsertActivities(r.Context(), dev, acts) + if err != nil { + s.internalError(w, r, err) + return + } + ns, err := s.store.InsertSamples(r.Context(), dev, samples) + if err != nil { + s.internalError(w, r, err) + return + } + writeJSON(w, http.StatusOK, ingestResult{Received: len(acts) + len(samples), Inserted: na, Samples: ns}) +} + +func (s *Server) activities(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + now := s.now() + f := store.ActivityFilter{ + From: now.Add(-24 * time.Hour), + To: now, + Source: q.Get("source"), + Kind: q.Get("kind"), + Limit: 1000, + } + var err error + if v := q.Get("from"); v != "" { + if f.From, err = time.Parse(time.RFC3339, v); err != nil { + writeError(w, http.StatusBadRequest, "from must be RFC3339") + return + } + } + if v := q.Get("to"); v != "" { + if f.To, err = time.Parse(time.RFC3339, v); err != nil { + writeError(w, http.StatusBadRequest, "to must be RFC3339") + return + } + } + if v := q.Get("limit"); v != "" { + if f.Limit, err = strconv.Atoi(v); err != nil || f.Limit < 1 || f.Limit > 10000 { + writeError(w, http.StatusBadRequest, "limit must be 1-10000") + return + } + } + + acts, err := s.store.Activities(r.Context(), f) + if err != nil { + s.internalError(w, r, err) + return + } + writeJSON(w, http.StatusOK, map[string]any{"activities": acts}) +} + +func (s *Server) dailySummary(w http.ResponseWriter, r *http.Request) { + day := s.now().In(s.loc) + if v := r.URL.Query().Get("date"); v != "" { + var err error + if day, err = time.ParseInLocation(time.DateOnly, v, s.loc); err != nil { + writeError(w, http.StatusBadRequest, "date must be YYYY-MM-DD") + return + } + } + from, to := summary.DayBounds(day, s.loc) + + totals, err := s.store.Totals(r.Context(), from, to) + if err != nil { + s.internalError(w, r, err) + return + } + goals, err := s.store.Goals(r.Context()) + if err != nil { + s.internalError(w, r, err) + return + } + writeJSON(w, http.StatusOK, summary.Build(from.Format(time.DateOnly), from, to, totals, goals)) +} + +// ---- helpers ---- + +func (s *Server) decode(w http.ResponseWriter, r *http.Request, limit int64, v any) bool { + r.Body = http.MaxBytesReader(w, r.Body, limit) + if err := json.NewDecoder(r.Body).Decode(v); err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + writeError(w, http.StatusRequestEntityTooLarge, "request body too large") + } else { + writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error()) + } + return false + } + return true +} + +func (s *Server) internalError(w http.ResponseWriter, r *http.Request, err error) { + s.log.Error("request failed", "path", r.URL.Path, "err", err) + writeError(w, http.StatusInternalServerError, "internal error") +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + json.NewEncoder(w).Encode(v) +} + +func writeError(w http.ResponseWriter, status int, msg string) { + writeJSON(w, status, map[string]string{"error": msg}) +} diff --git a/internal/api/api_test.go b/internal/api/api_test.go new file mode 100644 index 0000000..a6bacce --- /dev/null +++ b/internal/api/api_test.go @@ -0,0 +1,119 @@ +package api + +import ( + "context" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "ccp/internal/migrations" + "ccp/internal/store" +) + +// 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 +func setup(t *testing.T) (*httptest.Server, string) { + url := os.Getenv("TEST_DATABASE_URL") + if url == "" { + t.Skip("TEST_DATABASE_URL not set") + } + 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) + _, key, err := st.CreateDevice(ctx, "test", "hyprland") + if err != nil { + t.Fatal(err) + } + if _, err := st.CreateGoal(ctx, store.Goal{Kind: "app_focus", Label: "kitty", Op: ">=", TargetS: 3600}); err != nil { + t.Fatal(err) + } + + srv := httptest.NewServer(New(st, time.UTC, slog.New(slog.NewTextHandler(io.Discard, nil)))) + t.Cleanup(srv.Close) + return srv, key +} + +func do(t *testing.T, method, url, key, body string) (int, map[string]any) { + t.Helper() + req, _ := http.NewRequest(method, url, strings.NewReader(body)) + if key != "" { + req.Header.Set("Authorization", "Bearer "+key) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var out map[string]any + json.NewDecoder(resp.Body).Decode(&out) + return resp.StatusCode, out +} + +func TestIngestAndSummary(t *testing.T) { + srv, key := setup(t) + day := time.Now().UTC().Add(-48 * time.Hour).Format(time.DateOnly) + + // The second event crosses midnight; only its first hour belongs to `day`. + batch := `{"events":[ + {"id":"e1","kind":"app_focus","label":"kitty","started_at":"` + day + `T09:00:00Z","ended_at":"` + day + `T10:30:00Z","attrs":{"title":"nvim"}}, + {"id":"e2","kind":"app_focus","label":"firefox","started_at":"` + day + `T23:00:00Z","ended_at":"` + day + `T23:59:59Z"} + ]}` + + if code, _ := do(t, "POST", srv.URL+"/api/v1/desktop/events", "", batch); code != http.StatusUnauthorized { + t.Fatalf("no key: got %d", code) + } + if code, _ := do(t, "POST", srv.URL+"/api/v1/desktop/events", "trk_wrong", batch); code != http.StatusUnauthorized { + t.Fatalf("bad key: got %d", code) + } + + code, body := do(t, "POST", srv.URL+"/api/v1/desktop/events", key, batch) + if code != http.StatusOK || body["inserted"] != 2.0 { + t.Fatalf("first upload: %d %v", code, body) + } + code, body = do(t, "POST", srv.URL+"/api/v1/desktop/events", key, batch) + if code != http.StatusOK || body["inserted"] != 0.0 { + t.Fatalf("re-upload should be idempotent: %d %v", code, body) + } + + code, body = do(t, "POST", srv.URL+"/api/v1/desktop/events", key, `{"events":[{"id":"x","kind":"walk","started_at":"`+day+`T09:00:00Z","ended_at":"`+day+`T10:00:00Z"}]}`) + if code != http.StatusUnprocessableEntity { + t.Fatalf("wrong kind for endpoint: %d %v", code, body) + } + + code, body = do(t, "GET", srv.URL+"/api/v1/summary/daily?date="+day, key, "") + if code != http.StatusOK { + t.Fatalf("summary: %d %v", code, body) + } + if got := body["by_kind"].(map[string]any)["app_focus"]; got != float64(5400+3599) { + t.Errorf("app_focus total = %v", got) + } + goal := body["goals"].([]any)[0].(map[string]any) + if goal["actual_s"] != 5400.0 || goal["met"] != true { + t.Errorf("goal = %v", goal) + } + + code, body = do(t, "GET", srv.URL+"/api/v1/activities?from="+day+"T00:00:00Z&to="+day+"T23:59:59Z&kind=app_focus", key, "") + if code != http.StatusOK || len(body["activities"].([]any)) != 2 { + t.Fatalf("activities: %d %v", code, body) + } +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..a21c5bb --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,43 @@ +// Package config loads server configuration from environment variables. +package config + +import ( + "errors" + "fmt" + "os" + "strconv" + "time" +) + +type Config struct { + DatabaseURL string + ListenAddr string + AutoMigrate bool + Location *time.Location // timezone used for day boundaries in summaries +} + +func Load() (Config, error) { + c := Config{ + DatabaseURL: os.Getenv("DATABASE_URL"), + ListenAddr: envOr("LISTEN_ADDR", ":8080"), + } + if c.DatabaseURL == "" { + return c, errors.New("DATABASE_URL is required") + } + + var err error + if c.AutoMigrate, err = strconv.ParseBool(envOr("AUTO_MIGRATE", "true")); err != nil { + return c, fmt.Errorf("AUTO_MIGRATE: %w", err) + } + if c.Location, err = time.LoadLocation(envOr("TRACKER_TZ", "UTC")); err != nil { + return c, fmt.Errorf("TRACKER_TZ: %w", err) + } + return c, nil +} + +func envOr(key, def string) string { + if v := os.Getenv(key); v != "" { + return v + } + return def +} diff --git a/internal/ingest/hae.go b/internal/ingest/hae.go new file mode 100644 index 0000000..d4d2a53 --- /dev/null +++ b/internal/ingest/hae.go @@ -0,0 +1,156 @@ +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 +} diff --git a/internal/ingest/ingest.go b/internal/ingest/ingest.go new file mode 100644 index 0000000..b5ee525 --- /dev/null +++ b/internal/ingest/ingest.go @@ -0,0 +1,129 @@ +// Package ingest defines the wire format collectors upload and normalises it +// into activities and samples ready for storage. +package ingest + +import ( + "fmt" + "strings" + "time" +) + +const ( + MaxBatch = 1000 + maxDuration = 7 * 24 * time.Hour + maxFutureSkew = 5 * time.Minute + maxLabelLength = 512 + maxIDLength = 128 +) + +// Event is a single interval as sent by a collector. ID is generated by the +// collector and makes re-uploads idempotent. +type Event struct { + ID string `json:"id"` + Kind string `json:"kind"` + Label string `json:"label"` + StartedAt time.Time `json:"started_at"` + EndedAt time.Time `json:"ended_at"` + Attrs map[string]any `json:"attrs,omitempty"` +} + +type Batch struct { + Events []Event `json:"events"` +} + +// Activity is a normalised interval ready to be stored. +type Activity struct { + Source string + Kind string + Label string + StartedAt time.Time + EndedAt time.Time + Attrs map[string]any + 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 +// activities are stored under. +type Spec struct { + Source string + Kinds map[string]bool // nil accepts any kind +} + +var ( + Desktop = Spec{Source: "hyprland", Kinds: set("app_focus", "idle", "locked")} + Browser = Spec{Source: "browser", Kinds: set("tab_focus", "idle")} + Presence = Spec{Source: "presence", Kinds: set("at_desk", "in_bed", "away")} + Manual = Spec{Source: "manual"} +) + +func set(kinds ...string) map[string]bool { + m := make(map[string]bool, len(kinds)) + for _, k := range kinds { + m[k] = true + } + return m +} + +// Normalize validates every event in the batch and converts it to activities. +// The whole batch is rejected if any event is invalid. +func (s Spec) Normalize(b Batch, now time.Time) ([]Activity, error) { + if len(b.Events) == 0 { + return nil, fmt.Errorf("batch has no events") + } + if len(b.Events) > MaxBatch { + return nil, fmt.Errorf("batch has %d events, max is %d", len(b.Events), MaxBatch) + } + + out := make([]Activity, 0, len(b.Events)) + for i, e := range b.Events { + if err := s.validate(e, now); err != nil { + return nil, fmt.Errorf("event %d: %w", i, err) + } + attrs := e.Attrs + if attrs == nil { + attrs = map[string]any{} + } + out = append(out, Activity{ + Source: s.Source, + Kind: e.Kind, + Label: strings.TrimSpace(e.Label), + StartedAt: e.StartedAt.UTC(), + EndedAt: e.EndedAt.UTC(), + Attrs: attrs, + ExternalID: e.ID, + }) + } + return out, nil +} + +func (s Spec) validate(e Event, now time.Time) error { + switch { + case e.ID == "" || len(e.ID) > maxIDLength: + return fmt.Errorf("id must be 1-%d characters", maxIDLength) + case e.Kind == "": + return fmt.Errorf("kind is required") + case s.Kinds != nil && !s.Kinds[e.Kind]: + return fmt.Errorf("kind %q not accepted by this endpoint", e.Kind) + case len(e.Label) > maxLabelLength: + return fmt.Errorf("label longer than %d characters", maxLabelLength) + case e.StartedAt.IsZero() || e.EndedAt.IsZero(): + return fmt.Errorf("started_at and ended_at are required") + case e.EndedAt.Before(e.StartedAt): + return fmt.Errorf("ended_at is before started_at") + case e.EndedAt.Sub(e.StartedAt) > maxDuration: + return fmt.Errorf("interval longer than %s", maxDuration) + case e.EndedAt.After(now.Add(maxFutureSkew)): + return fmt.Errorf("ended_at is in the future") + } + return nil +} diff --git a/internal/ingest/ingest_test.go b/internal/ingest/ingest_test.go new file mode 100644 index 0000000..20c9f4d --- /dev/null +++ b/internal/ingest/ingest_test.go @@ -0,0 +1,72 @@ +package ingest + +import ( + "encoding/json" + "strings" + "testing" + "time" +) + +func TestNormalizeValidation(t *testing.T) { + now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) + ok := Event{ID: "1", Kind: "app_focus", Label: "kitty", StartedAt: now.Add(-time.Hour), EndedAt: now} + + tests := []struct { + name string + mutate func(*Event) + wantErr string + }{ + {"valid", func(e *Event) {}, ""}, + {"missing id", func(e *Event) { e.ID = "" }, "id"}, + {"wrong kind", func(e *Event) { e.Kind = "tab_focus" }, "not accepted"}, + {"reversed", func(e *Event) { e.EndedAt = e.StartedAt.Add(-time.Second) }, "before"}, + {"future", func(e *Event) { e.EndedAt = now.Add(time.Hour) }, "future"}, + {"too long", func(e *Event) { e.StartedAt = now.Add(-8 * 24 * time.Hour) }, "longer"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + e := ok + tt.mutate(&e) + acts, err := Desktop.Normalize(Batch{Events: []Event{e}}, now) + if tt.wantErr == "" { + if err != nil || len(acts) != 1 || acts[0].Source != "hyprland" { + t.Fatalf("got %+v, %v", acts, err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("got err %v, want containing %q", err, tt.wantErr) + } + }) + } +} + +func TestNormalizeHAE(t *testing.T) { + raw := `{"data":{ + "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":[ + {"name":"step_count","units":"count","data":[{"date":"2026-10-14 07:00:00 -0700","qty":812,"source":"iPhone"},{"date":"bad"}]}, + {"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}]} + ]}}` + var p HAEPayload + if err := json.Unmarshal([]byte(raw), &p); err != nil { + t.Fatal(err) + } + acts, samples, err := NormalizeHAE(p) + if err != nil { + t.Fatal(err) + } + if len(acts) != 2 || len(samples) != 1 { + t.Fatalf("got %d activities, %d samples", len(acts), len(samples)) + } + walk := acts[0] + if walk.Kind != "walk" || walk.ExternalID != "W1" || walk.EndedAt.Sub(walk.StartedAt) != 45*time.Minute { + t.Errorf("walk: %+v", walk) + } + 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]) + } +} diff --git a/internal/migrations/00001_init.sql b/internal/migrations/00001_init.sql new file mode 100644 index 0000000..6322f46 --- /dev/null +++ b/internal/migrations/00001_init.sql @@ -0,0 +1,74 @@ +-- +goose Up +CREATE TABLE devices ( + id bigserial PRIMARY KEY, + name text NOT NULL UNIQUE, + kind text NOT NULL, + api_key_hash text NOT NULL UNIQUE, + created_at timestamptz NOT NULL DEFAULT now(), + last_seen_at timestamptz, + revoked_at timestamptz +); + +CREATE TABLE activities ( + id bigserial PRIMARY KEY, + device_id bigint NOT NULL REFERENCES devices (id), + source text NOT NULL, + kind text NOT NULL, + label text NOT NULL DEFAULT '', + started_at timestamptz NOT NULL, + ended_at timestamptz NOT NULL, + duration_s integer GENERATED ALWAYS AS (extract(epoch FROM ended_at - started_at)::integer) STORED, + attrs jsonb NOT NULL DEFAULT '{}', + external_id text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + CHECK (ended_at >= started_at), + UNIQUE (source, external_id) +); +CREATE INDEX activities_started_at_idx ON activities (started_at); +CREATE INDEX activities_kind_started_at_idx ON activities (kind, started_at); +CREATE INDEX activities_label_idx ON activities (label); + +-- Point-in-time metrics such as step counts or heart rate. +CREATE TABLE samples ( + id bigserial PRIMARY KEY, + device_id bigint NOT NULL REFERENCES devices (id), + source text NOT NULL, + metric text NOT NULL, + ts timestamptz NOT NULL, + value double precision NOT NULL, + unit text NOT NULL DEFAULT '', + external_id text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (source, external_id) +); +CREATE INDEX samples_metric_ts_idx ON samples (metric, ts); + +-- Daily targets, e.g. kind=tab_focus label=youtube.com op=<= target_s=3600. +-- An empty label matches every label of that kind. +CREATE TABLE goals ( + id bigserial PRIMARY KEY, + kind text NOT NULL, + label text NOT NULL DEFAULT '', + op text NOT NULL CHECK (op IN ('>=', '<=')), + target_s integer NOT NULL CHECK (target_s >= 0), + period text NOT NULL DEFAULT 'day' CHECK (period IN ('day')), + created_at timestamptz NOT NULL DEFAULT now() +); + +-- Output of future AI analysis jobs. +CREATE TABLE reports ( + id bigserial PRIMARY KEY, + period_start timestamptz NOT NULL, + period_end timestamptz NOT NULL, + model text NOT NULL, + prompt_hash text NOT NULL, + body text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +-- +goose Down +DROP TABLE reports; +DROP TABLE goals; +DROP TABLE samples; +DROP TABLE activities; +DROP TABLE devices; diff --git a/internal/migrations/migrations.go b/internal/migrations/migrations.go new file mode 100644 index 0000000..ecf4623 --- /dev/null +++ b/internal/migrations/migrations.go @@ -0,0 +1,30 @@ +// Package migrations embeds the SQL schema migrations and applies them with goose. +package migrations + +import ( + "context" + "embed" + "fmt" + + "github.com/jackc/pgx/v5/pgxpool" + "github.com/jackc/pgx/v5/stdlib" + "github.com/pressly/goose/v3" +) + +//go:embed *.sql +var files embed.FS + +// Up applies all pending migrations. +func Up(ctx context.Context, pool *pgxpool.Pool) error { + db := stdlib.OpenDBFromPool(pool) + defer db.Close() + + p, err := goose.NewProvider(goose.DialectPostgres, db, files) + if err != nil { + return fmt.Errorf("goose provider: %w", err) + } + if _, err := p.Up(ctx); err != nil { + return fmt.Errorf("migrate up: %w", err) + } + return nil +} diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..ae8e243 --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,266 @@ +// Package store wraps all PostgreSQL access. +package store + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "ccp/internal/ingest" +) + +var ErrNotFound = errors.New("not found") + +type Store struct { + pool *pgxpool.Pool +} + +func New(pool *pgxpool.Pool) *Store { return &Store{pool: pool} } + +func (s *Store) Ping(ctx context.Context) error { return s.pool.Ping(ctx) } + +// ---- devices / API keys ---- + +type Device struct { + ID int64 `json:"id"` + Name string `json:"name"` + Kind string `json:"kind"` + CreatedAt time.Time `json:"created_at"` + LastSeenAt *time.Time `json:"last_seen_at"` + RevokedAt *time.Time `json:"revoked_at"` +} + +// HashKey returns the stored representation of an API key. +func HashKey(key string) string { + sum := sha256.Sum256([]byte(key)) + return hex.EncodeToString(sum[:]) +} + +// CreateDevice registers a device and returns its plaintext API key, which +// is not stored and can't be recovered later. +func (s *Store) CreateDevice(ctx context.Context, name, kind string) (Device, string, error) { + raw := make([]byte, 32) + if _, err := rand.Read(raw); err != nil { + return Device{}, "", err + } + key := "trk_" + base64.RawURLEncoding.EncodeToString(raw) + + var d Device + err := s.pool.QueryRow(ctx, + `INSERT INTO devices (name, kind, api_key_hash) VALUES ($1, $2, $3) + RETURNING id, name, kind, created_at, last_seen_at, revoked_at`, + name, kind, HashKey(key), + ).Scan(&d.ID, &d.Name, &d.Kind, &d.CreatedAt, &d.LastSeenAt, &d.RevokedAt) + return d, key, err +} + +func (s *Store) ListDevices(ctx context.Context) ([]Device, error) { + rows, err := s.pool.Query(ctx, + `SELECT id, name, kind, created_at, last_seen_at, revoked_at FROM devices ORDER BY id`) + if err != nil { + return nil, err + } + return pgx.CollectRows(rows, func(r pgx.CollectableRow) (Device, error) { + var d Device + err := r.Scan(&d.ID, &d.Name, &d.Kind, &d.CreatedAt, &d.LastSeenAt, &d.RevokedAt) + return d, err + }) +} + +func (s *Store) RevokeDevice(ctx context.Context, name string) error { + tag, err := s.pool.Exec(ctx, + `UPDATE devices SET revoked_at = now() WHERE name = $1 AND revoked_at IS NULL`, name) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + return nil +} + +// DeviceByKey authenticates an API key and records that the device was seen. +func (s *Store) DeviceByKey(ctx context.Context, key string) (Device, error) { + var d Device + err := s.pool.QueryRow(ctx, + `UPDATE devices SET last_seen_at = now() + WHERE api_key_hash = $1 AND revoked_at IS NULL + RETURNING id, name, kind, created_at, last_seen_at, revoked_at`, + HashKey(key), + ).Scan(&d.ID, &d.Name, &d.Kind, &d.CreatedAt, &d.LastSeenAt, &d.RevokedAt) + if errors.Is(err, pgx.ErrNoRows) { + return d, ErrNotFound + } + return d, err +} + +// ---- ingest ---- + +// InsertActivities stores activities, skipping ones already stored with the +// same (source, external_id). It returns how many rows were new. +func (s *Store) InsertActivities(ctx context.Context, deviceID int64, acts []ingest.Activity) (int64, error) { + b := &pgx.Batch{} + for _, a := range acts { + b.Queue(`INSERT INTO activities + (device_id, source, kind, label, started_at, ended_at, attrs, external_id) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (source, external_id) DO NOTHING`, + deviceID, a.Source, a.Kind, a.Label, a.StartedAt, a.EndedAt, a.Attrs, a.ExternalID) + } + 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) + } + return s.sendBatch(ctx, b) +} + +func (s *Store) sendBatch(ctx context.Context, b *pgx.Batch) (int64, error) { + if b.Len() == 0 { + return 0, nil + } + tx, err := s.pool.Begin(ctx) + if err != nil { + return 0, err + } + defer tx.Rollback(ctx) + + br := tx.SendBatch(ctx, b) + var inserted int64 + for range b.Len() { + tag, err := br.Exec() + if err != nil { + br.Close() + return 0, err + } + inserted += tag.RowsAffected() + } + if err := br.Close(); err != nil { + return 0, err + } + return inserted, tx.Commit(ctx) +} + +// ---- queries ---- + +type StoredActivity struct { + ID int64 `json:"id"` + Device string `json:"device"` + Source string `json:"source"` + Kind string `json:"kind"` + Label string `json:"label"` + StartedAt time.Time `json:"started_at"` + EndedAt time.Time `json:"ended_at"` + DurationS int `json:"duration_s"` + Attrs map[string]any `json:"attrs"` +} + +type ActivityFilter struct { + From, To time.Time + Source, Kind string // empty matches all + Limit int +} + +// 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 + AND ($3 = '' OR a.source = $3) + AND ($4 = '' OR a.kind = $4) + ORDER BY a.started_at + LIMIT $5`, + f.From, f.To, f.Source, f.Kind, f.Limit) + if err != nil { + return nil, err + } + return pgx.CollectRows(rows, func(r pgx.CollectableRow) (StoredActivity, error) { + var a StoredActivity + err := r.Scan(&a.ID, &a.Device, &a.Source, &a.Kind, &a.Label, &a.StartedAt, &a.EndedAt, &a.DurationS, &a.Attrs) + return a, err + }) +} + +type Total struct { + Source string `json:"source"` + Kind string `json:"kind"` + Label string `json:"label"` + Seconds int64 `json:"seconds"` +} + +// Totals sums activity time per (source, kind, label), counting only the +// part of each interval that falls inside [from, to). +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 + GROUP BY source, kind, label + ORDER BY seconds DESC`, + from, to) + if err != nil { + return nil, err + } + return pgx.CollectRows(rows, pgx.RowToStructByPos[Total]) +} + +// ---- goals ---- + +type Goal struct { + ID int64 `json:"id"` + Kind string `json:"kind"` + Label string `json:"label"` + Op string `json:"op"` + TargetS int64 `json:"target_s"` + Period string `json:"period"` +} + +func (s *Store) Goals(ctx context.Context) ([]Goal, error) { + rows, err := s.pool.Query(ctx, + `SELECT id, kind, label, op, target_s, period FROM goals ORDER BY id`) + if err != nil { + return nil, err + } + return pgx.CollectRows(rows, pgx.RowToStructByPos[Goal]) +} + +func (s *Store) CreateGoal(ctx context.Context, g Goal) (Goal, error) { + err := s.pool.QueryRow(ctx, + `INSERT INTO goals (kind, label, op, target_s) VALUES ($1, $2, $3, $4) + RETURNING id, period`, + g.Kind, g.Label, g.Op, g.TargetS, + ).Scan(&g.ID, &g.Period) + if err != nil { + return g, fmt.Errorf("create goal: %w", err) + } + return g, nil +} + +func (s *Store) DeleteGoal(ctx context.Context, id int64) error { + tag, err := s.pool.Exec(ctx, `DELETE FROM goals WHERE id = $1`, id) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + return nil +} diff --git a/internal/summary/summary.go b/internal/summary/summary.go new file mode 100644 index 0000000..f9251d6 --- /dev/null +++ b/internal/summary/summary.go @@ -0,0 +1,70 @@ +// Package summary builds daily summaries and evaluates goals against them. +package summary + +import ( + "time" + + "ccp/internal/store" +) + +type GoalResult struct { + store.Goal + ActualS int64 `json:"actual_s"` + Met bool `json:"met"` +} + +type Daily struct { + Date string `json:"date"` + From time.Time `json:"from"` + To time.Time `json:"to"` + Totals []store.Total `json:"totals"` + ByKind map[string]int64 `json:"by_kind"` + Goals []GoalResult `json:"goals"` +} + +// DayBounds returns the start and end of the calendar day containing t in loc. +// It uses AddDate rather than 24h so DST transitions are handled. +func DayBounds(t time.Time, loc *time.Location) (time.Time, time.Time) { + t = t.In(loc) + start := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, loc) + return start, start.AddDate(0, 0, 1) +} + +// Build assembles a daily summary from per-label totals and goals. +func Build(date string, from, to time.Time, totals []store.Total, goals []store.Goal) Daily { + d := Daily{ + Date: date, + From: from, + To: to, + Totals: totals, + ByKind: map[string]int64{}, + Goals: Evaluate(totals, goals), + } + if d.Totals == nil { + d.Totals = []store.Total{} + } + for _, t := range totals { + d.ByKind[t.Kind] += t.Seconds + } + return d +} + +// Evaluate checks each goal against the totals. A goal with an empty label +// counts every label of its kind. +func Evaluate(totals []store.Total, goals []store.Goal) []GoalResult { + out := make([]GoalResult, 0, len(goals)) + for _, g := range goals { + var actual int64 + for _, t := range totals { + if t.Kind == g.Kind && (g.Label == "" || t.Label == g.Label) { + actual += t.Seconds + } + } + met := actual >= g.TargetS + if g.Op == "<=" { + met = actual <= g.TargetS + } + out = append(out, GoalResult{Goal: g, ActualS: actual, Met: met}) + } + return out +} diff --git a/internal/summary/summary_test.go b/internal/summary/summary_test.go new file mode 100644 index 0000000..d4eb8b9 --- /dev/null +++ b/internal/summary/summary_test.go @@ -0,0 +1,43 @@ +package summary + +import ( + "testing" + "time" + + "ccp/internal/store" +) + +func TestEvaluate(t *testing.T) { + totals := []store.Total{ + {Kind: "tab_focus", Label: "youtube.com", Seconds: 5400}, + {Kind: "tab_focus", Label: "github.com", Seconds: 1800}, + {Kind: "walk", Label: "Outdoor Walk", Seconds: 1200}, + } + goals := []store.Goal{ + {ID: 1, Kind: "tab_focus", Label: "youtube.com", Op: "<=", TargetS: 3600}, + {ID: 2, Kind: "walk", Op: ">=", TargetS: 1800}, + {ID: 3, Kind: "tab_focus", Op: ">=", TargetS: 7200}, // empty label = all labels + } + got := Evaluate(totals, goals) + want := []struct { + actual int64 + met bool + }{{5400, false}, {1200, false}, {7200, true}} + for i, w := range want { + if got[i].ActualS != w.actual || got[i].Met != w.met { + t.Errorf("goal %d: got actual=%d met=%v, want %+v", goals[i].ID, got[i].ActualS, got[i].Met, w) + } + } +} + +func TestDayBoundsDST(t *testing.T) { + loc, err := time.LoadLocation("America/New_York") + if err != nil { + t.Skip("no tzdata:", err) + } + // 2026-03-08 is the spring-forward day: only 23 hours long. + from, to := DayBounds(time.Date(2026, 3, 8, 15, 0, 0, 0, loc), loc) + if to.Sub(from) != 23*time.Hour || from.Hour() != 0 { + t.Fatalf("got %v - %v", from, to) + } +}