Public: anyone can read this; the crew can change it.

Observability 1: GET /metrics speaks OpenMetrics - the forge's own series, ready for real Grafana #3741

Parked opened this in answer to
Closed without merging

scout/forge:scout/3690-observability-1-get-metrics-speaks-openm → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +384 −1
docs/METRICS.md added +39
@@ -0,0 +1,39 @@
1 # Metrics
2
3 `GET /metrics` answers [OpenMetrics](https://openmetrics.io) text
4 (`application/openmetrics-text; version=1.0.0`), Prometheus-compatible. It is
5 read with `Authorization: Bearer <token>` where the token belongs to an admin;
6 make one at `/settings/tokens` for each scraper so it can be revoked alone.
7 A session, a member's token or no credential gets the same 404 as any unknown
8 path. Nothing is stored for it: each scrape reads the tables the forge already
9 keeps. No dependency is added; `src/system/openmetrics.ts` writes the format.
10
11 ```yaml
12 scrape_configs:
13 - job_name: forge
14 metrics_path: /metrics
15 scheme: https
16 authorization: { credentials_file: /etc/prometheus/forge-token }
17 static_configs: [{ targets: ["forge.example.com"] }]
18 ```
19
20 Counters are totals over the rows still kept; route timing is pruned after 30
21 days, which a scraper reads as a counter reset. Labels never carry a
22 repository, branch or person; `member` is a crew member, `route` a route pattern.
23
24 | Series | Type | Labels | Meaning |
25 | --- | --- | --- | --- |
26 | `forge_build_info` | info | `version` | the running release |
27 | `forge_pulls_merged_total` | counter | | pulls landed |
28 | `forge_releases_total` | counter | `result` = ok, failed | releases preflighted |
29 | `forge_check_runs_total` | counter | `state` | check runs |
30 | `forge_check_run_seconds_total` | counter | | wall time in finished checks |
31 | `forge_check_queue_depth` | gauge | `state` = queued, running | checks waiting or running |
32 | `forge_crew_runs_total` | counter | `member`, `state` | crew runs |
33 | `forge_crew_spend_usd_total` | counter | `member` | crew spend, US dollars |
34 | `forge_http_request_duration_seconds` | histogram | `route` | time to headers (the Server-Timing `app` figure) |
35 | `forge_cell_cpu_cores` | gauge | `cell`, `kind` | CPU a cell uses |
36 | `forge_cell_memory_bytes` | gauge | `cell`, `kind` | resident memory a cell holds |
37 | `forge_apps` | gauge | | apps hosted |
38
39 Not yet: ask→live seconds, red-main minutes, apps up/asleep (follow-ups).
src/http/metrics.ts added +22
@@ -0,0 +1,22 @@
1 /**
2 * GET /metrics: the forge's own series as OpenMetrics text. An admin's
3 * bearer token reads it — a session, a password or a member's token does
4 * not — so a scraper holds a credential that can be revoked on its own
5 * (`/settings/tokens`). Anyone else gets the same 404 as a path that does
6 * not exist, so the door does not announce itself. Never cached.
7 */
8 import { lacks } from "../core/roles.ts";
9 import { running } from "../kernel/version.ts";
10 import { collect } from "../system/metrics.ts";
11 import { CONTENT_TYPE, render } from "../system/openmetrics.ts";
12 import { live } from "../system/live.ts";
13 import type { Handler } from "./context.ts";
14 import { apiError } from "./respond.ts";
15
16 export const metrics: Handler = (ctx) => {
17 const { user, via } = ctx.auth;
18 if (via !== "token" || user === undefined || user.kind !== "user" || lacks(ctx.app.db, user, "administer"))
19 return apiError("not_found", 404, "no such path");
20 const body = render(collect(ctx.app.db, live().read(), running().version));
21 return new Response(body, { headers: { "content-type": CONTENT_TYPE, "cache-control": "no-store" } });
22 };
src/http/server.ts +2
@@ -73,6 +73,7 @@ import {
7373 import { activeEdgeToken, edgeIdentity } from "./edge.ts";
7474 import { liveResponse, readyResponse } from "./health.ts";
7575 import { running } from "../kernel/version.ts";
76 import { metrics } from "./metrics.ts";
7677 import { runGit } from "../git/env.ts";
7778 import { noteRefusedInternal } from "../kernel/internal_refused.ts";
7879 import { pushCap, storageChanged, storageRefusal, storageRefusedText, storageSentence } from "../core/storage.ts";
@@ -657,6 +658,7 @@ export function buildRouter(): Router<Handler> {
657658 router.add("GET", "/.well-known/change-password", changePassword);
658659 router.add("GET", "/robots.txt", robotsTxt);
659660 router.add("GET", "/releases.json", releasesJson);
661 router.add("GET", "/metrics", metrics);
660662 router.add("GET", "/sitemap.xml", sitemapXml);
661663 router.add("GET", "/manifest.webmanifest", webManifest);
662664 router.add("GET", "/opensearch.xml", openSearch);
src/system/metrics.ts added +153
@@ -0,0 +1,153 @@
1 /**
2 * The forge's own series, read from its own tables on each scrape: what
3 * landed, how the checks and the crew are doing, how long routes take, what
4 * the cells hold. Each is a count or a sum over rows the forge already
5 * keeps (git is truth, the DB an index, so nothing new is stored). Counters
6 * are totals over the rows still kept; route timing is pruned after 30 days,
7 * which a scraper reads as a counter reset. Names, units and labels are
8 * listed in docs/METRICS.md. No repository, branch or person is a label:
9 * crew members are, because they are the crew; routes are patterns.
10 */
11 import type { Database } from "bun:sqlite";
12 import { EDGES_MS } from "../core/route_timing.ts";
13 import type { Family } from "./openmetrics.ts";
14 import type { SystemView } from "./view.ts";
15
16 type Row = Record<string, string | number | null>;
17 const rows = (db: Database, sql: string): Row[] => db.query<Row, []>(sql).all();
18 const num = (v: string | number | null | undefined): number => Number(v ?? 0);
19
20 export function collect(db: Database, view: SystemView, version: string): Family[] {
21 const families: Family[] = [];
22
23 families.push({
24 name: "forge_build",
25 type: "info",
26 help: "The running release.",
27 samples: [{ labels: { version }, value: 1 }],
28 });
29
30 families.push({
31 name: "forge_pulls_merged",
32 type: "counter",
33 help: "Pulls landed on their base branch.",
34 samples: [{ value: num(rows(db, "SELECT COUNT(*) AS n FROM pull WHERE merged_at IS NOT NULL")[0]?.n) }],
35 });
36
37 families.push({
38 name: "forge_releases",
39 type: "counter",
40 help: "Releases checked out and preflighted, by verdict.",
41 samples: ["ok", "failed"].map((result) => ({
42 labels: { result },
43 value: num(
44 rows(db, `SELECT COUNT(*) AS n FROM release WHERE ok ${result === "ok" ? "<> 0" : "= 0"}`)[0]?.n,
45 ),
46 })),
47 });
48
49 const checks = rows(
50 db,
51 `SELECT state, COUNT(*) AS n,
52 COALESCE(SUM((julianday(finished_at) - julianday(started_at)) * 86400.0), 0) AS secs
53 FROM run WHERE kind = 'check' GROUP BY state`,
54 );
55 families.push({
56 name: "forge_check_runs",
57 type: "counter",
58 help: "Check runs, by state.",
59 samples: checks.map((r) => ({ labels: { state: String(r.state) }, value: num(r.n) })),
60 });
61 families.push({
62 name: "forge_check_run_seconds",
63 type: "counter",
64 unit: "seconds",
65 help: "Wall time spent in finished check runs.",
66 samples: [
67 { value: checks.filter((r) => r.state === "ok" || r.state === "failed").reduce((a, r) => a + num(r.secs), 0) },
68 ],
69 });
70 families.push({
71 name: "forge_check_queue_depth",
72 type: "gauge",
73 help: "Check runs waiting or running.",
74 samples: ["queued", "running"].map((state) => ({
75 labels: { state },
76 value: checks.find((r) => r.state === state) ? num(checks.find((r) => r.state === state)!.n) : 0,
77 })),
78 });
79
80 const crew = rows(
81 db,
82 `SELECT COALESCE(u.username, 'unknown') AS member, r.state AS state,
83 COUNT(*) AS n, COALESCE(SUM(r.cost_usd), 0) AS usd
84 FROM run r LEFT JOIN user u ON u.id = r.actor_id
85 WHERE r.kind = 'agent' GROUP BY member, state`,
86 );
87 families.push({
88 name: "forge_crew_runs",
89 type: "counter",
90 help: "Crew runs, by member and state.",
91 samples: crew.map((r) => ({ labels: { member: String(r.member), state: String(r.state) }, value: num(r.n) })),
92 });
93 const spend = new Map<string, number>();
94 for (const r of crew) spend.set(String(r.member), (spend.get(String(r.member)) ?? 0) + num(r.usd));
95 families.push({
96 name: "forge_crew_spend_usd",
97 type: "counter",
98 help: "Money spent by crew runs, in US dollars, by member.",
99 samples: [...spend].map(([member, value]) => ({ labels: { member }, value })),
100 });
101
102 // Route timing: cumulative `le` buckets in seconds, per route pattern.
103 const timing = rows(db, "SELECT pattern, bucket, SUM(n) AS n, SUM(sum_us) AS us FROM route_timing GROUP BY pattern, bucket ORDER BY pattern, bucket");
104 const byRoute = new Map<string, { n: number[]; us: number }>();
105 for (const r of timing) {
106 const t = byRoute.get(String(r.pattern)) ?? { n: new Array<number>(EDGES_MS.length + 1).fill(0), us: 0 };
107 t.n[num(r.bucket)] = num(r.n);
108 t.us += num(r.us);
109 byRoute.set(String(r.pattern), t);
110 }
111 const http: Family["samples"][number][] = [];
112 for (const [route, t] of byRoute) {
113 let running = 0;
114 t.n.forEach((n, i) => {
115 running += n;
116 const le = i < EDGES_MS.length ? String(EDGES_MS[i]! / 1000) : "+Inf";
117 http.push({ suffix: "_bucket", labels: { route, le }, value: running });
118 });
119 http.push({ suffix: "_count", labels: { route }, value: running });
120 http.push({ suffix: "_sum", labels: { route }, value: t.us / 1e6 });
121 }
122 families.push({
123 name: "forge_http_request_duration_seconds",
124 type: "histogram",
125 unit: "seconds",
126 help: "Time to headers of the forge's own responses, by route pattern.",
127 samples: http,
128 });
129
130 const cells = view.groups.filter((g) => g.kind !== "host");
131 families.push({
132 name: "forge_cell_cpu_cores",
133 type: "gauge",
134 help: "CPU a cell is using, in cores.",
135 samples: cells.filter((g) => g.cpuCores !== null).map((g) => ({ labels: { cell: g.label, kind: g.kind }, value: g.cpuCores! })),
136 });
137 families.push({
138 name: "forge_cell_memory_bytes",
139 type: "gauge",
140 unit: "bytes",
141 help: "Resident memory a cell holds.",
142 samples: cells.map((g) => ({ labels: { cell: g.label, kind: g.kind }, value: g.rssBytes })),
143 });
144
145 families.push({
146 name: "forge_apps",
147 type: "gauge",
148 help: "Apps the forge hosts.",
149 samples: [{ value: num(rows(db, "SELECT COUNT(*) AS n FROM app")[0]?.n) }],
150 });
151
152 return families;
153 }
src/system/openmetrics.ts added +58
@@ -0,0 +1,58 @@
1 /**
2 * OpenMetrics text, written by hand: a family is a name, a type, a help line
3 * and its samples; `render` turns families into the exposition format and
4 * ends it with `# EOF`. Plain data in, a string out. Label values are
5 * escaped (backslash, quote, newline); a name or label that is not legal is
6 * a programming error and throws, so a bad series never reaches a scraper.
7 */
8
9 export type Labels = Readonly<Record<string, string>>;
10 export type Sample = { readonly suffix?: string; readonly labels?: Labels; readonly value: number };
11 export type Family = {
12 readonly name: string;
13 readonly type: "counter" | "gauge" | "histogram" | "info";
14 readonly help: string;
15 readonly unit?: string;
16 readonly samples: readonly Sample[];
17 };
18
19 export const CONTENT_TYPE = "application/openmetrics-text; version=1.0.0; charset=utf-8";
20
21 const NAME = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
22 const LABEL = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
23
24 const escapeValue = (v: string): string => v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
25 const escapeHelp = (v: string): string => v.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
26
27 function number(v: number): string {
28 if (Number.isNaN(v)) return "NaN";
29 if (v === Infinity) return "+Inf";
30 if (v === -Infinity) return "-Inf";
31 return String(v);
32 }
33
34 function labelText(labels: Labels | undefined): string {
35 const pairs = Object.entries(labels ?? {});
36 if (pairs.length === 0) return "";
37 return `{${pairs
38 .map(([k, v]) => {
39 if (!LABEL.test(k) || k.startsWith("__")) throw new Error(`illegal label name: ${k}`);
40 return `${k}="${escapeValue(v)}"`;
41 })
42 .join(",")}}`;
43 }
44
45 export function render(families: readonly Family[]): string {
46 const out: string[] = [];
47 for (const f of families) {
48 if (!NAME.test(f.name)) throw new Error(`illegal metric name: ${f.name}`);
49 if (f.unit !== undefined && !f.name.endsWith(`_${f.unit}`)) throw new Error(`${f.name} does not end in its unit`);
50 out.push(`# TYPE ${f.name} ${f.type === "info" ? "info" : f.type}`);
51 if (f.unit !== undefined) out.push(`# UNIT ${f.name} ${f.unit}`);
52 out.push(`# HELP ${f.name} ${escapeHelp(f.help)}`);
53 const own = f.type === "counter" ? "_total" : f.type === "info" ? "_info" : "";
54 for (const s of f.samples) out.push(`${f.name}${s.suffix ?? own}${labelText(s.labels)} ${number(s.value)}`);
55 }
56 out.push("# EOF", "");
57 return out.join("\n");
58 }
test/design-audit.test.ts +1 −1
@@ -11,7 +11,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8");
1111
1212 /** Routes that answer a file, a fragment, a redirect hop or a callback. */
1313 const NOT_PAGES =
14 /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|events$|system\/stream$|settings\/teams\/stream$|sw\.js$|robots\.txt$|sitemap\.xml$|manifest\.webmanifest$|opensearch\.xml$|llms\.txt$|releases\.json$|audit\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|settings\/origins\/callback$|home\/archived\/|settings\/backups\/live$)/;
14 /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|events$|system\/stream$|settings\/teams\/stream$|sw\.js$|robots\.txt$|sitemap\.xml$|manifest\.webmanifest$|opensearch\.xml$|llms\.txt$|releases\.json$|metrics$|audit\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|settings\/origins\/callback$|home\/archived\/|settings\/backups\/live$)/;
1515
1616 const getRoutes = [
1717 ...server.matchAll(/router\.add\(\s*"GET",\s*"([^"]+)"/g),
test/metrics.test.ts added +109
@@ -0,0 +1,109 @@
1 /** GET /metrics speaks OpenMetrics to an admin's bearer token and 404s everyone else (#3690). */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { createToken } from "../src/core/tokens.ts";
9 import { createUser } from "../src/core/users.ts";
10 import { serve } from "../src/http/server.ts";
11 import { render } from "../src/system/openmetrics.ts";
12
13 let dataDir: string;
14 let app: App;
15 let servers: Awaited<ReturnType<typeof serve>>;
16 let admin: string;
17 let bob: string;
18
19 beforeAll(async () => {
20 dataDir = await mkdtemp(join(tmpdir(), "forge-metrics-"));
21 app = createApp({ dataDir, port: 0 });
22 servers = await serve(app);
23 const mk = async (username: string, adminIfFirst: boolean) => {
24 const u = await createUser(app.db, {
25 origin: "seed",
26 trusted: true,
27 username,
28 email: `${username}@forge.local`,
29 password: "a-good-passphrase",
30 adminIfFirst,
31 });
32 if (!u.ok) throw new Error("user");
33 return createToken(app.db, u.value.id, "t", "ro").token;
34 };
35 admin = await mk("alice", true);
36 bob = await mk("bob", false);
37 });
38
39 afterAll(async () => {
40 servers.stop();
41 app.close();
42 await rm(dataDir, { recursive: true, force: true });
43 });
44
45 const scrape = (token?: string) =>
46 fetch(`${servers.url}/metrics`, token ? { headers: { authorization: `Bearer ${token}` } } : {});
47
48 /** A strict reading of the OpenMetrics text grammar this forge writes. */
49 function parse(text: string): Map<string, number> {
50 const lines = text.split("\n");
51 expect(lines.at(-1)).toBe("");
52 expect(lines.at(-2)).toBe("# EOF");
53 const types = new Map<string, string>();
54 const samples = new Map<string, number>();
55 for (const line of lines.slice(0, -2)) {
56 expect(line).not.toBe("");
57 const meta = /^# (TYPE|UNIT|HELP) ([a-zA-Z_:][a-zA-Z0-9_:]*) (.*)$/.exec(line);
58 if (meta) {
59 if (meta[1] === "TYPE") types.set(meta[2]!, meta[3]!);
60 continue;
61 }
62 const m = /^([a-zA-Z_:][a-zA-Z0-9_:]*)(\{(?:[a-zA-Z_][a-zA-Z0-9_]*="(?:[^"\\\n]|\\[\\"n])*",?)*\})? (-?[0-9][0-9.e+-]*|\+Inf|NaN)$/.exec(line);
63 if (!m) throw new Error(`not a sample: ${line}`);
64 const family = [...types.keys()].find((t) => m[1]!.startsWith(t));
65 expect(family).toBeDefined();
66 if (types.get(family!) === "counter") expect(m[1]).toBe(`${family}_total`);
67 samples.set(m[1]! + (m[2] ?? ""), Number(m[3]));
68 }
69 return samples;
70 }
71
72 test("an admin's token reads OpenMetrics that parses, ending in # EOF", async () => {
73 const res = await scrape(admin);
74 expect(res.status).toBe(200);
75 expect(res.headers.get("content-type")).toStartWith("application/openmetrics-text; version=1.0.0");
76 expect(res.headers.get("cache-control")).toBe("no-store");
77 const s = parse(await res.text());
78 expect(s.get("forge_pulls_merged_total")).toBe(0);
79 expect(s.get("forge_apps")).toBe(0);
80 expect(s.get('forge_check_queue_depth{state="queued"}')).toBe(0);
81 });
82
83 test("everyone else meets a 404", async () => {
84 expect((await scrape()).status).toBe(404);
85 expect((await scrape(bob)).status).toBe(404);
86 expect((await scrape("forge_nope")).status).toBe(404);
87 });
88
89 test("a release and a request each move their series", async () => {
90 const before = parse(await (await scrape(admin)).text());
91 app.db
92 .query("INSERT INTO release (sha, repo_id, pull_number, ok, line, created_at) VALUES ('a','r',1,1,'ok',?1)")
93 .run(new Date().toISOString());
94 await fetch(`${servers.url}/robots.txt`);
95 await Bun.sleep(1200); // route timing flushes about a second after a record
96 const after = parse(await (await scrape(admin)).text());
97 expect(after.get('forge_releases_total{result="ok"}')).toBe((before.get('forge_releases_total{result="ok"}') ?? 0) + 1);
98 expect(after.get('forge_http_request_duration_seconds_count{route="/robots.txt"}')).toBe(1);
99 expect(after.get('forge_http_request_duration_seconds_bucket{route="/robots.txt",le="+Inf"}')).toBe(1);
100 });
101
102 test("label values are escaped and illegal names are refused", () => {
103 const text = render([
104 { name: "x", type: "gauge", help: "h\nz", samples: [{ labels: { a: 'q"\\\n' }, value: 1 }] },
105 ]);
106 expect(text).toContain('x{a="q\\"\\\\\\n"} 1');
107 expect(() => render([{ name: "bad name", type: "gauge", help: "", samples: [] }])).toThrow();
108 expect(() => render([{ name: "x", type: "gauge", help: "", samples: [{ labels: { "a-b": "" }, value: 1 }] }])).toThrow();
109 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs