// 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 }