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 <[email protected]>
This commit is contained in:
@@ -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})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user