feat(datasource): Prometheus queries, YAML config, and query_range braille pipeline

Phase 2 + Phase 3 of the v0.1 MVP.

Phase 2 — instant queries + native config:
- internal/datasource: Datasource interface at the consumer boundary
  (QueryInstant/QueryRange) with Instant/Range request types.
- internal/datasource/prom: client_golang-backed impl; {{label}} legend
  expansion; NaN samples dropped.
- internal/config: canonical Dashboard/WidgetSpec model + strict YAML loader
  (KnownFields, validation, defaults).
- internal/app: BuildWidget spec→widget factory.
- cmd/grot run: --config/--prom/--theme/--watch; per-widget ctx timeout so one
  slow/failing query never breaks the grid.

Phase 3 — query_range + braille timeseries:
- internal/app/step: StepFor(range, chartWidth) — chartWidth×2 dots → step
  rounded up a clean ladder, 10s floor; sample count never exceeds the dot
  budget (table + invariant tests).
- cmd/grot run: layout planned once per tick so fetch (step sizing) and draw
  share widths; timeseries routed through QueryRange; --ascii block fallback.
- examples/pilot.yaml: p95 execution + stacked tokens-by-model timeseries.

Known gap: range NaN points are dropped rather than
kept as positional gaps, which collapses the time axis for sparse series and
would misalign stacked multi-series. To be addressed before stacked ships.
This commit is contained in:
Aleks Petrov committed 2026-07-07 15:09:48 +02:00
1 parent 0c118ff95f
commit 4cfb29e515
15 files changed
+1187 -1

No files matched your search

