P1-24: live dashboard — fleet summary tiles + host table
Server-rendered HTML view backed by:
- new store.FleetSummary aggregating host counts + repo bytes +
snapshot total + open alerts + last-24h job rollup in two queries.
- GET /api/hosts (JSON list of hosts in the dashboard projection).
- GET /api/fleet/summary (JSON aggregate, same shape as above).
The HTML page (web/templates/pages/dashboard.html) renders the four
summary tiles + host table directly from store data — no separate
fetch. Per-row state colour comes from .host-row.{degraded,failed,
offline} which paint a 3px left edge so problem hosts are scannable
without reading. HTMX is loaded into the base layout so per-row
"Run now" buttons can hx-post to /hosts/{id}/run-backup, a thin
HTML wrapper that funnels into a new dispatchJob helper shared
with the JSON /api/hosts/{id}/jobs endpoint.
Empty state (zero hosts) collapses to the "no hosts yet" prompt
with the + Add host CTA — matches the v1 mockup.
Template helpers (internal/server/ui/funcs.go) added for byte
formatting (412 GB / 3.7 TB), relative time (3m ago / 2d ago), and
comma grouping (1,847). Pure Go, no template-magic dependency.
Browser-verified end-to-end with seeded fixture data: five hosts
across all four states render with correct dots, accents, last-
backup pills, sizes, snapshot counts, alerts, tags, and the right
action button (Run now / Retry / Run first / View → / offline).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
stdhttp "net/http"
|
||||
|
||||
"gitea.dcglab.co.uk/steve/restic-manager/internal/store"
|
||||
)
|
||||
|
||||
// hostView is the JSON projection of a Host row. Same shape as the
|
||||
// store row, but with explicit time-strings so wire format is stable
|
||||
// across DB driver changes.
|
||||
type hostView struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
OS string `json:"os"`
|
||||
Arch string `json:"arch"`
|
||||
AgentVersion string `json:"agent_version,omitempty"`
|
||||
ResticVersion string `json:"restic_version,omitempty"`
|
||||
ProtocolVersion int `json:"protocol_version"`
|
||||
EnrolledAt string `json:"enrolled_at"`
|
||||
LastSeenAt *string `json:"last_seen_at,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Tags []string `json:"tags"`
|
||||
CurrentJobID *string `json:"current_job_id,omitempty"`
|
||||
LastBackupAt *string `json:"last_backup_at,omitempty"`
|
||||
LastBackupStatus *string `json:"last_backup_status,omitempty"`
|
||||
RepoSizeBytes int64 `json:"repo_size_bytes"`
|
||||
SnapshotCount int `json:"snapshot_count"`
|
||||
OpenAlertCount int `json:"open_alert_count"`
|
||||
}
|
||||
|
||||
// handleListHosts returns the full fleet as JSON. Authenticated; the
|
||||
// shape mirrors what the dashboard renders, so external API consumers
|
||||
// see the same projection.
|
||||
func (s *Server) handleListHosts(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
return
|
||||
}
|
||||
hosts, err := s.deps.Store.ListHosts(r.Context())
|
||||
if err != nil {
|
||||
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "")
|
||||
return
|
||||
}
|
||||
out := make([]hostView, 0, len(hosts))
|
||||
for _, h := range hosts {
|
||||
out = append(out, hostToView(h))
|
||||
}
|
||||
writeJSON(w, stdhttp.StatusOK, map[string]any{
|
||||
"count": len(out),
|
||||
"hosts": out,
|
||||
})
|
||||
}
|
||||
|
||||
// handleFleetSummary returns the dashboard tile aggregate.
|
||||
func (s *Server) handleFleetSummary(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
return
|
||||
}
|
||||
fs, err := s.deps.Store.FleetSummary(r.Context())
|
||||
if err != nil {
|
||||
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "")
|
||||
return
|
||||
}
|
||||
writeJSON(w, stdhttp.StatusOK, fs)
|
||||
}
|
||||
|
||||
// hostToView converts a store.Host to its JSON shape. Times become
|
||||
// RFC 3339 strings; nullable times are passed through as nil.
|
||||
func hostToView(h store.Host) hostView {
|
||||
v := hostView{
|
||||
ID: h.ID,
|
||||
Name: h.Name,
|
||||
OS: h.OS,
|
||||
Arch: h.Arch,
|
||||
AgentVersion: h.AgentVersion,
|
||||
ResticVersion: h.ResticVersion,
|
||||
ProtocolVersion: h.ProtocolVersion,
|
||||
EnrolledAt: h.EnrolledAt.Format("2006-01-02T15:04:05.000000000Z"),
|
||||
Status: h.Status,
|
||||
Tags: h.Tags,
|
||||
CurrentJobID: h.CurrentJobID,
|
||||
LastBackupStatus: h.LastBackupStatus,
|
||||
RepoSizeBytes: h.RepoSizeBytes,
|
||||
SnapshotCount: h.SnapshotCount,
|
||||
OpenAlertCount: h.OpenAlertCount,
|
||||
}
|
||||
if v.Tags == nil {
|
||||
v.Tags = []string{}
|
||||
}
|
||||
if h.LastSeenAt != nil {
|
||||
s := h.LastSeenAt.Format("2006-01-02T15:04:05.000000000Z")
|
||||
v.LastSeenAt = &s
|
||||
}
|
||||
if h.LastBackupAt != nil {
|
||||
s := h.LastBackupAt.Format("2006-01-02T15:04:05.000000000Z")
|
||||
v.LastBackupAt = &s
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
stdhttp "net/http"
|
||||
"time"
|
||||
@@ -33,65 +34,76 @@ func (s *Server) handleRunNow(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
return
|
||||
}
|
||||
|
||||
hostID := chi.URLParam(r, "id")
|
||||
if hostID == "" {
|
||||
writeJSONError(w, stdhttp.StatusBadRequest, "missing_host_id", "")
|
||||
return
|
||||
}
|
||||
|
||||
var req runNowRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSONError(w, stdhttp.StatusBadRequest, "invalid_json", err.Error())
|
||||
return
|
||||
}
|
||||
if !validJobKind(req.Kind) {
|
||||
writeJSONError(w, stdhttp.StatusBadRequest, "invalid_kind",
|
||||
"kind must be one of backup|forget|prune|check|unlock")
|
||||
|
||||
res, status, code, msg := s.dispatchJob(r.Context(), user, hostID, req.Kind, req.Args)
|
||||
if code != "" {
|
||||
writeJSONError(w, status, code, msg)
|
||||
return
|
||||
}
|
||||
writeJSON(w, stdhttp.StatusAccepted, res)
|
||||
}
|
||||
|
||||
host, err := s.deps.Store.GetHost(r.Context(), hostID)
|
||||
// dispatchJob is the common path for HTTP-driven job dispatch. It
|
||||
// validates the kind, checks the host is online, persists the job
|
||||
// row, and ships command.run over the WS. Returns:
|
||||
// - res: the queued-job response (job_id + status)
|
||||
// - status: HTTP status to return on failure (or 0 on success)
|
||||
// - code, msg: error code/message for the wire (empty on success)
|
||||
//
|
||||
// JSON callers wrap with writeJSONError; HTML callers translate to
|
||||
// flash banner + redirect.
|
||||
func (s *Server) dispatchJob(ctx context.Context, user *store.User,
|
||||
hostID string, kind api.JobKind, args []string,
|
||||
) (res runNowResponse, status int, code, msg string) {
|
||||
if !validJobKind(kind) {
|
||||
return res, stdhttp.StatusBadRequest, "invalid_kind",
|
||||
"kind must be one of backup|forget|prune|check|unlock"
|
||||
}
|
||||
host, err := s.deps.Store.GetHost(ctx, hostID)
|
||||
if err != nil {
|
||||
writeJSONError(w, stdhttp.StatusNotFound, "host_not_found", "")
|
||||
return
|
||||
return res, stdhttp.StatusNotFound, "host_not_found", ""
|
||||
}
|
||||
|
||||
if !s.deps.Hub.Connected(host.ID) {
|
||||
writeJSONError(w, stdhttp.StatusServiceUnavailable, "host_offline",
|
||||
"agent is not currently connected; try again when it reconnects")
|
||||
return
|
||||
return res, stdhttp.StatusServiceUnavailable, "host_offline",
|
||||
"agent is not currently connected; try again when it reconnects"
|
||||
}
|
||||
|
||||
jobID := ulid.Make().String()
|
||||
now := time.Now().UTC()
|
||||
if err := s.deps.Store.CreateJob(r.Context(), store.Job{
|
||||
if err := s.deps.Store.CreateJob(ctx, store.Job{
|
||||
ID: jobID,
|
||||
HostID: host.ID,
|
||||
Kind: string(req.Kind),
|
||||
Kind: string(kind),
|
||||
ActorKind: "user",
|
||||
ActorID: &user.ID,
|
||||
CreatedAt: now,
|
||||
}); err != nil {
|
||||
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "")
|
||||
return
|
||||
return res, stdhttp.StatusInternalServerError, "internal", ""
|
||||
}
|
||||
|
||||
env, err := api.Marshal(api.MsgCommandRun, jobID, api.CommandRunPayload{
|
||||
JobID: jobID,
|
||||
Kind: req.Kind,
|
||||
Args: req.Args,
|
||||
Kind: kind,
|
||||
Args: args,
|
||||
})
|
||||
if err != nil {
|
||||
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "")
|
||||
return
|
||||
return res, stdhttp.StatusInternalServerError, "internal", ""
|
||||
}
|
||||
if err := s.deps.Hub.Send(r.Context(), host.ID, env); err != nil {
|
||||
writeJSONError(w, stdhttp.StatusServiceUnavailable, "host_offline", err.Error())
|
||||
return
|
||||
if err := s.deps.Hub.Send(ctx, host.ID, env); err != nil {
|
||||
return res, stdhttp.StatusServiceUnavailable, "host_offline", err.Error()
|
||||
}
|
||||
|
||||
_ = s.deps.Store.AppendAudit(r.Context(), store.AuditEntry{
|
||||
_ = s.deps.Store.AppendAudit(ctx, store.AuditEntry{
|
||||
ID: ulid.Make().String(),
|
||||
UserID: &user.ID,
|
||||
Actor: "user",
|
||||
@@ -100,11 +112,7 @@ func (s *Server) handleRunNow(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
TargetID: &jobID,
|
||||
TS: now,
|
||||
})
|
||||
|
||||
writeJSON(w, stdhttp.StatusAccepted, runNowResponse{
|
||||
JobID: jobID,
|
||||
Status: "queued",
|
||||
})
|
||||
return runNowResponse{JobID: jobID, Status: "queued"}, 0, "", ""
|
||||
}
|
||||
|
||||
// requireUser resolves the session cookie to a user row. Stub of the
|
||||
|
||||
@@ -88,6 +88,10 @@ func (s *Server) routes(r chi.Router) {
|
||||
// host page can call it; for now just the create endpoint.
|
||||
r.Post("/enrollment-tokens", s.handleCreateEnrollmentToken)
|
||||
|
||||
// Fleet read endpoints — back the dashboard.
|
||||
r.Get("/hosts", s.handleListHosts)
|
||||
r.Get("/fleet/summary", s.handleFleetSummary)
|
||||
|
||||
// Run-now: dispatch a job to a host's agent.
|
||||
r.Post("/hosts/{id}/jobs", s.handleRunNow)
|
||||
|
||||
@@ -127,6 +131,8 @@ func (s *Server) routes(r chi.Router) {
|
||||
r.Get("/login", s.handleUILoginGet)
|
||||
r.Post("/login", s.handleUILoginPost)
|
||||
r.Post("/logout", s.handleUILogoutPost)
|
||||
// HTMX action endpoint for "Run now" buttons on the dashboard.
|
||||
r.Post("/hosts/{id}/run-backup", s.handleUIRunBackup)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@ import (
|
||||
"log/slog"
|
||||
stdhttp "net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"gitea.dcglab.co.uk/steve/restic-manager/internal/api"
|
||||
"gitea.dcglab.co.uk/steve/restic-manager/internal/auth"
|
||||
"gitea.dcglab.co.uk/steve/restic-manager/internal/server/ui"
|
||||
"gitea.dcglab.co.uk/steve/restic-manager/internal/store"
|
||||
@@ -91,6 +94,13 @@ func (s *Server) version() string {
|
||||
|
||||
// ----- handlers -------------------------------------------------------
|
||||
|
||||
// dashboardPage is the data the dashboard template renders against.
|
||||
type dashboardPage struct {
|
||||
Hosts []store.Host
|
||||
HostCount int
|
||||
Summary store.FleetSummary
|
||||
}
|
||||
|
||||
// handleUIDashboard is the root page. Auth-gated; falls through to
|
||||
// /login if there is no session.
|
||||
func (s *Server) handleUIDashboard(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
@@ -98,13 +108,76 @@ func (s *Server) handleUIDashboard(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
||||
if u == nil {
|
||||
return
|
||||
}
|
||||
|
||||
hosts, err := s.deps.Store.ListHosts(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("ui dashboard: list hosts", "err", err)
|
||||
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
summary, err := s.deps.Store.FleetSummary(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("ui dashboard: fleet summary", "err", err)
|
||||
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
view := s.baseView(u, "dashboard")
|
||||
view.OpenAlerts = summary.OpenAlerts
|
||||
view.Page = dashboardPage{
|
||||
Hosts: hosts,
|
||||
HostCount: len(hosts),
|
||||
Summary: summary,
|
||||
}
|
||||
if err := s.deps.UI.Render(w, "dashboard", view); err != nil {
|
||||
slog.Error("ui: render dashboard", "err", err)
|
||||
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// handleUIRunBackup is the form-submit twin of POST /api/hosts/{id}/jobs
|
||||
// that the dashboard's "Run now" buttons call via hx-post. Returns
|
||||
// 204 on success — HTMX swap=none means "did the thing, no DOM
|
||||
// change needed." Failures return text in the body so HTMX's
|
||||
// response-header inspection surfaces it.
|
||||
func (s *Server) handleUIRunBackup(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
u := s.requireUIUser(w, r)
|
||||
if u == nil {
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
if hostID == "" {
|
||||
stdhttp.Error(w, "missing host id", stdhttp.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
storeUser, _, err := s.userByID(r, u.ID)
|
||||
if err != nil {
|
||||
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
_, status, code, msg := s.dispatchJob(r.Context(), storeUser, hostID, api.JobBackup, nil)
|
||||
if code != "" {
|
||||
stdhttp.Error(w, msg, status)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(stdhttp.StatusNoContent)
|
||||
}
|
||||
|
||||
// userByID fetches the full store.User the UI session represents.
|
||||
// Returns the user, ok-flag, error. Used by handlers that need the
|
||||
// store-side row (e.g. for audit_log.user_id) rather than just the
|
||||
// projected ui.User.
|
||||
func (s *Server) userByID(r *stdhttp.Request, id string) (*store.User, bool, error) {
|
||||
u, err := s.deps.Store.GetUserByID(r.Context(), id)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return nil, false, nil
|
||||
}
|
||||
return nil, false, err
|
||||
}
|
||||
return u, true, nil
|
||||
}
|
||||
|
||||
// handleUILoginGet renders the login form. If the user is already
|
||||
// signed in we redirect them home — login is for the unauthenticated.
|
||||
func (s *Server) handleUILoginGet(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// funcMap returns the template functions every page can call.
|
||||
// Kept small on purpose: anything fancier belongs in the handler,
|
||||
// which can pre-compute and pass primitives into the view.
|
||||
func funcMap() template.FuncMap {
|
||||
return template.FuncMap{
|
||||
"bytes": formatBytes,
|
||||
"relTime": formatRelTime,
|
||||
"comma": formatComma,
|
||||
"deref": derefStr,
|
||||
"timeNotZero": func(t *time.Time) bool { return t != nil && !t.IsZero() },
|
||||
}
|
||||
}
|
||||
|
||||
// formatBytes renders a byte count as a short human string —
|
||||
// "412 GB", "3.7 TB", "8.4 GB". Single decimal place for sub-1000
|
||||
// values, none above. Returns "—" for zero so the dashboard's
|
||||
// "never run" rows read clean.
|
||||
func formatBytes(n int64) template.HTML {
|
||||
if n == 0 {
|
||||
return template.HTML(`<span class="text-ink-fade">—</span>`)
|
||||
}
|
||||
const (
|
||||
kb = 1000
|
||||
mb = 1000 * kb
|
||||
gb = 1000 * mb
|
||||
tb = 1000 * gb
|
||||
)
|
||||
var (
|
||||
val float64
|
||||
unit string
|
||||
)
|
||||
switch {
|
||||
case n >= tb:
|
||||
val, unit = float64(n)/float64(tb), "TB"
|
||||
case n >= gb:
|
||||
val, unit = float64(n)/float64(gb), "GB"
|
||||
case n >= mb:
|
||||
val, unit = float64(n)/float64(mb), "MB"
|
||||
case n >= kb:
|
||||
val, unit = float64(n)/float64(kb), "kB"
|
||||
default:
|
||||
return template.HTML(fmt.Sprintf(`%d <span class="text-ink-mute text-[11px]">B</span>`, n))
|
||||
}
|
||||
num := strconv.FormatFloat(val, 'f', -1, 64)
|
||||
if val < 100 && !strings.Contains(num, ".") {
|
||||
num += ".0"
|
||||
} else if val < 100 && strings.Contains(num, ".") {
|
||||
// One decimal max, e.g. "3.7" not "3.74".
|
||||
idx := strings.Index(num, ".")
|
||||
if len(num) > idx+2 {
|
||||
num = num[:idx+2]
|
||||
}
|
||||
} else {
|
||||
// Above 100, no decimals — "412" not "412.4".
|
||||
if idx := strings.Index(num, "."); idx > 0 {
|
||||
num = num[:idx]
|
||||
}
|
||||
}
|
||||
return template.HTML(fmt.Sprintf(`%s <span class="text-ink-mute text-[11px]">%s</span>`, num, unit))
|
||||
}
|
||||
|
||||
// formatRelTime renders a *time.Time as a short relative string like
|
||||
// "3m ago" / "2d ago" / "5w ago". Future times render as "in Xs".
|
||||
// Nil pointer returns "—".
|
||||
func formatRelTime(t *time.Time) string {
|
||||
if t == nil || t.IsZero() {
|
||||
return "—"
|
||||
}
|
||||
d := time.Since(*t)
|
||||
suffix := "ago"
|
||||
if d < 0 {
|
||||
d = -d
|
||||
suffix = "from now"
|
||||
}
|
||||
switch {
|
||||
case d < time.Minute:
|
||||
return fmt.Sprintf("%ds %s", int(d.Seconds()), suffix)
|
||||
case d < time.Hour:
|
||||
return fmt.Sprintf("%dm %s", int(d.Minutes()), suffix)
|
||||
case d < 24*time.Hour:
|
||||
return fmt.Sprintf("%dh %s", int(d.Hours()), suffix)
|
||||
case d < 7*24*time.Hour:
|
||||
return fmt.Sprintf("%dd %s", int(d.Hours()/24), suffix)
|
||||
default:
|
||||
return fmt.Sprintf("%dw %s", int(d.Hours()/(24*7)), suffix)
|
||||
}
|
||||
}
|
||||
|
||||
// formatComma renders 1847 as "1,847". Used for snapshot counts and
|
||||
// any other count that benefits from grouping at this scale.
|
||||
func formatComma(n int) string {
|
||||
s := strconv.Itoa(n)
|
||||
if n < 1000 && n > -1000 {
|
||||
return s
|
||||
}
|
||||
// Hand-rolled grouping; Go has no builtin and we don't want a
|
||||
// dep for this. Negative numbers handled by stripping the sign,
|
||||
// grouping, then putting it back.
|
||||
neg := false
|
||||
if s[0] == '-' {
|
||||
neg = true
|
||||
s = s[1:]
|
||||
}
|
||||
var b strings.Builder
|
||||
for i, c := range s {
|
||||
if i > 0 && (len(s)-i)%3 == 0 {
|
||||
b.WriteByte(',')
|
||||
}
|
||||
b.WriteRune(c)
|
||||
}
|
||||
if neg {
|
||||
return "-" + b.String()
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// derefStr returns the string a pointer points to, or "" if nil.
|
||||
// Avoids "<nil>" appearing in templates that hit a missing FK.
|
||||
func derefStr(p *string) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
return *p
|
||||
}
|
||||
@@ -88,6 +88,7 @@ func New() (*Renderer, error) {
|
||||
"templates/layouts/base.html",
|
||||
"templates/layouts/chromeless.html",
|
||||
"templates/partials/nav.html",
|
||||
"templates/partials/host_row.html",
|
||||
}
|
||||
|
||||
pageEntries, err := fs.Glob(web.FS, "templates/pages/*.html")
|
||||
@@ -101,7 +102,8 @@ func New() (*Renderer, error) {
|
||||
r := &Renderer{pages: make(map[string]*template.Template, len(pageEntries))}
|
||||
for _, p := range pageEntries {
|
||||
base := strings.TrimSuffix(path.Base(p), ".html")
|
||||
t, err := template.New(base).ParseFS(web.FS, append(append([]string{}, commonPaths...), p)...)
|
||||
t, err := template.New(base).Funcs(funcMap()).
|
||||
ParseFS(web.FS, append(append([]string{}, commonPaths...), p)...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ui: parse %s: %w", p, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// FleetSummary is the aggregated view that powers the dashboard's
|
||||
// summary tiles. All numbers are point-in-time snapshots; the
|
||||
// caller polls.
|
||||
type FleetSummary struct {
|
||||
TotalHosts int
|
||||
HostsOnline int
|
||||
HostsDegraded int
|
||||
HostsOffline int
|
||||
|
||||
RepoBytesTotal int64
|
||||
SnapshotsTotal int
|
||||
OpenAlerts int
|
||||
|
||||
// Last-24h job rollup. JobsTotal includes every status; the
|
||||
// breakdown sums to it (modulo any in-flight queued/running).
|
||||
JobsLast24h int
|
||||
JobsLast24hSucceeded int
|
||||
JobsLast24hFailed int
|
||||
JobsLast24hCancelled int
|
||||
}
|
||||
|
||||
// FleetSummary aggregates host + job stats in two queries. Cheap on
|
||||
// SQLite at Phase 1 scale (12 hosts, a few hundred jobs/day) — no
|
||||
// caching layer; the tile is regenerated on every dashboard render.
|
||||
func (s *Store) FleetSummary(ctx context.Context) (FleetSummary, error) {
|
||||
var fs FleetSummary
|
||||
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT
|
||||
COUNT(*),
|
||||
COALESCE(SUM(CASE WHEN status = 'online' THEN 1 ELSE 0 END), 0),
|
||||
COALESCE(SUM(CASE WHEN status = 'degraded' THEN 1 ELSE 0 END), 0),
|
||||
COALESCE(SUM(CASE WHEN status = 'offline' THEN 1 ELSE 0 END), 0),
|
||||
COALESCE(SUM(repo_size_bytes), 0),
|
||||
COALESCE(SUM(snapshot_count), 0),
|
||||
COALESCE(SUM(open_alert_count), 0)
|
||||
FROM hosts`)
|
||||
if err := row.Scan(
|
||||
&fs.TotalHosts, &fs.HostsOnline, &fs.HostsDegraded, &fs.HostsOffline,
|
||||
&fs.RepoBytesTotal, &fs.SnapshotsTotal, &fs.OpenAlerts,
|
||||
); err != nil {
|
||||
return FleetSummary{}, fmt.Errorf("store: fleet summary hosts: %w", err)
|
||||
}
|
||||
|
||||
cutoff := time.Now().Add(-24 * time.Hour).UTC().Format(time.RFC3339Nano)
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT status, COUNT(*) FROM jobs WHERE created_at > ? GROUP BY status`,
|
||||
cutoff)
|
||||
if err != nil {
|
||||
return FleetSummary{}, fmt.Errorf("store: fleet summary jobs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var status string
|
||||
var n int
|
||||
if err := rows.Scan(&status, &n); err != nil {
|
||||
return FleetSummary{}, fmt.Errorf("store: fleet summary scan: %w", err)
|
||||
}
|
||||
fs.JobsLast24h += n
|
||||
switch status {
|
||||
case "succeeded":
|
||||
fs.JobsLast24hSucceeded = n
|
||||
case "failed":
|
||||
fs.JobsLast24hFailed = n
|
||||
case "cancelled":
|
||||
fs.JobsLast24hCancelled = n
|
||||
}
|
||||
}
|
||||
return fs, rows.Err()
|
||||
}
|
||||
Reference in New Issue
Block a user