Public: anyone can read this; the crew can change it.
/explore evaluates rate, sum by and topk over the metric series and draws the result as a chart above a table #17063
Merged 44h 18m ago, live in production
scout/forge:scout/17049-explore-evaluates-rate-sum-by-and-topk-o → main 0 commits fork
8 files
changed +432
−9
docs/design/attention-budget.json +5 −5
| @@ -189,15 +189,15 @@ | ||
| 189 | 189 | "note": "Measured on the test forge's empty state with the machine reading replaced by an empty one and the two cell-cap sentences fixed (the live page's counts depend on the host's cores, disks, processes and cgroups); nothing seeded or waited for. Blocks 65 -> 67 (#11805): the off-site backup section's heading and one-sentence state stay on first view so a red lane is seen without a click; its rows sit behind the disclosure. Blocks 67 -> 69 (#12010): the database size section's heading and its one-sentence state (the file's size and growth, a badge when either is worth a look) stay on first view, as the off-site lane's do; its fact rows and the table of the ten largest tables and indexes sit behind the disclosure. Words +22, blocks +1 (#12092): the footprint section's heading and its one-sentence state (on an empty forge, not read yet and the memory budget) stay on first view; the measured facts and the optional parts sit behind the disclosure. Words +6, blocks +2 (#12420): the stale-pulls section's heading and \"None.\" on a forge with no quiet pull. Words +4, blocks +2 (#13052): the Restore section's heading and its one sentence (\"Restore never proven.\" on an empty forge) stay on first view, so the owner sees whether a restore works without a click. Words +16, blocks +2 (#15073): the least-used-routes section's heading and its one-sentence count stay on first view (how many route groups had no request in 30 days); the table sits behind the disclosure. Words +6, blocks +2 (#15309): the heap census section's heading and its one-sentence state (\"No heap census yet.\" on an empty forge) stay on first view; the button, what a census costs and the table of types that grew sit behind the disclosure." |
| 190 | 190 | }, |
| 191 | 191 | "explore": { |
| 192 | "note": "Measured as an admin: the unfiltered count reads 'N apps, forges and people' (+3 words over 'N results'); a guest reads two fewer. An app row says forks by people (+1 word, #14323). A person row says its ships and forks in 30 days, the figures its place is made of: words +3 (#15754).", | |
| 192 | "note": "Measured as an admin: the unfiltered count reads 'N apps, forges and people' (+3 words over 'N results'); a guest reads two fewer. An app row says forks by people (+1 word, #14323). A person row says its ships and forks in 30 days, the figures its place is made of: words +3 (#15754). The admin-only metric box adds its Run button: +1 word, +1 block (#17049).", | |
| 193 | 193 | "390": { |
| 194 | "words": 46, | |
| 195 | "blocks": 9, | |
| 194 | "words": 47, | |
| 195 | "blocks": 10, | |
| 196 | 196 | "colours": 0 |
| 197 | 197 | }, |
| 198 | 198 | "1280": { |
| 199 | "words": 46, | |
| 200 | "blocks": 9, | |
| 199 | "words": 47, | |
| 200 | "blocks": 10, | |
| 201 | 201 | "colours": 0 |
| 202 | 202 | } |
| 203 | 203 | }, |
docs/features/explore.md +13
| @@ -138,3 +138,16 @@ Each app row leads with a small picture of its newest public look, so you see wh | ||
| 138 | 138 | ## A JSON form for an agent (#15744) |
| 139 | 139 | |
| 140 | 140 | `GET /explore.json` answers the page's rows for the page's one filter line (`readExploreLine`; the same words in `q`, or the separate parameters `kind`, `sort`, `updated`, `owner` and the rest). The answer is `{ query, filters, items, next_cursor }`: `filters` names what the line set (`sort` always; `kind`, `text`, `updated`, `owner`, `forks`, `ships`, `live`, `mine`, `template`, `archived` when set), and each app row carries `score_parts` (`forks`, `ships`, `likes`, `fresh`, `use`, `quiet` (0, or the drop a long-quiet app takes), each as the ranking weighs it, and `total`, their sum, within a rounding of the row's `score`). A word the explorer does not take is a 422 naming it (`unknown_filter` for a word in `q`, `invalid` with `field` for a parameter); rows are the ones this viewer may see, so a private app never appears for a stranger. `GET /api/v1/explore` is the same list without `filters` and `score_parts`. No new MCP tool: the `explore` tool already takes the same line. |
| 141 | ||
| 142 | ## The metric box (#17049) | |
| 143 | ||
| 144 | A site admin who is a person sees a second line on `/explore`: `?m=` takes a small PromQL subset over the forge's metric series (`reach`: `visitors`, `server_p95`, `lcp_p75`…; `spawn_time`: `p50`, `p95`, `budget`): | |
| 145 | ||
| 146 | | line | meaning | | |
| 147 | |---|---| | |
| 148 | | `server_p95` | one line per route | | |
| 149 | | `rate(visitors[2d])` | change per second over a trailing window (`s`, `m`, `h`, `d`, up to 31 days; a window holding one point gives none) | | |
| 150 | | `sum by (route)(server_p95)` | grouped by the source's label (`route`, or `series` for `spawn_time`) | | |
| 151 | | `topk(3, server_p95)` | the 3 lines with the highest latest value (1 to 20) | | |
| 152 | ||
| 153 | `sum by (route)(x)` adds the lines' points at each time into one line. An answer with no points is one plain line, not an empty chart. Anything else is a 422 saying "<token> is not supported. Try rate, sum by or topk." The answer is a chart above a table (`src/boards/chart.ts`), at most 8 lines, 120 table rows. In the terminal, the data explorer (`src/tui/screens/ask_data.ts`) takes `m` and prints the same rows. The grammar and evaluator are `parseMetric` and `evalMetric` in `src/boards/query.ts`; the text is parsed, never evaluated. |
src/actions/explore.ts +47
| @@ -18,6 +18,8 @@ | ||
| 18 | 18 | |
| 19 | 19 | import { cappedQuery, MAX_QUERY_CHARS } from "../core/query_limit.ts"; |
| 20 | 20 | import type { Database } from "bun:sqlite"; |
| 21 | import { evalMetric, MAX_TABLE, parseMetric, type Line, type MetricAnswer } from "../boards/query.ts"; | |
| 22 | import { formatValue, type Cell } from "../boards/chart.ts"; | |
| 21 | 23 | import type { App } from "../app.ts"; |
| 22 | 24 | import { appsForRepos } from "../core/apps.ts"; |
| 23 | 25 | import { markOf, type Mark } from "../core/marks.ts"; |
| @@ -1187,3 +1189,48 @@ function place(ranked: readonly ExploreRow[], forgeRows: ExploreRow[], query: Ex | ||
| 1187 | 1189 | return order([...ranked, ...own], query); |
| 1188 | 1190 | } |
| 1189 | 1191 | |
| 1192 | // ── The metric query box (#17049) ─────────────────────────────────────────── | |
| 1193 | ||
| 1194 | /** What both doors say when an answer has no points. */ | |
| 1195 | export const NO_POINTS = "No points: nothing matches this query."; | |
| 1196 | ||
| 1197 | /** Whether the box is offered: a site admin who is a person. */ | |
| 1198 | export const mayQueryMetric = (user: User | undefined): boolean => user?.isAdmin === true && user.kind !== "agent"; | |
| 1199 | ||
| 1200 | /** | |
| 1201 | * What the box answered: 422 and the first unsupported token, or the lines a chart and a table | |
| 1202 | * draw. | |
| 1203 | */ | |
| 1204 | export type ExploreMetric = | |
| 1205 | | { ok: false; status: 422; error: string } | |
| 1206 | | { ok: true; status: 200; text: string; answer: Extract<MetricAnswer, { ok: true }> }; | |
| 1207 | ||
| 1208 | /** | |
| 1209 | * Run the box's text for `user`. Only a site admin who is a person reads the metric sources (as | |
| 1210 | * the data explorer does); for anyone else nothing is offered and nothing runs (`undefined`). | |
| 1211 | * The text is read by `parseMetric`, never evaluated. | |
| 1212 | */ | |
| 1213 | export function exploreMetric(app: App, user: User | undefined, text: string): ExploreMetric | undefined { | |
| 1214 | if (!mayQueryMetric(user) || text.trim() === "") return undefined; | |
| 1215 | const parsed = parseMetric(text); | |
| 1216 | if (!parsed.ok) return { ok: false, status: 422, error: parsed.error }; | |
| 1217 | const answer = evalMetric(app.db, parsed.metric, { repoIds: "all" }); | |
| 1218 | if (!answer.ok) return { ok: false, status: 422, error: answer.error }; | |
| 1219 | return { ok: true, status: 200, text: text.trim(), answer }; | |
| 1220 | } | |
| 1221 | ||
| 1222 | /** | |
| 1223 | * The cells a chart and a table draw from an answer's lines: the day, the line's label, the value. | |
| 1224 | */ | |
| 1225 | export function metricCells(lines: readonly Line[]): Cell[] { | |
| 1226 | const many = lines.length > 1; | |
| 1227 | return lines.flatMap((l) => l.points.map((p): Cell => ({ label: p.at.slice(0, 10), value: p.value, ...(many ? { series: l.label } : {}) }))); | |
| 1228 | } | |
| 1229 | ||
| 1230 | /** The answer as plain lines for the terminal: one per point, the same cells the table has. */ | |
| 1231 | export function metricLines(r: ExploreMetric): string[] { | |
| 1232 | if (!r.ok) return [`refused: ${r.error}`]; | |
| 1233 | const cells = metricCells(r.answer.lines); | |
| 1234 | if (cells.length === 0) return [r.text, "", NO_POINTS]; | |
| 1235 | return [r.text, "", ...cells.slice(0, MAX_TABLE).map((c) => `${c.label}${c.series === undefined ? "" : ` · ${c.series}`} ${formatValue(c.value)}`)]; | |
| 1236 | } |
src/boards/query.ts +143
| @@ -208,3 +208,146 @@ export function runQuery(db: Database, q: unknown, scope: Scope): Answer { | ||
| 208 | 208 | } |
| 209 | 209 | return { ok: true, rows }; |
| 210 | 210 | } |
| 211 | ||
| 212 | // ── The metric query box on /explore (#17049) ─────────────────────────────── | |
| 213 | // A small PromQL subset over the metric-shaped sources (`reach`, `spawn_time`): | |
| 214 | // x rate(x[5m]) sum by (label)(x) topk(n, x) | |
| 215 | // The text is read by a fixed grammar into a plain `Metric`, never evaluated; the | |
| 216 | // rows come through `runQuery`, so scope, bound parameters and the row limit apply. | |
| 217 | ||
| 218 | /** The metric names each series source holds, and the column that splits one metric into lines. */ | |
| 219 | export const SERIES_SOURCES: Readonly<Record<string, { label: string; names: readonly string[] }>> = { | |
| 220 | reach: { | |
| 221 | label: "route", | |
| 222 | names: ["visitors", "load_p75", "lcp_p75", "inp_p75", "cls_p75", "ttfb_p75", "server_p50", "server_p95", "accounts_active_1d", "accounts_active_7d", "accounts_total"], | |
| 223 | }, | |
| 224 | spawn_time: { label: "series", names: ["p50", "p95", "budget"] }, | |
| 225 | }; | |
| 226 | ||
| 227 | const RATE_UNITS = { s: 1, m: 60, h: 3600, d: 86_400 } as const; | |
| 228 | const MAX_RATE_WINDOW = 31 * 86_400; | |
| 229 | const MAX_TOPK = 20; | |
| 230 | /** The most lines and the most table rows one metric answer carries. */ | |
| 231 | export const MAX_LINES = 8; | |
| 232 | export const MAX_TABLE = 120; | |
| 233 | export const MAX_METRIC_TEXT = 200; | |
| 234 | ||
| 235 | export type Metric = | |
| 236 | | { form: "series"; name: string } | |
| 237 | | { form: "rate"; name: string; seconds: number } | |
| 238 | | { form: "sum"; name: string; by: string } | |
| 239 | | { form: "topk"; name: string; n: number }; | |
| 240 | ||
| 241 | /** | |
| 242 | * One line of a metric answer: a label (a route, or the metric itself) and its points in time | |
| 243 | * order. | |
| 244 | */ | |
| 245 | export type Line = { label: string; points: { at: string; value: number }[] }; | |
| 246 | export type MetricAnswer = { ok: true; metric: Metric; lines: Line[]; cut: boolean } | { ok: false; error: string }; | |
| 247 | ||
| 248 | /** What a refusal offers instead. */ | |
| 249 | const TRY = "Try rate, sum by or topk."; | |
| 250 | const NAME = "[a-z][a-z0-9_]{0,63}"; | |
| 251 | const FORMS: readonly [RegExp, (m: RegExpExecArray) => Metric | string][] = [ | |
| 252 | [new RegExp(`^(${NAME})$`), (m) => ({ form: "series", name: m[1]! })], | |
| 253 | [new RegExp(`^rate\\(\\s*(${NAME})\\[(\\d{1,4})([smhd])\\]\\s*\\)$`), (m) => { | |
| 254 | const seconds = Number(m[2]) * RATE_UNITS[m[3] as keyof typeof RATE_UNITS]; | |
| 255 | return seconds < 1 || seconds > MAX_RATE_WINDOW ? `${m[2]}${m[3]}` : { form: "rate", name: m[1]!, seconds }; | |
| 256 | }], | |
| 257 | [new RegExp(`^sum\\s+by\\s*\\(\\s*([a-z_]{1,32})\\s*\\)\\s*\\(\\s*(${NAME})\\s*\\)$`), (m) => ({ form: "sum", by: m[1]!, name: m[2]! })], | |
| 258 | [new RegExp(`^topk\\(\\s*(\\d{1,3})\\s*,\\s*(${NAME})\\s*\\)$`), (m) => { | |
| 259 | const n = Number(m[1]); | |
| 260 | return n < 1 || n > MAX_TOPK ? m[1]! : { form: "topk", name: m[2]!, n }; | |
| 261 | }], | |
| 262 | ]; | |
| 263 | ||
| 264 | /** The first token of `text` that no form takes: its leading word, or the whole of it. */ | |
| 265 | function firstBad(text: string): string { | |
| 266 | return /^[A-Za-z_][A-Za-z0-9_]*|^\S+/.exec(text)?.[0].slice(0, 40) ?? ""; | |
| 267 | } | |
| 268 | ||
| 269 | /** | |
| 270 | * Read `text` as one metric query, or refuse naming the first unsupported token. Pure; never | |
| 271 | * throws. | |
| 272 | */ | |
| 273 | export function parseMetric(text: unknown): { ok: true; metric: Metric } | { ok: false; error: string } { | |
| 274 | const bad = (token: string) => ({ ok: false as const, error: `${token} is not supported. ${TRY}` }); | |
| 275 | const say = (error: string) => ({ ok: false as const, error }); | |
| 276 | if (typeof text !== "string") return say(`Nothing to run. ${TRY}`); | |
| 277 | const t = text.trim(); | |
| 278 | if (t === "" || t.length > MAX_METRIC_TEXT) return say(t === "" ? `Nothing to run. ${TRY}` : `That query is too long. ${TRY}`); | |
| 279 | let metric: Metric | undefined; | |
| 280 | for (const [re, make] of FORMS) { | |
| 281 | const m = re.exec(t); | |
| 282 | if (m === null) continue; | |
| 283 | const made = make(m); | |
| 284 | if (typeof made === "string") return bad(made); | |
| 285 | metric = made; | |
| 286 | break; | |
| 287 | } | |
| 288 | if (metric === undefined) { | |
| 289 | // A function the grammar lacks is named by its word; a known one written wrong, by what follows | |
| 290 | // it. | |
| 291 | const word = firstBad(t); | |
| 292 | return bad(["rate", "sum", "topk"].includes(word) ? firstBad(t.slice(word.length).trim()) || word : word); | |
| 293 | } | |
| 294 | const home = Object.entries(SERIES_SOURCES).find(([, s]) => s.names.includes(metric!.name)); | |
| 295 | if (home === undefined) return bad(metric.name); | |
| 296 | if (metric.form === "sum" && metric.by !== home[1].label) return bad(metric.by); | |
| 297 | return { ok: true, metric }; | |
| 298 | } | |
| 299 | ||
| 300 | /** The source a metric name lives in. */ | |
| 301 | const sourceOf = (name: string) => Object.entries(SERIES_SOURCES).find(([, s]) => s.names.includes(name))!; | |
| 302 | ||
| 303 | /** | |
| 304 | * Per second, over each point's trailing window: the change from the window's first point to this | |
| 305 | * one. | |
| 306 | */ | |
| 307 | function rateOf(points: Line["points"], seconds: number): Line["points"] { | |
| 308 | const out: Line["points"] = []; | |
| 309 | const ms = points.map((p) => Date.parse(p.at)); | |
| 310 | let from = 0; | |
| 311 | for (let i = 0; i < points.length; i++) { | |
| 312 | while (ms[i]! - ms[from]! > seconds * 1000) from++; | |
| 313 | const dt = (ms[i]! - ms[from]!) / 1000; | |
| 314 | if (dt > 0) out.push({ at: points[i]!.at, value: (points[i]!.value - points[from]!.value) / dt }); | |
| 315 | } | |
| 316 | return out; | |
| 317 | } | |
| 318 | ||
| 319 | /** | |
| 320 | * Evaluate `metric` over the rows `scope` allows: lines of points, at most `MAX_LINES`, `cut` when | |
| 321 | * more existed. | |
| 322 | */ | |
| 323 | export function evalMetric(db: Database, metric: Metric, scope: Scope): MetricAnswer { | |
| 324 | const [source, { label }] = sourceOf(metric.name); | |
| 325 | const got = runQuery( | |
| 326 | db, | |
| 327 | { source, aggregate: "sum", column: "value", groupBy: "at", series: label, filter: [{ column: "metric", op: "eq", value: metric.name }] }, | |
| 328 | scope, | |
| 329 | ); | |
| 330 | if (!got.ok) return got; | |
| 331 | const by = new Map<string, Line["points"]>(); | |
| 332 | for (const r of got.rows) { | |
| 333 | if (typeof r.group !== "string" || r.value === null) continue; | |
| 334 | // A metric with no label (visitors) is one line named for itself. | |
| 335 | const name = r.series === undefined || r.series === null || r.series === "" ? metric.name : String(r.series); | |
| 336 | (by.get(name) ?? by.set(name, []).get(name)!).push({ at: r.group, value: r.value }); | |
| 337 | } | |
| 338 | // `sum by (label)(x)` adds the points that share a time into one line named for the metric. | |
| 339 | if (metric.form === "sum") { | |
| 340 | const total = new Map<string, number>(); | |
| 341 | for (const points of by.values()) for (const p of points) total.set(p.at, (total.get(p.at) ?? 0) + p.value); | |
| 342 | by.clear(); | |
| 343 | by.set(metric.name, [...total].sort(([a], [b]) => (a < b ? -1 : 1)).map(([at, value]) => ({ at, value }))); | |
| 344 | } | |
| 345 | let lines: Line[] = [...by].map(([name, points]) => ({ label: name, points: metric.form === "rate" ? rateOf(points, metric.seconds) : points })); | |
| 346 | lines = lines.filter((l) => l.points.length > 0); | |
| 347 | // Highest latest value first, the label to break a tie: what topk keeps and what a cut keeps. | |
| 348 | const last = (l: Line) => l.points[l.points.length - 1]!.value; | |
| 349 | lines.sort((a, b) => last(b) - last(a) || (a.label < b.label ? -1 : 1)); | |
| 350 | const cap = metric.form === "topk" ? Math.min(metric.n, MAX_LINES) : MAX_LINES; | |
| 351 | const cut = lines.length > cap && metric.form !== "topk"; | |
| 352 | return { ok: true, metric, lines: lines.slice(0, cap), cut }; | |
| 353 | } |
src/tui/screens/ask_data.ts +19 −1
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | * anyone else the door is not offered, the list is empty and no query runs. |
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | import { exploreMetric, metricLines } from "../../actions/explore.ts"; | |
| 13 | 14 | import { ask, GUIDE, parseSentence, QUESTIONS, sentence } from "../../boards/guide.ts"; |
| 14 | 15 | import { fillFromSentence, MODEL_FILLED, unreadWords } from "../../boards/model_fill.ts"; |
| 15 | 16 | import { runFor } from "../../boards/panel_data.ts"; |
| @@ -83,7 +84,7 @@ export function askDataScreen(session: Session, ctx: Ctx): Screen { | ||
| 83 | 84 | const open = (p: Params, note = ""): void => ctx.push(resultScreen(ctx, session, p, note)); |
| 84 | 85 | const screen: Screen = { |
| 85 | 86 | title: "Data", |
| 86 | keys: [binding(["j", "k"], "move"), binding(["enter"], "open"), binding(["/"], "ask in a sentence")], | |
| 87 | keys: [binding(["j", "k"], "move"), binding(["enter"], "open"), binding(["/"], "ask in a sentence"), binding(["m"], "query a metric")], | |
| 87 | 88 | load: async () => { |
| 88 | 89 | rows = exploreRows(session, Date.now()); |
| 89 | 90 | state.clamp(rows.length); |
| @@ -124,6 +125,23 @@ export function askDataScreen(session: Session, ctx: Ctx): Screen { | ||
| 124 | 125 | ); |
| 125 | 126 | return true; |
| 126 | 127 | } |
| 128 | if (e.key === "m" && mayExplore(session)) { | |
| 129 | // The page's metric box (#17049): rate(x[5m]), sum by (label)(x), topk(n, x), the same | |
| 130 | // answer. | |
| 131 | ctx.push( | |
| 132 | promptScreen(ctx, screen, { | |
| 133 | title: "Query a metric", | |
| 134 | label: "Query", | |
| 135 | placeholder: "topk(3, server_p95)", | |
| 136 | onSubmit: (text) => | |
| 137 | Promise.resolve().then(() => { | |
| 138 | const r = exploreMetric(session.app, session.user, text); | |
| 139 | ctx.push(linesScreen(ctx, "Metric", r === undefined ? [] : metricLines(r).map(plain))); | |
| 140 | }), | |
| 141 | }), | |
| 142 | ); | |
| 143 | return true; | |
| 144 | } | |
| 127 | 145 | return false; |
| 128 | 146 | }, |
| 129 | 147 | }; |
src/web/studio/explore.ts +35 −3
| @@ -17,6 +17,10 @@ import { | ||
| 17 | 17 | EXPLORE_PARAMS, |
| 18 | 18 | badExploreParam, |
| 19 | 19 | exploreParams, |
| 20 | exploreMetric, | |
| 21 | mayQueryMetric, | |
| 22 | NO_POINTS, | |
| 23 | metricCells, | |
| 20 | 24 | exploreNote, |
| 21 | 25 | exploreSuggestion, |
| 22 | 26 | MAKE_IT_YOURS, |
| @@ -32,6 +36,8 @@ import { | ||
| 32 | 36 | type ExploreQuery, |
| 33 | 37 | type ExploreRow, |
| 34 | 38 | } from "../../actions/explore.ts"; |
| 39 | import { drawChart } from "../../boards/chart.ts"; | |
| 40 | import { MAX_METRIC_TEXT, MAX_TABLE } from "../../boards/query.ts"; | |
| 35 | 41 | import { exploreThumbs } from "../../looks/explore_pictures.ts"; |
| 36 | 42 | import { frontWeights, type FrontWeights } from "../../core/front.ts"; |
| 37 | 43 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| @@ -42,7 +48,7 @@ import { html, type Html } from "../html.ts"; | ||
| 42 | 48 | import { compact } from "../compact.ts"; |
| 43 | 49 | import { page, redirect } from "../layout.ts"; |
| 44 | 50 | import { heldCopy, pageTag } from "../page_tag.ts"; |
| 45 | import { btn, card, empty, nameMark, row as rowOf, seg, tabs, time } from "../ui.ts"; | |
| 51 | import { btn, card, chartFrame, empty, nameMark, row as rowOf, seg, tabs, time } from "../ui.ts"; | |
| 46 | 52 | |
| 47 | 53 | const href = (query: ExploreQuery, page = 1): string => { |
| 48 | 54 | const params = new URLSearchParams(exploreParams(query)); |
| @@ -239,6 +245,29 @@ function pager(query: ExploreQuery, page: number, pages: number): Html { | ||
| 239 | 245 | </nav>`; |
| 240 | 246 | } |
| 241 | 247 | |
| 248 | /** | |
| 249 | * The metric box (#17049), for the admins who may read those series: a one-line form, then the | |
| 250 | * answer as a chart above a table, each in a box that holds its height. A refusal is one line | |
| 251 | * naming the first unsupported token. | |
| 252 | */ | |
| 253 | function metricBox(text: string, r: ReturnType<typeof exploreMetric>): Html { | |
| 254 | const form = html`<form method="get" action="/explore" class="bar mb" data-metric-form> | |
| 255 | <input type="text" class="input mono" name="m" value="${text}" maxlength="${MAX_METRIC_TEXT}" placeholder="rate(visitors[2d]) · sum by (route)(server_p95) · topk(3, server_p50)" aria-label="Query a metric" autocomplete="off" spellcheck="false" /> | |
| 256 | ${btn("Run", { size: "sm" })} | |
| 257 | </form>`; | |
| 258 | if (r === undefined || text === "") return form; | |
| 259 | if (!r.ok) return html`${form}<p class="mb small" role="alert" data-metric-refused>${r.error}</p>`; | |
| 260 | const cells = metricCells(r.answer.lines); | |
| 261 | if (cells.length === 0) return html`${form}<p class="mb small muted" data-metric-empty>${NO_POINTS}</p>`; | |
| 262 | const many = r.answer.lines.length > 1; | |
| 263 | const title = r.text; | |
| 264 | return html`${form}<div class="mb" data-metric-result> | |
| 265 | ${chartFrame(many ? "area" : "line", drawChart(many ? "area" : "line", cells, title, "this metric"))} | |
| 266 | ${chartFrame("table", drawChart("table", cells.slice(0, MAX_TABLE), title, "this metric"))} | |
| 267 | ${r.answer.cut ? html`<p class="muted small">Showing the first ${r.answer.lines.length} lines by latest value.</p>` : html``} | |
| 268 | </div>`; | |
| 269 | } | |
| 270 | ||
| 242 | 271 | // GET /explore |
| 243 | 272 | export async function explorePage(ctx: Ctx): Promise<Response> { |
| 244 | 273 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| @@ -303,7 +332,9 @@ export async function explorePage(ctx: Ctx): Promise<Response> { | ||
| 303 | 332 | // The tag is of what the page would say, before any of it is drawn: a reader who holds it gets a |
| 304 | 333 | // 304 and no render (a refused parameter is a 400, never held). Each row's age wording is an |
| 305 | 334 | // input, so the tag moves when "shipped 5m ago" would. |
| 306 | const tag = refused === null ? pageTag(ctx, [line, query, shown, note, suggestion ?? null, oldLink, queryTooLong(ctx.url.searchParams.get("q")), weights, shown.items.map((r) => [whyOf(r, query.sort, now, weights)?.text ?? null, r.shippedAt === null ? null : shippedAgo(r.shippedAt, now)])]) : undefined; | |
| 335 | const metricText = (ctx.url.searchParams.get("m") ?? "").slice(0, MAX_METRIC_TEXT + 1); | |
| 336 | const metric = exploreMetric(ctx.app, ctx.auth.user, metricText); | |
| 337 | const tag = refused === null && metric?.ok !== false ? pageTag(ctx, [line, query, shown, note, suggestion ?? null, oldLink, queryTooLong(ctx.url.searchParams.get("q")), weights, metric ?? null, shown.items.map((r) => [whyOf(r, query.sort, now, weights)?.text ?? null, r.shippedAt === null ? null : shippedAgo(r.shippedAt, now)])]) : undefined; | |
| 307 | 338 | const held = heldCopy(ctx, tag); |
| 308 | 339 | if (held !== undefined) { |
| 309 | 340 | notePhase(ctx.request, "render", 0); |
| @@ -337,6 +368,7 @@ export async function explorePage(ctx: Ctx): Promise<Response> { | ||
| 337 | 368 | const body = html`<div data-explore>${pageHead("Explore", { |
| 338 | 369 | sub: query.kind === "person" ? PEOPLE_ORDER_WORDS : "Public apps and their builders, ranked by use, forks, deployments and recency.", |
| 339 | 370 | })} |
| 371 | ${!mayQueryMetric(ctx.auth.user) ? html`` : metricBox(metricText, metric)} | |
| 340 | 372 | <div class="bar mb" data-filter-line> |
| 341 | 373 | <form method="get" action="/explore" class="bar"> |
| 342 | 374 | <input |
| @@ -421,5 +453,5 @@ export async function explorePage(ctx: Ctx): Promise<Response> { | ||
| 421 | 453 | })}${rows.some((r) => r.kind === "app" && quietSince(r.shippedAt, now) !== "") ? html`<p class="mb small muted" data-quiet-note>${quietNote}</p>` : html``}${pager(query, shown.page, shown.pages)}</div>`; |
| 422 | 454 | const drawn = page({ ctx, title: "Explore", description: query.kind === "person" ? `People on this forge. ${PEOPLE_ORDER_WORDS}` : "Public apps, forges and people on this forge, ranked by use, forks, deployments and recency.", body: compact(body), feed: { href: "/explore.atom", title: "Explore" }, ...(tag === undefined ? {} : { etag: tag }) }); |
| 423 | 455 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 424 | return badKind ? new Response(drawn.body, { status: 400, headers: drawn.headers }) : drawn; | |
| 456 | return badKind || metric?.ok === false ? new Response(drawn.body, { status: badKind ? 400 : 422, headers: drawn.headers }) : drawn; | |
| 425 | 457 | } |
test/explore_query.test.ts added +158
| @@ -0,0 +1,158 @@ | ||
| 1 | /** The metric box on /explore (#17049): the grammar, the evaluator on a fixed series, the page. */ | |
| 2 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 3 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { createApp, type App } from "../src/app.ts"; | |
| 7 | import { exploreMetric, metricLines, NO_POINTS } from "../src/actions/explore.ts"; | |
| 8 | import { evalMetric, parseMetric, type Metric } from "../src/boards/query.ts"; | |
| 9 | import { createUser } from "../src/core/users.ts"; | |
| 10 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 11 | import { adminCookie, seedAdmin } from "./helpers/admin.ts"; | |
| 12 | import { quietLogs } from "./helpers/globals.ts"; | |
| 13 | ||
| 14 | quietLogs(); | |
| 15 | ||
| 16 | const ALL = { repoIds: "all" } as const; | |
| 17 | const metric = (text: string): Metric => { | |
| 18 | const r = parseMetric(text); | |
| 19 | if (!r.ok) throw new Error(r.error); | |
| 20 | return r.metric; | |
| 21 | }; | |
| 22 | ||
| 23 | describe("parseMetric", () => { | |
| 24 | test("takes each form", () => { | |
| 25 | expect(metric("server_p95")).toEqual({ form: "series", name: "server_p95" }); | |
| 26 | expect(metric("rate(visitors[5m])")).toEqual({ form: "rate", name: "visitors", seconds: 300 }); | |
| 27 | expect(metric(" sum by (route)(server_p95) ")).toEqual({ form: "sum", name: "server_p95", by: "route" }); | |
| 28 | expect(metric("topk(3, server_p50)")).toEqual({ form: "topk", name: "server_p50", n: 3 }); | |
| 29 | }); | |
| 30 | ||
| 31 | test("refuses what it does not take, naming the first token", () => { | |
| 32 | const bad = (t: string) => { | |
| 33 | const r = parseMetric(t); | |
| 34 | return r.ok ? "accepted" : r.error; | |
| 35 | }; | |
| 36 | expect(bad("avg(visitors)")).toBe("avg is not supported. Try rate, sum by or topk."); | |
| 37 | expect(bad("nope")).toBe("nope is not supported. Try rate, sum by or topk."); | |
| 38 | expect(bad("sum by (user)(server_p95)")).toBe("user is not supported. Try rate, sum by or topk."); | |
| 39 | expect(bad("topk(99, server_p50)")).toBe("99 is not supported. Try rate, sum by or topk."); | |
| 40 | expect(bad("rate(visitors[0m])")).toBe("0m is not supported. Try rate, sum by or topk."); | |
| 41 | expect(bad("visitors; DROP TABLE user")).toMatch(/is not supported\. Try/); | |
| 42 | expect(bad("")).toBe("Nothing to run. Try rate, sum by or topk."); | |
| 43 | expect(bad("x".repeat(500))).toBe("That query is too long. Try rate, sum by or topk."); | |
| 44 | expect(bad(7 as unknown as string)).toMatch(/^Nothing to run/); | |
| 45 | }); | |
| 46 | }); | |
| 47 | ||
| 48 | describe("evalMetric on a fixed series", () => { | |
| 49 | let dir: string; | |
| 50 | let app: App; | |
| 51 | beforeAll(async () => { | |
| 52 | dir = await mkdtemp(join(tmpdir(), "forge-explore-query-")); | |
| 53 | app = createApp({ dataDir: dir, port: 0 }); | |
| 54 | const ins = app.db.prepare("INSERT INTO page_vital (day, at, route, visitor, ttfb, cls) VALUES (?, 0, ?, 'v', ?, 0)"); | |
| 55 | for (const [day, route, ttfb] of [["2026-10-01", "/x", 10], ["2026-10-02", "/x", 30], ["2026-10-03", "/x", 50], ["2026-10-01", "/y", 5], ["2026-10-01", "/z", 99]] as const) ins.run(day, route, ttfb); | |
| 56 | }); | |
| 57 | afterAll(async () => { | |
| 58 | app.close(); | |
| 59 | await rm(dir, { recursive: true, force: true }); | |
| 60 | }); | |
| 61 | const lines = (t: string) => { | |
| 62 | const r = evalMetric(app.db, metric(t), ALL); | |
| 63 | if (!r.ok) throw new Error(r.error); | |
| 64 | return r.lines.map((l) => [l.label, l.points.map((p) => p.value)]); | |
| 65 | }; | |
| 66 | ||
| 67 | test("a series is one line per route, the highest latest value first", () => { | |
| 68 | expect(lines("server_p95")).toEqual([["/z", [99]], ["/x", [10, 30, 50]], ["/y", [5]]]); | |
| 69 | }); | |
| 70 | test("rate is the change per second over the window; a line with one point has none", () => { | |
| 71 | expect(lines("rate(server_p95[2d])")).toEqual([["/x", [20 / 86_400, 20 / 86_400]]]); | |
| 72 | }); | |
| 73 | test("sum by the label adds the points that share a time into one line named for the metric", () => { | |
| 74 | expect(lines("sum by (route)(server_p95)")).toEqual([["server_p95", [114, 30, 50]]]); | |
| 75 | }); | |
| 76 | test("topk keeps n lines", () => { | |
| 77 | expect(lines("topk(2, server_p95)")).toEqual([["/z", [99]], ["/x", [10, 30, 50]]]); | |
| 78 | }); | |
| 79 | test("only an admin's scope reads the series", () => { | |
| 80 | const r = evalMetric(app.db, metric("server_p95"), { repoIds: ["r1"] }); | |
| 81 | expect(r.ok && r.lines).toEqual([]); | |
| 82 | }); | |
| 83 | test("the terminal says what the table says", async () => { | |
| 84 | const made = await seedAdmin(app, { username: "carol", email: "[email protected]" }); | |
| 85 | if (!made.ok) throw new Error(made.error); | |
| 86 | const admin = made.value; | |
| 87 | const r = exploreMetric(app, admin, "topk(1, server_p95)")!; | |
| 88 | expect(metricLines(r)).toEqual(["topk(1, server_p95)", "", "2026-10-01 99"]); | |
| 89 | expect(metricLines(exploreMetric(app, admin, "rate(visitors[5m])")!)).toEqual(["rate(visitors[5m])", "", NO_POINTS]); | |
| 90 | expect(metricLines(exploreMetric(app, admin, "bogus(x)")!)).toEqual(["refused: bogus is not supported. Try rate, sum by or topk."]); | |
| 91 | expect(exploreMetric(app, undefined, "server_p95")).toBeUndefined(); | |
| 92 | }); | |
| 93 | }); | |
| 94 | ||
| 95 | describe("/explore?m=", () => { | |
| 96 | let dir: string; | |
| 97 | let app: App; | |
| 98 | let servers: Servers; | |
| 99 | let cookie: string; | |
| 100 | beforeAll(async () => { | |
| 101 | dir = await mkdtemp(join(tmpdir(), "forge-explore-query-page-")); | |
| 102 | app = createApp({ dataDir: dir, port: 0 }); | |
| 103 | servers = await serve(app); | |
| 104 | cookie = await adminCookie(app, { username: "alice", email: "[email protected]" }); | |
| 105 | app.db.run("INSERT INTO page_vital (day, at, route, visitor, ttfb, cls) VALUES ('2026-10-01', 0, '/<b>x</b>', 'v', 500, 0), ('2026-10-01', 0, '/y', 'v', 5, 0), ('2026-10-02', 0, '/y', 'v', 15, 0)"); | |
| 106 | for (let i = 0; i < 8; i++) app.db.run(`INSERT INTO page_vital (day, at, route, visitor, ttfb, cls) VALUES ('2026-10-01', 0, '/r${i}', 'v', ${100 + i}, 0)`); | |
| 107 | await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 108 | }); | |
| 109 | afterAll(async () => { | |
| 110 | servers.stop(); | |
| 111 | app.close(); | |
| 112 | await rm(dir, { recursive: true, force: true }); | |
| 113 | }); | |
| 114 | const get = (q: string, c = cookie) => fetch(`${servers.url}/explore?m=${encodeURIComponent(q)}`, { headers: c ? { cookie: c } : {} }); | |
| 115 | ||
| 116 | test("draws a chart above a table, escaped", async () => { | |
| 117 | const res = await get("server_p95"); | |
| 118 | const body = await res.text(); | |
| 119 | expect(res.status).toBe(200); | |
| 120 | expect(body).toContain("data-metric-result"); | |
| 121 | expect(body.indexOf("<svg")).toBeLessThan(body.indexOf("chart-table")); | |
| 122 | expect(body).not.toContain("<b>x</b>"); | |
| 123 | expect(body).toContain("<b>x"); | |
| 124 | }); | |
| 125 | test("an unsupported query is a 422 naming the token, escaped", async () => { | |
| 126 | const res = await get("<script>alert(1)</script>"); | |
| 127 | const body = await res.text(); | |
| 128 | expect(res.status).toBe(422); | |
| 129 | expect(body).toContain("data-metric-refused"); | |
| 130 | expect(body).not.toContain("<script>alert(1)"); | |
| 131 | }); | |
| 132 | test("rate is a 200 with a chart", async () => { | |
| 133 | const res = await get("rate(server_p95[2d])"); | |
| 134 | const body = await res.text(); | |
| 135 | expect(res.status).toBe(200); | |
| 136 | expect(body).toContain("data-metric-result"); | |
| 137 | expect(body).toContain("<svg"); | |
| 138 | }); | |
| 139 | test("an answer with no points says so in one line, with no empty chart", async () => { | |
| 140 | const res = await get("rate(visitors[5m])"); | |
| 141 | const body = await res.text(); | |
| 142 | expect(res.status).toBe(200); | |
| 143 | expect(body).toContain("data-metric-empty"); | |
| 144 | expect(body).toContain(NO_POINTS); | |
| 145 | expect(body).not.toContain("data-metric-result"); | |
| 146 | }); | |
| 147 | test("more than eight lines are cut, and the page says how many it shows", async () => { | |
| 148 | const body = await (await get("server_p95")).text(); | |
| 149 | expect(body).toContain("Showing the first 8 lines by latest value."); | |
| 150 | expect(evalMetric(app.db, metric("server_p95"), ALL)).toMatchObject({ ok: true, cut: true }); | |
| 151 | expect(await (await get("topk(3, server_p95)")).text()).not.toContain("Showing the first"); | |
| 152 | }); | |
| 153 | test("no box and no run for anyone but an admin", async () => { | |
| 154 | const body = await (await get("server_p95", "")).text(); | |
| 155 | expect(body).not.toContain("data-metric-form"); | |
| 156 | expect(body).not.toContain("data-metric-result"); | |
| 157 | }); | |
| 158 | }); |
test/tui-ask-data.test.ts +12
| @@ -100,3 +100,15 @@ test("a sentence the rules cannot read goes to the model, and the result says so | ||
| 100 | 100 | useModel(); |
| 101 | 101 | } |
| 102 | 102 | }); |
| 103 | ||
| 104 | test("m asks for a metric and shows what the page's table shows; nobody else has the key", async () => { | |
| 105 | const text = await typed(carol, ["m", ..."rate(visitors[5m])", "\r"]); | |
| 106 | expect(text).toContain("No points: nothing matches this query."); | |
| 107 | const bad = await typed(carol, ["m", ..."avg(x)", "\r"]); | |
| 108 | expect(bad).toContain("avg is not supported. Try rate, sum by or topk."); | |
| 109 | for (const who of [bob, undefined]) { | |
| 110 | const none = await typed(who, ["m", ..."visitors", "\r"]); | |
| 111 | expect(none).not.toContain("Query a metric"); | |
| 112 | expect(none).not.toContain("No points"); | |
| 113 | } | |
| 114 | }); |
new above
offline