+1
View File
@@ -23,6 +23,7 @@ Import your existing Grafana dashboard JSON or write a simple YAML config.`,
}
root.AddCommand(demoCmd())
root.AddCommand(runCmd())
root.AddCommand(&cobra.Command{
Use: "version",
Short: "Print version",
+272
View File
@@ -0,0 +1,272 @@
package main
import (
"context"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/charmbracelet/lipgloss"
"github.com/spf13/cobra"
"golang.org/x/term"
"github.com/qf-studio/grot/internal/app"
"github.com/qf-studio/grot/internal/config"
"github.com/qf-studio/grot/internal/datasource"
"github.com/qf-studio/grot/internal/datasource/prom"
"github.com/qf-studio/grot/pkg/tui/render"
"github.com/qf-studio/grot/pkg/tui/theme"
"github.com/qf-studio/grot/pkg/tui/widget"
)
func runCmd() *cobra.Command {
var (
cfgPath string
promAddr string
themeName string
watch bool
ascii bool
)
cmd := &cobra.Command{
Use: "run",
Short: "Render a dashboard config against a live Prometheus",
RunE: func(cmd *cobra.Command, _ []string) error {
dash, err := config.Load(cfgPath)
if err != nil {
return err
}
ds, err := prom.New(promAddr)
if err != nil {
return err
}
th := theme.ByName(coalesce(themeName, dash.Theme))
widgets := make([]widget.Widget, len(dash.Widgets))
for i, spec := range dash.Widgets {
w, err := app.BuildWidget(spec)
if err != nil {
return fmt.Errorf("widget %d: %w", i, err)
}
if ascii {
if ts, ok := w.(*widget.TimeSeries); ok {
ts.Solid = true
}
}
widgets[i] = w
}
refresh := dash.Refresh.Duration()
renderFrame := func(ctx context.Context) string {
// Lay out once per tick so fetch (range-query step sizing) and
// draw share the same cell widths, and both track a resize.
lay := planLayout(dash.Widgets, termWidth())
fetchAll(ctx, ds, dash, widgets, lay, refresh)
return frame(dash, widgets, th, lay)
}
if !watch {
fmt.Println(renderFrame(cmd.Context()))
return nil
}
return watchLoop(cmd.Context(), refresh, renderFrame)
},
}
cmd.Flags().StringVarP(&cfgPath, "config", "c", "", "dashboard YAML config (required)")
cmd.Flags().StringVar(&promAddr, "prom", "http://localhost:9090", "Prometheus base URL")
cmd.Flags().StringVar(&themeName, "theme", "", "override theme (default: config theme)")
cmd.Flags().BoolVarP(&watch, "watch", "w", false, "refresh on the config interval until Ctrl-C")
cmd.Flags().BoolVar(&ascii, "ascii", false, "block-character charts instead of braille")
_ = cmd.MarkFlagRequired("config")
return cmd
}
// fetchAll runs each widget's queries and delivers results (or errors). A slow
// or failing query only affects its own widget — the grid never breaks. The
// layout supplies each widget's cell size so range queries can size their step
// to the chart width.
func fetchAll(ctx context.Context, ds datasource.Datasource, dash *config.Dashboard, widgets []widget.Widget, lay layout, refresh time.Duration) {
timeout := 10 * time.Second
if refresh > 0 && refresh < timeout {
timeout = refresh
}
rng := dash.Range.Duration()
for i, spec := range dash.Widgets {
chartW, _ := render.InnerSize(lay.cells[i].W, lay.cells[i].H)
cctx, cancel := context.WithTimeout(ctx, timeout)
res, err := fetchWidget(cctx, ds, spec, chartW, rng)
cancel()
if err != nil {
widgets[i].SetError(err)
continue
}
widgets[i].SetResult(res)
}
}
func fetchWidget(ctx context.Context, ds datasource.Datasource, spec config.WidgetSpec, chartW int, rng time.Duration) (widget.QueryResult, error) {
var all []widget.Series
for _, q := range spec.Queries {
var (
s []widget.Series
err error
)
if useRange(spec, q) {
end := time.Now()
s, err = ds.QueryRange(ctx, datasource.Range{
Expr: q.Expr,
Legend: q.Legend,
Start: end.Add(-rng),
End: end,
Step: app.StepFor(rng, chartW),
})
} else {
s, err = ds.QueryInstant(ctx, datasource.Instant{Expr: q.Expr, Legend: q.Legend})
}
if err != nil {
return widget.QueryResult{}, err
}
all = append(all, s...)
}
return widget.QueryResult{Series: all, FetchedAt: time.Now()}, nil
}
// useRange decides whether a query runs as query_range. Time-series panels need
// a range to draw a line; single-value panels (stat/gauge/bargauge) reduce to
// one point and stay instant. A query may opt back into instant via Instant.
func useRange(spec config.WidgetSpec, q config.Query) bool {
return spec.Type == config.TypeTimeSeries && !q.Instant
}
// frame renders the header plus the packed grid described by lay.
func frame(dash *config.Dashboard, widgets []widget.Widget, th theme.Theme, lay layout) string {
header := th.AccentStyle().Bold(true).Render(" "+coalesce(dash.Title, "grot")) +
th.DimStyle().Render(" · "+time.Now().Format("15:04:05")+" · "+th.Name)
return header + "\n" + packRows(widgets, th, lay)
}
// cellPlan is one widget's outer cell size within the packed grid.
type cellPlan struct{ W, H int }
// layout is the resolved placement for a frame: per-widget cell sizes plus the
// grouping of widget indices into rows. Computed once per tick so fetch and
// draw agree on widths.
type layout struct {
cells []cellPlan
rows [][]int
}
// planLayout packs widgets left-to-right into rows, even-splitting each row's
// width. Phase 3 uses this simple split; the 24-column grid engine arrives in
// Phase 4.
func planLayout(specs []config.WidgetSpec, termW int) layout {
perRow := termW / 34
if perRow < 1 {
perRow = 1
}
if perRow > 4 {
perRow = 4
}
lay := layout{cells: make([]cellPlan, len(specs))}
for start := 0; start < len(specs); start += perRow {
end := start + perRow
if end > len(specs) {
end = len(specs)
}
n := end - start
colW := termW / n
rowH := 0
for i := start; i < end; i++ {
if h := typeHeight(specs[i].Type); h > rowH {
rowH = h
}
}
row := make([]int, 0, n)
for i := start; i < end; i++ {
cellW := colW
if i == end-1 {
cellW = termW - colW*(n-1) // last column absorbs the remainder
}
lay.cells[i] = cellPlan{W: cellW, H: rowH}
row = append(row, i)
}
lay.rows = append(lay.rows, row)
}
return lay
}
// packRows draws the widgets at the sizes fixed by lay.
func packRows(widgets []widget.Widget, th theme.Theme, lay layout) string {
rows := make([]string, 0, len(lay.rows))
for _, idxs := range lay.rows {
cols := make([]string, 0, len(idxs))
for _, i := range idxs {
c := lay.cells[i]
cols = append(cols, widgets[i].Render(c.W, c.H, th, false))
}
rows = append(rows, lipgloss.JoinHorizontal(lipgloss.Top, cols...))
}
return strings.Join(rows, "\n")
}
func typeHeight(t config.WidgetType) int {
switch t {
case config.TypeStat:
return 6
case config.TypeGauge:
return 7
case config.TypeBarGauge:
return 8
case config.TypeTimeSeries:
return 10
}
return 6
}
// watchLoop clears the screen and re-renders on the refresh interval until the
// context is cancelled or an interrupt arrives.
func watchLoop(ctx context.Context, refresh time.Duration, render func(context.Context) string) error {
if refresh <= 0 {
refresh = 30 * time.Second
}
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
draw := func() {
fmt.Print("\033[H\033[2J") // cursor home + clear screen
fmt.Println(render(ctx))
}
draw()
t := time.NewTicker(refresh)
defer t.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-t.C:
draw()
}
}
}
func termWidth() int {
if w, _, err := term.GetSize(int(os.Stdout.Fd())); err == nil && w > 40 {
return w
}
return 100
}
func coalesce(vals ...string) string {
for _, v := range vals {
if v != "" {
return v
}
}
return ""
}
+61
View File
@@ -0,0 +1,61 @@
# grot native dashboard config — Pilot metrics from Prometheus.
# Run: grot run --config examples/pilot.yaml --prom http://localhost:9093
title: pilot
theme: pilot
refresh: 30s
range: 15m
widgets:
- type: stat
title: executions
unit: short
queries:
- expr: sum(pilot_executions_total)
- type: stat
title: tokens
unit: short
queries:
- expr: sum(pilot_tokens_consumed_total)
- type: stat
title: cost
unit: currencyUSD
decimals: 2
queries:
- expr: sum(pilot_execution_cost_usd_total)
- type: stat
title: active prs
unit: short
queries:
- expr: sum(pilot_active_prs)
- type: gauge
title: success rate
unit: percentunit
min: 0
max: 1
thresholds:
- color: red
- value: 0.8
color: yellow
- value: 0.95
color: green
queries:
- expr: pilot_success_rate
- type: timeseries
title: p95 execution
unit: s
queries:
- expr: histogram_quantile(0.95, sum(rate(pilot_execution_duration_seconds_bucket[5m])) by (le))
legend: p95
- type: timeseries
title: tokens by model
unit: short
stacked: true
queries:
- expr: sum(rate(pilot_tokens_consumed_total[5m])) by (model)
legend: "{{model}}"
+10
View File
@@ -4,8 +4,11 @@ go 1.25.6
require (
github.com/charmbracelet/lipgloss v1.1.0
github.com/prometheus/client_golang v1.23.2
github.com/prometheus/common v0.66.1
github.com/spf13/cobra v1.10.2
golang.org/x/term v0.44.0
gopkg.in/yaml.v3 v3.0.1
)
require (
@@ -15,12 +18,19 @@ require (
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/muesli/termenv v0.16.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.9 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/sys v0.46.0 // indirect
google.golang.org/protobuf v1.36.8 // indirect
)
+58
View File
@@ -1,5 +1,9 @@
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
@@ -11,32 +15,86 @@ github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA=
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+SVif2QVs3tOP0zanoHgBEVAwHxUSIzRqU=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+58
View File
@@ -0,0 +1,58 @@
// Package app wires the canonical config model to renderable widgets and (in
// later phases) the Bubble Tea application shell.
package app
import (
"fmt"
"github.com/qf-studio/grot/internal/config"
"github.com/qf-studio/grot/pkg/tui/widget"
)
// BuildWidget constructs a renderable widget from a spec.
func BuildWidget(spec config.WidgetSpec) (widget.Widget, error) {
thresholds := convertThresholds(spec.Thresholds)
switch spec.Type {
case config.TypeStat:
w := widget.NewStat(spec.Title, spec.Unit)
w.Decimals = spec.Decimals
w.Thresholds = thresholds
return w, nil
case config.TypeGauge:
var min, max float64
if spec.Min != nil {
min = *spec.Min
}
if spec.Max != nil {
max = *spec.Max
}
w := widget.NewGauge(spec.Title, spec.Unit, min, max)
w.Decimals = spec.Decimals
w.Thresholds = thresholds
return w, nil
case config.TypeBarGauge:
w := widget.NewBarGauge(spec.Title, spec.Unit)
w.Decimals = spec.Decimals
w.Max = spec.Max
w.Thresholds = thresholds
return w, nil
case config.TypeTimeSeries:
w := widget.NewTimeSeries(spec.Title, spec.Unit)
w.Decimals = spec.Decimals
w.Stacked = spec.Stacked
return w, nil
default:
return nil, fmt.Errorf("unknown widget type %q", spec.Type)
}
}
func convertThresholds(ts []config.Threshold) []widget.Threshold {
if len(ts) == 0 {
return nil
}
out := make([]widget.Threshold, len(ts))
for i, t := range ts {
out[i] = widget.Threshold{Value: t.Value, Color: t.Color}
}
return out
}
+61
View File
@@ -0,0 +1,61 @@
package app
import (
"testing"
"github.com/qf-studio/grot/internal/config"
"github.com/qf-studio/grot/pkg/tui/widget"
)
func fptr(v float64) *float64 { return &v }
func iptr(v int) *int { return &v }
func TestBuildWidgetTypes(t *testing.T) {
stat, err := BuildWidget(config.WidgetSpec{
Type: config.TypeStat, Title: "s", Unit: "short", Decimals: iptr(1),
Thresholds: []config.Threshold{{Color: "red"}, {Value: fptr(5), Color: "green"}},
})
if err != nil {
t.Fatal(err)
}
s, ok := stat.(*widget.Stat)
if !ok {
t.Fatalf("stat type: %T", stat)
}
if len(s.Thresholds) != 2 || s.Thresholds[1].Value == nil || *s.Thresholds[1].Value != 5 {
t.Errorf("stat thresholds: %+v", s.Thresholds)
}
if s.Decimals == nil || *s.Decimals != 1 {
t.Errorf("stat decimals: %v", s.Decimals)
}
g, err := BuildWidget(config.WidgetSpec{Type: config.TypeGauge, Unit: "percentunit", Min: fptr(0), Max: fptr(1)})
if err != nil {
t.Fatal(err)
}
if gg := g.(*widget.Gauge); gg.Min != 0 || gg.Max != 1 {
t.Errorf("gauge min/max: %v/%v", gg.Min, gg.Max)
}
b, err := BuildWidget(config.WidgetSpec{Type: config.TypeBarGauge, Max: fptr(100)})
if err != nil {
t.Fatal(err)
}
if bg := b.(*widget.BarGauge); bg.Max == nil || *bg.Max != 100 {
t.Errorf("bargauge max: %v", bg.Max)
}
ts, err := BuildWidget(config.WidgetSpec{Type: config.TypeTimeSeries, Stacked: true})
if err != nil {
t.Fatal(err)
}
if !ts.(*widget.TimeSeries).Stacked {
t.Errorf("timeseries stacked not set")
}
}
func TestBuildWidgetUnknown(t *testing.T) {
if _, err := BuildWidget(config.WidgetSpec{Type: "nope"}); err == nil {
t.Error("expected error for unknown type")
}
}
+42
View File
@@ -0,0 +1,42 @@
package app
import "time"
// stepLadder is the set of "clean" query_range steps StepFor rounds up to, so
// axis ticks land on human-friendly intervals rather than arbitrary seconds.
var stepLadder = []time.Duration{
10 * time.Second, 15 * time.Second, 30 * time.Second,
1 * time.Minute, 2 * time.Minute, 5 * time.Minute,
10 * time.Minute, 15 * time.Minute, 30 * time.Minute,
1 * time.Hour, 2 * time.Hour, 3 * time.Hour,
6 * time.Hour, 12 * time.Hour, 24 * time.Hour,
}
// StepFor picks a query_range step for a chart chartWidth cells wide. Braille
// packs two horizontal dots per cell, so the target sample count is chartWidth×2
// — roughly one sample per plotted dot. The raw step (range ÷ dots) is rounded
// UP to the next clean ladder value; rounding up keeps the returned sample count
// at or below the dot budget (never more points than we can draw) and floors the
// step at 10s so we don't hammer Prometheus on short ranges.
func StepFor(rng time.Duration, chartWidth int) time.Duration {
if chartWidth < 1 {
chartWidth = 1
}
raw := rng / time.Duration(chartWidth*2)
return roundStep(raw)
}
// roundStep returns the smallest ladder value >= d. Anything at or below the
// floor (10s) snaps to the floor; anything above the ladder rounds up to whole
// hours.
func roundStep(d time.Duration) time.Duration {
for _, s := range stepLadder {
if d <= s {
return s
}
}
if d%time.Hour == 0 {
return d
}
return d.Truncate(time.Hour) + time.Hour
}
+87
View File
@@ -0,0 +1,87 @@
package app
import (
"testing"
"time"
)
func TestStepFor(t *testing.T) {
tests := []struct {
name string
rng time.Duration
width int
want time.Duration
}{
{
// 15m over 80 cells = 160 dots → 5.6s raw → floored to 10s.
name: "short range floors at 10s", rng: 15 * time.Minute, width: 80,
want: 10 * time.Second,
},
{
// 6h over 80 cells = 160 dots → 135s raw → next rung 5m.
name: "mid range rounds up to clean rung", rng: 6 * time.Hour, width: 80,
want: 5 * time.Minute,
},
{
// 24h over 100 cells = 200 dots → 432s raw → next rung 10m.
name: "day range", rng: 24 * time.Hour, width: 100,
want: 10 * time.Minute,
},
{
// 1h over 30 cells = 60 dots → 60s raw → exact rung 1m (<= match).
name: "raw lands exactly on a rung", rng: time.Hour, width: 30,
want: 1 * time.Minute,
},
{
// Very narrow chart still floors at 10s, never zero.
name: "narrow chart floors at 10s", rng: time.Minute, width: 4,
want: 10 * time.Second,
},
{
// Above the ladder: 60h over 1 cell = 2 dots → 30h raw, already a
// whole hour, so returned as-is (no spurious +1h).
name: "beyond ladder keeps clean whole hour", rng: 60 * time.Hour, width: 1,
want: 30 * time.Hour,
},
{
// Above the ladder, fractional: 51h over 1 cell = 2 dots → 25.5h raw
// → rounds up to 26h.
name: "beyond ladder rounds fractional up", rng: 51 * time.Hour, width: 1,
want: 26 * time.Hour,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := StepFor(tt.rng, tt.width); got != tt.want {
t.Errorf("StepFor(%s, %d) = %s, want %s", tt.rng, tt.width, got, tt.want)
}
})
}
}
// StepFor must never return a step so small it exceeds the dot budget, nor a
// non-positive step, across a sweep of realistic ranges and widths.
func TestStepForInvariants(t *testing.T) {
ranges := []time.Duration{
time.Minute, 5 * time.Minute, 15 * time.Minute, time.Hour,
6 * time.Hour, 24 * time.Hour, 7 * 24 * time.Hour,
}
widths := []int{0, 1, 4, 24, 80, 200, 400}
for _, rng := range ranges {
for _, w := range widths {
step := StepFor(rng, w)
if step < 10*time.Second {
t.Errorf("StepFor(%s, %d) = %s below 10s floor", rng, w, step)
}
effW := w
if effW < 1 {
effW = 1
}
dots := effW * 2
if samples := int(rng / step); samples > dots {
t.Errorf("StepFor(%s, %d) = %s yields %d samples > %d dot budget",
rng, w, step, samples, dots)
}
}
}
}
+157
View File
@@ -0,0 +1,157 @@
// Package config defines grot's canonical dashboard model and a YAML loader.
// Both native YAML configs and (later) Grafana JSON import produce a Dashboard.
package config
import (
"bytes"
"fmt"
"os"
"strings"
"time"
"gopkg.in/yaml.v3"
)
// WidgetType enumerates the renderable widget kinds.
type WidgetType string
const (
TypeStat WidgetType = "stat"
TypeGauge WidgetType = "gauge"
TypeBarGauge WidgetType = "bargauge"
TypeTimeSeries WidgetType = "timeseries"
)
// Dashboard is grot's canonical dashboard model.
type Dashboard struct {
Title string `yaml:"title"`
Theme string `yaml:"theme"`
Refresh Duration `yaml:"refresh"`
Range Duration `yaml:"range"`
Widgets []WidgetSpec `yaml:"widgets"`
}
// WidgetSpec describes one panel: its type, placement, queries, and formatting.
type WidgetSpec struct {
Type WidgetType `yaml:"type"`
Title string `yaml:"title"`
Grid GridPos `yaml:"grid"`
Queries []Query `yaml:"queries"`
Unit string `yaml:"unit"`
Decimals *int `yaml:"decimals"`
Min *float64 `yaml:"min"`
Max *float64 `yaml:"max"`
Thresholds []Threshold `yaml:"thresholds"`
Stacked bool `yaml:"stacked"`
Reduce string `yaml:"reduce"`
}
// Query is a single PromQL expression with an optional {{label}} legend.
// Instant selects an instant query; otherwise a range query is used.
type Query struct {
Expr string `yaml:"expr"`
Legend string `yaml:"legend"`
Instant bool `yaml:"instant"`
}
// GridPos is a Grafana-compatible 24-column placement.
type GridPos struct {
X int `yaml:"x"`
Y int `yaml:"y"`
W int `yaml:"w"`
H int `yaml:"h"`
}
// Threshold colors a value at or above Value. A nil Value is the base color.
type Threshold struct {
Value *float64 `yaml:"value"`
Color string `yaml:"color"`
}
// Duration is a time.Duration that unmarshals from a YAML string like "30s".
type Duration time.Duration
// UnmarshalYAML parses a Go duration string ("30s", "5m", "1h").
func (d *Duration) UnmarshalYAML(node *yaml.Node) error {
var s string
if err := node.Decode(&s); err != nil {
return fmt.Errorf("duration: %w", err)
}
if s == "" {
return nil
}
v, err := time.ParseDuration(s)
if err != nil {
return fmt.Errorf("invalid duration %q: %w", s, err)
}
*d = Duration(v)
return nil
}
// Duration returns the underlying time.Duration.
func (d Duration) Duration() time.Duration { return time.Duration(d) }
// Load reads and validates a dashboard config from a YAML file.
func Load(path string) (*Dashboard, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read config %q: %w", path, err)
}
return Parse(b)
}
// Parse decodes and validates a dashboard config from YAML bytes. Unknown
// fields are rejected so typos surface immediately.
func Parse(b []byte) (*Dashboard, error) {
var d Dashboard
dec := yaml.NewDecoder(bytes.NewReader(b))
dec.KnownFields(true)
if err := dec.Decode(&d); err != nil {
return nil, fmt.Errorf("parse config: %w", err)
}
if err := d.validate(); err != nil {
return nil, err
}
d.applyDefaults()
return &d, nil
}
func (d *Dashboard) validate() error {
if len(d.Widgets) == 0 {
return fmt.Errorf("config has no widgets")
}
for i, w := range d.Widgets {
label := w.Title
if label == "" {
label = fmt.Sprintf("#%d", i)
}
switch w.Type {
case TypeStat, TypeGauge, TypeBarGauge, TypeTimeSeries:
case "":
return fmt.Errorf("widget %s: missing type", label)
default:
return fmt.Errorf("widget %s: unknown type %q", label, w.Type)
}
if len(w.Queries) == 0 {
return fmt.Errorf("widget %s: no queries", label)
}
for j, q := range w.Queries {
if strings.TrimSpace(q.Expr) == "" {
return fmt.Errorf("widget %s: query %d has empty expr", label, j)
}
}
}
return nil
}
func (d *Dashboard) applyDefaults() {
if d.Theme == "" {
d.Theme = "pilot"
}
if d.Refresh == 0 {
d.Refresh = Duration(30 * time.Second)
}
if d.Range == 0 {
d.Range = Duration(15 * time.Minute)
}
}
+104
View File
@@ -0,0 +1,104 @@
package config
import (
"testing"
"time"
)
func TestParseValid(t *testing.T) {
src := `
title: pilot
theme: tokyo-night
refresh: 15s
range: 1h
widgets:
- type: stat
title: cost
unit: currencyUSD
decimals: 2
queries:
- expr: sum(pilot_execution_cost_usd_total)
- type: gauge
title: success rate
unit: percentunit
min: 0
max: 1
thresholds:
- color: red
- value: 0.8
color: yellow
queries:
- expr: pilot_success_rate
legend: "{{job}}"
`
d, err := Parse([]byte(src))
if err != nil {
t.Fatalf("Parse: %v", err)
}
if d.Title != "pilot" || d.Theme != "tokyo-night" {
t.Fatalf("meta: got %q/%q", d.Title, d.Theme)
}
if d.Refresh.Duration() != 15*time.Second {
t.Errorf("refresh: got %v", d.Refresh.Duration())
}
if d.Range.Duration() != time.Hour {
t.Errorf("range: got %v", d.Range.Duration())
}
if len(d.Widgets) != 2 {
t.Fatalf("widgets: got %d", len(d.Widgets))
}
cost := d.Widgets[0]
if cost.Type != TypeStat || cost.Decimals == nil || *cost.Decimals != 2 {
t.Errorf("stat: %+v", cost)
}
g := d.Widgets[1]
if g.Type != TypeGauge || g.Min == nil || *g.Min != 0 || g.Max == nil || *g.Max != 1 {
t.Errorf("gauge min/max: %+v", g)
}
if len(g.Thresholds) != 2 || g.Thresholds[0].Value != nil || g.Thresholds[1].Value == nil {
t.Errorf("thresholds: %+v", g.Thresholds)
}
if g.Queries[0].Legend != "{{job}}" {
t.Errorf("legend: %q", g.Queries[0].Legend)
}
}
func TestParseDefaults(t *testing.T) {
d, err := Parse([]byte(`
widgets:
- type: stat
title: x
queries:
- expr: up
`))
if err != nil {
t.Fatalf("Parse: %v", err)
}
if d.Theme != "pilot" {
t.Errorf("default theme: %q", d.Theme)
}
if d.Refresh.Duration() != 30*time.Second {
t.Errorf("default refresh: %v", d.Refresh.Duration())
}
if d.Range.Duration() != 15*time.Minute {
t.Errorf("default range: %v", d.Range.Duration())
}
}
func TestParseErrors(t *testing.T) {
cases := map[string]string{
"no widgets": `title: x`,
"unknown type": "widgets:\n - type: piechart\n queries:\n - expr: up",
"no queries": "widgets:\n - type: stat\n title: x",
"empty expr": "widgets:\n - type: stat\n queries:\n - expr: \" \"",
"unknown field": "widgets:\n - type: stat\n queries:\n - expr: up\n color: red",
"bad duration": "refresh: 5parsecs\nwidgets:\n - type: stat\n queries:\n - expr: up",
}
for name, src := range cases {
if _, err := Parse([]byte(src)); err == nil {
t.Errorf("%s: expected error, got nil", name)
}
}
}
+38
View File
@@ -0,0 +1,38 @@
// Package datasource defines the boundary grot's widgets query against. The
// interface lives here (the consumer side); concrete backends such as
// datasource/prom implement it.
package datasource
import (
"context"
"time"
"github.com/qf-studio/grot/pkg/tui/widget"
)
// Instant requests a single-value (vector) query evaluated at At. A zero At
// means "server now".
type Instant struct {
Expr string
Legend string // Grafana-style {{label}} template; empty → derived from labels
At time.Time
}
// Range requests a query_range over [Start, End] at the given Step.
type Range struct {
Expr string
Legend string
Start time.Time
End time.Time
Step time.Duration
}
// Datasource fetches series for widgets. Each returned Series carries an
// expanded legend and the points for one result element.
type Datasource interface {
// QueryInstant evaluates an instant vector query, returning one Series
// (with a single Point) per result element.
QueryInstant(ctx context.Context, q Instant) ([]widget.Series, error)
// QueryRange evaluates a range query, returning one Series per element.
QueryRange(ctx context.Context, q Range) ([]widget.Series, error)
}
+129
View File
@@ -0,0 +1,129 @@
// Package prom implements a Prometheus-backed datasource.Datasource using the
// official client_golang API package for query decoding.
package prom
import (
"context"
"fmt"
"math"
"strings"
"time"
promapi "github.com/prometheus/client_golang/api"
promv1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
"github.com/qf-studio/grot/internal/datasource"
"github.com/qf-studio/grot/pkg/tui/widget"
)
// Client queries a Prometheus server.
type Client struct {
api promv1.API
}
// New creates a client for the given base URL (e.g. http://localhost:9090).
func New(addr string) (*Client, error) {
c, err := promapi.NewClient(promapi.Config{Address: addr})
if err != nil {
return nil, fmt.Errorf("prometheus client %q: %w", addr, err)
}
return &Client{api: promv1.NewAPI(c)}, nil
}
// Interface compliance.
var _ datasource.Datasource = (*Client)(nil)
// QueryInstant runs an instant vector query.
func (c *Client) QueryInstant(ctx context.Context, q datasource.Instant) ([]widget.Series, error) {
ts := q.At
if ts.IsZero() {
ts = time.Now()
}
val, _, err := c.api.Query(ctx, q.Expr, ts)
if err != nil {
return nil, fmt.Errorf("instant query %q: %w", q.Expr, err)
}
vec, ok := val.(model.Vector)
if !ok {
return nil, fmt.Errorf("instant query %q: expected vector, got %s", q.Expr, val.Type())
}
series := make([]widget.Series, 0, len(vec))
for _, s := range vec {
v := float64(s.Value)
if math.IsNaN(v) {
continue
}
series = append(series, widget.Series{
Legend: expandLegend(q.Legend, s.Metric),
Points: []widget.Point{{T: s.Timestamp.Time(), V: v}},
})
}
return series, nil
}
// QueryRange runs a range query.
func (c *Client) QueryRange(ctx context.Context, q datasource.Range) ([]widget.Series, error) {
r := promv1.Range{Start: q.Start, End: q.End, Step: q.Step}
val, _, err := c.api.QueryRange(ctx, q.Expr, r)
if err != nil {
return nil, fmt.Errorf("range query %q: %w", q.Expr, err)
}
mat, ok := val.(model.Matrix)
if !ok {
return nil, fmt.Errorf("range query %q: expected matrix, got %s", q.Expr, val.Type())
}
series := make([]widget.Series, 0, len(mat))
for _, ss := range mat {
pts := make([]widget.Point, 0, len(ss.Values))
for _, p := range ss.Values {
v := float64(p.Value)
if math.IsNaN(v) {
continue
}
pts = append(pts, widget.Point{T: p.Timestamp.Time(), V: v})
}
series = append(series, widget.Series{
Legend: expandLegend(q.Legend, ss.Metric),
Points: pts,
})
}
return series, nil
}
// expandLegend fills a Grafana-style {{label}} template from a metric's labels.
// An empty template derives a default from the metric's identity.
func expandLegend(tmpl string, metric model.Metric) string {
if strings.TrimSpace(tmpl) == "" {
return defaultLegend(metric)
}
var b strings.Builder
for {
i := strings.Index(tmpl, "{{")
if i < 0 {
b.WriteString(tmpl)
break
}
b.WriteString(tmpl[:i])
rest := tmpl[i+2:]
j := strings.Index(rest, "}}")
if j < 0 {
b.WriteString(tmpl[i:]) // unterminated placeholder — emit literally
break
}
label := strings.TrimSpace(rest[:j])
b.WriteString(string(metric[model.LabelName(label)]))
tmpl = rest[j+2:]
}
return b.String()
}
// defaultLegend returns the metric name when it is the only distinguishing
// label, otherwise the full Prometheus label set (which is unique per series).
func defaultLegend(metric model.Metric) string {
name := string(metric[model.MetricNameLabel])
if len(metric) <= 1 {
return name
}
return metric.String()
}
+106
View File
@@ -0,0 +1,106 @@
package prom
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/prometheus/common/model"
"github.com/qf-studio/grot/internal/datasource"
)
// stubServer returns a Prometheus-shaped API server serving canned responses
// keyed by request path suffix (/query or /query_range).
func stubServer(t *testing.T, instant, rng string) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/query_range"):
_, _ = w.Write([]byte(rng))
case strings.HasSuffix(r.URL.Path, "/query"):
_, _ = w.Write([]byte(instant))
default:
http.NotFound(w, r)
}
}))
}
func TestQueryInstant(t *testing.T) {
const body = `{"status":"success","data":{"resultType":"vector","result":[
{"metric":{"__name__":"pilot_active_prs","repo":"a"},"value":[1700000000,"3"]},
{"metric":{"__name__":"pilot_active_prs","repo":"b"},"value":[1700000000,"5"]},
{"metric":{"__name__":"pilot_active_prs","repo":"c"},"value":[1700000000,"NaN"]}
]}}`
srv := stubServer(t, body, "")
defer srv.Close()
c, err := New(srv.URL)
if err != nil {
t.Fatalf("New: %v", err)
}
series, err := c.QueryInstant(context.Background(), datasource.Instant{
Expr: "pilot_active_prs", Legend: "{{repo}}",
})
if err != nil {
t.Fatalf("QueryInstant: %v", err)
}
// NaN sample dropped → 2 series.
if len(series) != 2 {
t.Fatalf("series: got %d, want 2", len(series))
}
if series[0].Legend != "a" || series[1].Legend != "b" {
t.Errorf("legends: %q, %q", series[0].Legend, series[1].Legend)
}
if v, ok := series[0].Last(); !ok || v != 3 {
t.Errorf("value[0]: %v (%v)", v, ok)
}
}
func TestQueryRange(t *testing.T) {
const body = `{"status":"success","data":{"resultType":"matrix","result":[
{"metric":{"model":"opus"},"values":[[1700000000,"1"],[1700000060,"2"],[1700000120,"NaN"]]}
]}}`
srv := stubServer(t, "", body)
defer srv.Close()
c, err := New(srv.URL)
if err != nil {
t.Fatalf("New: %v", err)
}
series, err := c.QueryRange(context.Background(), datasource.Range{Expr: "x", Legend: "{{model}}"})
if err != nil {
t.Fatalf("QueryRange: %v", err)
}
if len(series) != 1 || series[0].Legend != "opus" {
t.Fatalf("series: %+v", series)
}
if len(series[0].Points) != 2 { // NaN point dropped
t.Errorf("points: got %d, want 2", len(series[0].Points))
}
}
func TestExpandLegend(t *testing.T) {
m := model.Metric{"__name__": "http_requests", "method": "GET", "code": "200"}
cases := []struct{ tmpl, want string }{
{"{{method}} {{code}}", "GET 200"},
{"{{ method }}", "GET"}, // whitespace trimmed
{"{{missing}}", ""}, // absent label → empty
{"static", "static"}, // no placeholders
{"{{method}", "{{method}"}, // unterminated → literal
{"", "http_requests{code=\"200\", method=\"GET\"}"}, // empty → full label set
}
for _, c := range cases {
if got := expandLegend(c.tmpl, m); got != c.want {
t.Errorf("expandLegend(%q) = %q, want %q", c.tmpl, got, c.want)
}
}
// Single-label metric → bare name.
if got := expandLegend("", model.Metric{"__name__": "up"}); got != "up" {
t.Errorf("default single: %q", got)
}
}
+3 -1
View File
@@ -35,7 +35,9 @@ func TestWidgetsExactDimensions(t *testing.T) {
{"no data", func(w Widget) { w.SetResult(QueryResult{}) }},
{"single point", func(w Widget) { w.SetResult(result(42)) }},
{"range", func(w Widget) { w.SetResult(result(1, 5, 3, 8, 2)) }},
{"error", func(w Widget) { w.SetError(errors.New("connection refused: very long error message that should truncate")) }},
{"error", func(w Widget) {
w.SetError(errors.New("connection refused: very long error message that should truncate"))
}},
}
sizes := []struct{ w, h int }{{20, 4}, {30, 6}, {50, 12}, {80, 8}}