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,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)
|
||||
}
|
||||
@@ -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 <command>`.
|
||||
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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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])
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user