Files
ccp/internal/api/api.go
T
adamfandClaude Opus 5.5 06800edd91
Test and publish / test (push) Successful in 15s
Test and publish / publish (push) Successful in 3m10s
Add minimal dashboard page served at /
Single embedded HTML page that reads the daily summary and activities
endpoints with a user-supplied API key: goals, totals by kind, top labels
and a timeline for the selected day.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 21:02:11 +01:00

259 lines
7.0 KiB
Go

// 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"
"ccp/internal/web"
)
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)
mux.HandleFunc("GET /{$}", web.Handler)
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})
}