From 2d407d418a8391d3b06899190ae4fec70cb7f7b2 Mon Sep 17 00:00:00 2001 From: shoemoney Date: Tue, 23 Jun 2026 12:35:36 -0500 Subject: [PATCH] =?UTF-8?q?feat:=20hub=20live=20dashboard=20backend=20?= =?UTF-8?q?=E2=80=94=20state=20+=20SSE=20flow=20stream=20=F0=9F=93=8A?= =?UTF-8?q?=F0=9F=9B=B0=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Optional, off by default: devbox-hub serve --dashboard [--dashboard-addr 127.0.0.1:8099]. A separate, loopback-by-default listener (never widens the API surface; warns if bound non-loopback since it's unauthenticated read-only). - internal/hub/dashboard: embedded UI (go:embed index.html) + GET /api/state (hub/totals/devices/shares snapshot) + GET /api/events (SSE live flow stream). A nil *Dashboard is Emit-safe so hub handlers call it unconditionally. - meta reads for the snapshot: Devices(), ShareStats() (one rolled-up query), SumChunkBytes(). 'online' is activity-tracked since hub start (2-min window). - hub emits 'join' (device enrolled) and 'push' (device→share, bytes/chunks/ snapshot/new_head) flow events. Tests: state reflects the DB + a push event reaches a live SSE subscriber + nil-safe Emit. index.html here is a placeholder — the epic frontend lands next. --- cmd/devbox-hub/main.go | 41 +++- internal/hub/dashboard/dashboard.go | 241 +++++++++++++++++++++++ internal/hub/dashboard/dashboard_test.go | 98 +++++++++ internal/hub/dashboard/index.html | 5 + internal/hub/meta/meta.go | 73 +++++++ internal/hub/server.go | 27 ++- 6 files changed, 481 insertions(+), 4 deletions(-) create mode 100644 internal/hub/dashboard/dashboard.go create mode 100644 internal/hub/dashboard/dashboard_test.go create mode 100644 internal/hub/dashboard/index.html diff --git a/cmd/devbox-hub/main.go b/cmd/devbox-hub/main.go index c6f6905..4325049 100644 --- a/cmd/devbox-hub/main.go +++ b/cmd/devbox-hub/main.go @@ -6,6 +6,7 @@ import ( "crypto/rand" "encoding/hex" "fmt" + "net" "net/http" "os" "path/filepath" @@ -15,10 +16,24 @@ import ( "git.shoemoney.ai/shoemoney/devbox/internal/hub" "git.shoemoney.ai/shoemoney/devbox/internal/hub/blobstore" + "git.shoemoney.ai/shoemoney/devbox/internal/hub/dashboard" "git.shoemoney.ai/shoemoney/devbox/internal/hub/meta" "git.shoemoney.ai/shoemoney/devbox/internal/manifest" ) +// isLoopback reports whether addr binds only to a loopback interface. +func isLoopback(addr string) bool { + host, _, err := net.SplitHostPort(addr) + if err != nil { + host = addr + } + if host == "" || host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + var version = "0.0.0-dev" func main() { @@ -57,7 +72,8 @@ func openDB(data string) (*meta.DB, error) { } func serveCmd() *cobra.Command { - var data, listen string + var data, listen, dashAddr string + var dash bool cmd := &cobra.Command{ Use: "serve", Short: "🚀 run the hub server", @@ -71,7 +87,26 @@ func serveCmd() *cobra.Command { return err } srv := hub.NewServer(db, store) - fmt.Fprintf(cmd.OutOrStdout(), "🛰️ devbox-hub listening on %s (data: %s)\n", listen, data) + out := cmd.OutOrStdout() + + // Optional live dashboard on its own address (localhost by default so it + // never widens the API surface; it's unauthenticated read-only metrics). + if dash { + d := dashboard.New(db, version) + srv.WithDashboard(d) + if !isLoopback(dashAddr) { + fmt.Fprintf(out, "⚠️ dashboard on %s is UNAUTHENTICATED and not loopback — anyone who can reach it sees hub activity. SSH-tunnel instead, or you accept this.\n", dashAddr) + } + go func() { + ds := &http.Server{Addr: dashAddr, Handler: d.Handler(), ReadHeaderTimeout: 10 * time.Second} + fmt.Fprintf(out, "📊 dashboard live at http://%s\n", dashAddr) + if err := ds.ListenAndServe(); err != nil { + fmt.Fprintf(out, "dashboard server stopped: %v\n", err) + } + }() + } + + fmt.Fprintf(out, "🛰️ devbox-hub listening on %s (data: %s)\n", listen, data) // Explicit timeouts bound the slowloris surface (bare ListenAndServe // has none). No WriteTimeout on purpose: the /v1/events SSE stream is // long-lived and a WriteTimeout would kill it mid-flight. @@ -88,6 +123,8 @@ func serveCmd() *cobra.Command { } cmd.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory") cmd.Flags().StringVar(&listen, "listen", ":8080", "listen address") + cmd.Flags().BoolVar(&dash, "dashboard", false, "serve the live web dashboard") + cmd.Flags().StringVar(&dashAddr, "dashboard-addr", "127.0.0.1:8099", "dashboard listen address (loopback by default — unauthenticated)") return cmd } diff --git a/internal/hub/dashboard/dashboard.go b/internal/hub/dashboard/dashboard.go new file mode 100644 index 0000000..8ff303a --- /dev/null +++ b/internal/hub/dashboard/dashboard.go @@ -0,0 +1,241 @@ +// Package dashboard is the hub's OPTIONAL live dashboard: an embedded web UI +// plus a JSON state snapshot (/api/state) and a Server-Sent-Events flow stream +// (/api/events) that animates devices pushing/joining in real time. It is read- +// only and served on its own address (localhost by default) so it never widens +// the hub's API surface; a nil *Dashboard means "disabled" and is safe to Emit to. +package dashboard + +import ( + _ "embed" + "encoding/json" + "fmt" + "net/http" + "sync" + "time" + + "git.shoemoney.ai/shoemoney/devbox/internal/hub/meta" +) + +//go:embed index.html +var indexHTML []byte + +const onlineWindow = 2 * time.Minute + +// Event is one live activity event streamed to the dashboard UI. It is NOT wire- +// versioned (UI feed only), so it can change freely without breaking clients. +type Event struct { + TS int64 `json:"ts"` // unix millis + Type string `json:"type"` // "join" | "push" + Device string `json:"device"` + DeviceName string `json:"device_name"` + Share string `json:"share,omitempty"` + Bytes int64 `json:"bytes,omitempty"` + Chunks int `json:"chunks,omitempty"` + Snapshot string `json:"snapshot,omitempty"` + NewHead bool `json:"new_head,omitempty"` +} + +// Dashboard holds the live state broker and the read handles into the metadata DB. +type Dashboard struct { + db *meta.DB + version string + started time.Time + broker *broker + + mu sync.Mutex + lastSeen map[string]int64 // deviceID -> unix seconds of its last activity +} + +// New builds a dashboard over the hub's metadata DB. +func New(db *meta.DB, version string) *Dashboard { + return &Dashboard{db: db, version: version, started: time.Now(), broker: newBroker(), lastSeen: map[string]int64{}} +} + +// Emit records device activity and fans the event out to connected dashboards. +// Safe on a nil receiver (dashboard disabled) so hub handlers call it freely. +func (d *Dashboard) Emit(ev Event) { + if d == nil { + return + } + if ev.TS == 0 { + ev.TS = time.Now().UnixMilli() + } + if ev.Device != "" { + d.mu.Lock() + d.lastSeen[ev.Device] = time.Now().Unix() + d.mu.Unlock() + } + d.broker.publish(ev) +} + +func (d *Dashboard) online(deviceID, _ string, now int64) bool { + d.mu.Lock() + defer d.mu.Unlock() + ts, ok := d.lastSeen[deviceID] + return ok && now-ts <= int64(onlineWindow/time.Second) +} + +// Handler serves the UI (/), the state snapshot (/api/state) and the live flow +// stream (/api/events). +func (d *Dashboard) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Write(indexHTML) + }) + mux.HandleFunc("GET /api/state", d.handleState) + mux.HandleFunc("GET /api/events", d.handleEvents) + return mux +} + +type stateResp struct { + Hub hubInfo `json:"hub"` + Totals totalsInfo `json:"totals"` + Devices []deviceJSON `json:"devices"` + Shares []shareJSON `json:"shares"` +} +type hubInfo struct { + Version string `json:"version"` + UptimeS int64 `json:"uptime_s"` +} +type totalsInfo struct { + Devices, Online, Shares, Snapshots, Chunks int64 + Bytes int64 +} + +// MarshalJSON keeps the totals keys lowercase to match the frontend contract. +func (t totalsInfo) MarshalJSON() ([]byte, error) { + return json.Marshal(map[string]int64{ + "devices": t.Devices, "online": t.Online, "shares": t.Shares, + "snapshots": t.Snapshots, "chunks": t.Chunks, "bytes": t.Bytes, + }) +} + +type deviceJSON struct { + ID string `json:"id"` + Name string `json:"name"` + LastSeen int64 `json:"last_seen"` + Online bool `json:"online"` + Principal string `json:"principal"` + Revoked bool `json:"revoked"` +} +type shareJSON struct { + Name string `json:"name"` + Head string `json:"head"` + Snapshots int `json:"snapshots"` + Members int `json:"members"` + ACLMode string `json:"acl_mode"` + UpdatedAt int64 `json:"updated_at"` +} + +func (d *Dashboard) handleState(w http.ResponseWriter, _ *http.Request) { + now := time.Now().Unix() + devs, err := d.db.Devices() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + var online int64 + devices := make([]deviceJSON, 0, len(devs)) + for _, dv := range devs { + on := d.online(dv.ID, dv.Name, now) + if on { + online++ + } + devices = append(devices, deviceJSON{dv.ID, dv.Name, dv.LastSeen, on, dv.Principal, dv.Revoked}) + } + stats, err := d.db.ShareStats() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + shares := make([]shareJSON, 0, len(stats)) + for _, s := range stats { + shares = append(shares, shareJSON{s.Name, s.Head, s.Snapshots, s.Members, s.ACLMode, s.UpdatedAt}) + } + bytes, _ := d.db.SumChunkBytes() + count := func(t string) int64 { n, _ := d.db.Count(t); return n } + resp := stateResp{ + Hub: hubInfo{Version: d.version, UptimeS: int64(time.Since(d.started).Seconds())}, + Totals: totalsInfo{count("devices"), online, count("shares"), count("snapshots"), count("chunks"), bytes}, + Devices: devices, Shares: shares, + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(resp) +} + +// handleEvents streams live flow events as SSE (mirrors the hub's client event +// stream; copied not shared since the payload type differs). +func (d *Dashboard) handleEvents(w http.ResponseWriter, r *http.Request) { + flusher, ok := w.(http.Flusher) + if !ok { + http.Error(w, "streaming unsupported", http.StatusInternalServerError) + return + } + ch := d.broker.sub() + defer d.broker.unsub(ch) + h := w.Header() + h.Set("Content-Type", "text/event-stream") + h.Set("Cache-Control", "no-cache") + h.Set("Connection", "keep-alive") + w.WriteHeader(http.StatusOK) + flusher.Flush() + + ping := time.NewTicker(25 * time.Second) + defer ping.Stop() + for { + select { + case <-r.Context().Done(): + return + case <-ping.C: + fmt.Fprint(w, ": ping\n\n") + flusher.Flush() + case ev := <-ch: + b, _ := json.Marshal(ev) + fmt.Fprintf(w, "data: %s\n\n", b) + flusher.Flush() + } + } +} + +// broker fans dashboard events out to connected SSE subscribers; a slow one is +// dropped rather than blocking a hub handler. ponytail: same shape as the hub's +// proto.Event broker — kept separate (different payload) over a generic seam. +type broker struct { + mu sync.Mutex + subs map[chan Event]struct{} +} + +func newBroker() *broker { return &broker{subs: map[chan Event]struct{}{}} } + +func (b *broker) sub() chan Event { + ch := make(chan Event, 32) + b.mu.Lock() + b.subs[ch] = struct{}{} + b.mu.Unlock() + return ch +} + +func (b *broker) unsub(ch chan Event) { + b.mu.Lock() + if _, ok := b.subs[ch]; ok { + delete(b.subs, ch) + close(ch) + } + b.mu.Unlock() +} + +func (b *broker) publish(ev Event) { + b.mu.Lock() + defer b.mu.Unlock() + for ch := range b.subs { + select { + case ch <- ev: + default: // slow subscriber; drop (the dashboard re-fetches /api/state) + } + } +} diff --git a/internal/hub/dashboard/dashboard_test.go b/internal/hub/dashboard/dashboard_test.go new file mode 100644 index 0000000..3635aed --- /dev/null +++ b/internal/hub/dashboard/dashboard_test.go @@ -0,0 +1,98 @@ +package dashboard + +import ( + "bufio" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "git.shoemoney.ai/shoemoney/devbox/internal/hub/meta" +) + +// TestStateAndEvents covers both dashboard surfaces: /api/state reflects the DB, +// and an Emit'd flow event reaches a connected /api/events subscriber. +func TestStateAndEvents(t *testing.T) { + db, err := meta.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + now := time.Now().Unix() + if err := db.AddDevice("dev1", "hueb", []byte("k"), now); err != nil { + t.Fatal(err) + } + if err := db.CreateShare("proj", "dev1", now); err != nil { + t.Fatal(err) + } + + d := New(db, "1.2.3") + srv := httptest.NewServer(d.Handler()) + defer srv.Close() + + // /api/state reflects the DB. + resp, err := http.Get(srv.URL + "/api/state") + if err != nil { + t.Fatal(err) + } + var st stateResp + if err := json.NewDecoder(resp.Body).Decode(&st); err != nil { + t.Fatal(err) + } + resp.Body.Close() + if st.Hub.Version != "1.2.3" { + t.Fatalf("version = %q", st.Hub.Version) + } + if len(st.Devices) != 1 || st.Devices[0].Name != "hueb" { + t.Fatalf("devices = %+v", st.Devices) + } + if len(st.Shares) != 1 || st.Shares[0].Name != "proj" { + t.Fatalf("shares = %+v", st.Shares) + } + + // / serves the embedded UI. + if r, _ := http.Get(srv.URL + "/"); r == nil || r.StatusCode != 200 { + t.Fatal("dashboard root did not serve") + } + + // A flow event reaches a live /api/events subscriber. + ev, err := http.Get(srv.URL + "/api/events") + if err != nil { + t.Fatal(err) + } + defer ev.Body.Close() + got := make(chan string, 1) + go func() { + br := bufio.NewReader(ev.Body) + for { + line, err := br.ReadString('\n') + if err != nil { + return + } + if strings.Contains(line, `"type":"push"`) { + got <- line + return + } + } + }() + for i := 0; i < 20; i++ { // emit until the subscriber (registered async) catches one + d.Emit(Event{Type: "push", Device: "dev1", Share: "proj", Chunks: 3, Bytes: 99}) + select { + case line := <-got: + if !strings.Contains(line, "proj") { + t.Fatalf("event missing share: %s", line) + } + return + case <-time.After(40 * time.Millisecond): + } + } + t.Fatal("did not receive the push event over SSE") +} + +// TestEmitNilSafe documents that hub handlers can Emit unconditionally. +func TestEmitNilSafe(t *testing.T) { + var d *Dashboard + d.Emit(Event{Type: "push"}) // must not panic +} diff --git a/internal/hub/dashboard/index.html b/internal/hub/dashboard/index.html new file mode 100644 index 0000000..090fb59 --- /dev/null +++ b/internal/hub/dashboard/index.html @@ -0,0 +1,5 @@ +devbox hub + + +📦 devbox hub dashboard — loading… + diff --git a/internal/hub/meta/meta.go b/internal/hub/meta/meta.go index c2cb424..3ffafbe 100644 --- a/internal/hub/meta/meta.go +++ b/internal/hub/meta/meta.go @@ -826,6 +826,79 @@ func (d *DB) SnapshotIDs(share string) ([]string, error) { return d.queryStrings(`SELECT id FROM snapshots WHERE share=?`, share) } +// --- dashboard reads ------------------------------------------------------ + +// DeviceRow is a device's detail for the dashboard. +type DeviceRow struct { + ID string + Name string + Principal string + LastSeen int64 + Revoked bool +} + +// Devices lists every device with detail (newest-name order), for the dashboard. +func (d *DB) Devices() ([]DeviceRow, error) { + rows, err := d.sql.Query(`SELECT id, name, COALESCE(last_seen,0), revoked, principal_id FROM devices ORDER BY name`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []DeviceRow + for rows.Next() { + var r DeviceRow + var revoked int + if err := rows.Scan(&r.ID, &r.Name, &r.LastSeen, &revoked, &r.Principal); err != nil { + return nil, err + } + r.Revoked = revoked != 0 + out = append(out, r) + } + return out, rows.Err() +} + +// ShareStat is a share's rolled-up detail for the dashboard. +type ShareStat struct { + Name string + Head string + ACLMode string + Snapshots int + Members int + UpdatedAt int64 // newest snapshot time +} + +// ShareStats rolls up per-share counts for the dashboard in one query. +func (d *DB) ShareStats() ([]ShareStat, error) { + rows, err := d.sql.Query(` + SELECT s.name, COALESCE(s.head_snapshot,''), s.acl_mode, + (SELECT COUNT(*) FROM snapshots sn WHERE sn.share=s.name), + (SELECT COUNT(*) FROM members m WHERE m.share=s.name), + COALESCE((SELECT MAX(created_at) FROM snapshots sn WHERE sn.share=s.name),0) + FROM shares s ORDER BY s.name`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []ShareStat + for rows.Next() { + var s ShareStat + if err := rows.Scan(&s.Name, &s.Head, &s.ACLMode, &s.Snapshots, &s.Members, &s.UpdatedAt); err != nil { + return nil, err + } + out = append(out, s) + } + return out, rows.Err() +} + +// SumChunkBytes returns the total size of all stored chunks (0 if none). +func (d *DB) SumChunkBytes() (int64, error) { + var n sql.NullInt64 + if err := d.sql.QueryRow(`SELECT SUM(size) FROM chunks`).Scan(&n); err != nil { + return 0, err + } + return n.Int64, nil +} + func (d *DB) queryStrings(query string, args ...any) ([]string, error) { rows, err := d.sql.Query(query, args...) if err != nil { diff --git a/internal/hub/server.go b/internal/hub/server.go index dbd68bb..675073f 100644 --- a/internal/hub/server.go +++ b/internal/hub/server.go @@ -18,6 +18,7 @@ import ( "git.shoemoney.ai/shoemoney/devbox/internal/chunk" "git.shoemoney.ai/shoemoney/devbox/internal/hub/blobstore" + "git.shoemoney.ai/shoemoney/devbox/internal/hub/dashboard" "git.shoemoney.ai/shoemoney/devbox/internal/hub/meta" "git.shoemoney.ai/shoemoney/devbox/internal/identity" "git.shoemoney.ai/shoemoney/devbox/pkg/proto" @@ -36,7 +37,8 @@ type Server struct { db *meta.DB store blobstore.Store broker *broker - publishMu sync.Mutex // serializes publish so the case-clash check + create is atomic + dash *dashboard.Dashboard // optional live dashboard; nil = disabled (Emit is nil-safe) + publishMu sync.Mutex // serializes publish so the case-clash check + create is atomic } // NewServer builds a hub server over the given metadata store and blob store. @@ -44,6 +46,9 @@ func NewServer(db *meta.DB, store blobstore.Store) *Server { return &Server{db: db, store: store, broker: newBroker()} } +// WithDashboard attaches a live dashboard so the hub emits flow events to it. +func (s *Server) WithDashboard(d *dashboard.Dashboard) *Server { s.dash = d; return s } + // HashToken returns hex(sha256(token)); the token-mint CLI reuses it so the hub // only ever stores token hashes, never the tokens themselves. func HashToken(token string) string { @@ -156,9 +161,18 @@ func (s *Server) handleJoin(w http.ResponseWriter, r *http.Request) { return } } + s.dash.Emit(dashboard.Event{Type: "join", Device: deviceID, DeviceName: req.Name}) writeJSON(w, http.StatusOK, proto.JoinResponse{DeviceID: deviceID, Bearer: bearer}) } +// shortID truncates a content hash for the dashboard's compact event payloads. +func shortID(id string) string { + if len(id) > 12 { + return id[:12] + } + return id +} + // handleInvite mints an invite token for a share (M8a). The caller's effective // role + reshare bit must permit the requested grant (attenuation, enforced here // server-side so a compromised client can't escalate). On a legacy share the @@ -411,9 +425,18 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request, deviceID str // Only announce a genuine head advance. An idempotent re-push (manifest == // current head) must NOT broadcast, or daemons would storm: pull -> re-push // the same state -> broadcast -> pull -> ... forever. - if req.ManifestHash != head { + advanced := req.ManifestHash != head + if advanced { s.broker.publish(proto.Event{Share: req.Share, Snapshot: snapshotID}) } + var bytes int64 + for _, c := range chunks { + bytes += c.Size + } + s.dash.Emit(dashboard.Event{ + Type: "push", Device: deviceID, Share: req.Share, + Bytes: bytes, Chunks: len(chunks), Snapshot: shortID(snapshotID), NewHead: advanced, + }) writeJSON(w, http.StatusOK, proto.PushResponse{Snapshot: snapshotID, Head: snapshotID, Conflict: false}) }