Public: anyone can read this; the crew can change it.
GET /metrics serves forge_http_request_duration_seconds to an admin or an admin's token, listed as not-a-page #3881
scout/forge:scout/3749-get-metrics-serves-forge-http-request-du → main 1 commit fork
7 files
changed +205
−3
docs/METRICS.md added +32
| @@ -0,0 +1,32 @@ | ||
| 1 | # Metrics | |
| 2 | ||
| 3 | `GET /metrics` serves the forge's own series as OpenMetrics text | |
| 4 | (`application/openmetrics-text; version=1.0.0`). It names every route | |
| 5 | pattern, so it is for site admins: a signed-in admin's session, or a bearer | |
| 6 | token of any scope whose user is a site admin (an admin's `ro` token is the | |
| 7 | scrape token). No credentials: `401`. A non-admin: `404`. | |
| 8 | ||
| 9 | ## Families | |
| 10 | ||
| 11 | ### `forge_http_request_duration_seconds` | |
| 12 | ||
| 13 | Type: histogram. Label: `pattern`, the route pattern the router matched | |
| 14 | (`/:owner/:repo`, never the raw path). How long the forge took to answer, over | |
| 15 | the last hour (this hour's and the previous hour's rows of `route_timing`). | |
| 16 | Buckets, in seconds: 0.001, 0.002, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, | |
| 17 | 1, 2.5, `+Inf`. | |
| 18 | ||
| 19 | ## Prometheus | |
| 20 | ||
| 21 | yaml | |
| 22 | scrape_configs: | |
| 23 | - job_name: forge | |
| 24 | scheme: https | |
| 25 | metrics_path: /metrics | |
| 26 | authorization: | |
| 27 | credentials_file: /etc/prometheus/forge-token | |
| 28 | static_configs: | |
| 29 | - targets: ["forge.example.org"] | |
| 30 | ||
| 31 | ||
| 32 | The file holds an admin's token and nothing else. |
src/core/route_timing.ts +12
| @@ -249,3 +249,15 @@ export function takeDbTime(request: Request): number | undefined { | ||
| 249 | 249 | dbTimes.delete(request); |
| 250 | 250 | return ms; |
| 251 | 251 | } |
| 252 | ||
| 253 | const timingsByDb = new WeakMap<Database, RouteTiming>(); | |
| 254 | ||
| 255 | /** The one recorder a database has; made on first ask, so a read can flush what a request left pending. */ | |
| 256 | export function timingOf(db: Database): RouteTiming { | |
| 257 | let timing = timingsByDb.get(db); | |
| 258 | if (timing === undefined) { | |
| 259 | timing = createRouteTiming(db); | |
| 260 | timingsByDb.set(db, timing); | |
| 261 | } | |
| 262 | return timing; | |
| 263 | } |
src/http/server.ts +4 −2
| @@ -455,13 +455,14 @@ import { apiRoutes } from "./api.ts"; | ||
| 455 | 455 | import { inNamespace } from "../core/proposal_token.ts"; |
| 456 | 456 | import { proposalTokenMint, proposalTokenRevoke } from "../web/pages/proposal-tokens.ts"; |
| 457 | 457 | import { adminGate } from "./admin_gate.ts"; |
| 458 | import { metricsScrape } from "../metrics/forge.ts"; | |
| 458 | 459 | import { proposalGate } from "./proposal_gate.ts"; |
| 459 | 460 | import { feedRoutes } from "./feed.ts"; |
| 460 | 461 | import type { Database } from "bun:sqlite"; |
| 461 | 462 | import { mcpRoutes } from "./mcp.ts"; |
| 462 | 463 | import { createUsageCounter, type UsageCounter } from "../core/usage_count.ts"; |
| 463 | 464 | import { |
| 464 | createRouteTiming, | |
| 465 | timingOf, | |
| 465 | 466 | noteDbTime, |
| 466 | 467 | noteSessionTime, |
| 467 | 468 | takePhases, |
| @@ -741,6 +742,7 @@ export function buildRouter(): Router<Handler> { | ||
| 741 | 742 | router.add("GET", "/releases", releasesPage); |
| 742 | 743 | router.add("POST", "/releases/:sha/rollback", rollbackSubmit); |
| 743 | 744 | router.add("GET", "/audit.csv", auditCsv); |
| 745 | router.add("GET", "/metrics", metricsScrape); | |
| 744 | 746 | router.add("POST", "/audit/:owner/:name/probe", auditProbeSubmit); |
| 745 | 747 | router.add("POST", "/new", newRepoSubmit); |
| 746 | 748 | router.add("GET", "/organizations/new", newOrgPage); |
| @@ -2154,7 +2156,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 2154 | 2156 | try { |
| 2155 | 2157 | let timing = timings.get(owner.db); |
| 2156 | 2158 | if (timing === undefined) { |
| 2157 | timing = createRouteTiming(owner.db); | |
| 2159 | timing = timingOf(owner.db); | |
| 2158 | 2160 | timings.set(owner.db, timing); |
| 2159 | 2161 | } |
| 2160 | 2162 | timing.record(tag.pattern, ms); |
src/metrics/forge.ts added +63
| @@ -0,0 +1,63 @@ | ||
| 1 | /** | |
| 2 | * The forge's own series as OpenMetrics: `GET /metrics`. Reads `route_timing` | |
| 3 | * over the last hour into families; `openmetrics.ts` writes the text. It names | |
| 4 | * every route pattern, so it answers a site admin (session or any-scope | |
| 5 | * token) and no one else: 401 with no credentials, 404 for a non-admin. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { EDGES_MS, readTiming, timingOf } from "../core/route_timing.ts"; | |
| 10 | import type { Ctx } from "../http/context.ts"; | |
| 11 | import { openMetrics, type Family, type HistogramSample } from "./openmetrics.ts"; | |
| 12 | ||
| 13 | const HOUR_MS = 3_600_000; | |
| 14 | const CONTENT_TYPE = "application/openmetrics-text; version=1.0.0; charset=utf-8"; | |
| 15 | ||
| 16 | /** Per route pattern, the durations recorded since the hour before `now`, in seconds. */ | |
| 17 | export function forgeFamilies(db: Database, now: number = Date.now()): Family[] { | |
| 18 | const since = new Date(Math.floor((now - HOUR_MS) / HOUR_MS) * HOUR_MS).toISOString().slice(0, 13); | |
| 19 | const byPattern = new Map<string, { counts: number[]; sumUs: number }>(); | |
| 20 | for (const row of readTiming(db, since)) { | |
| 21 | let acc = byPattern.get(row.pattern); | |
| 22 | if (acc === undefined) { | |
| 23 | acc = { counts: new Array(EDGES_MS.length + 1).fill(0), sumUs: 0 }; | |
| 24 | byPattern.set(row.pattern, acc); | |
| 25 | } | |
| 26 | acc.counts[row.bucket] = (acc.counts[row.bucket] ?? 0) + row.n; | |
| 27 | acc.sumUs += row.sum_us; | |
| 28 | } | |
| 29 | const samples: HistogramSample[] = []; | |
| 30 | for (const [pattern, { counts, sumUs }] of [...byPattern].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) { | |
| 31 | let running = 0; | |
| 32 | const buckets = EDGES_MS.map((edge, i) => { | |
| 33 | running += counts[i]!; | |
| 34 | return { le: edge / 1000, count: running }; | |
| 35 | }); | |
| 36 | samples.push({ labels: { pattern }, buckets, count: running + counts[EDGES_MS.length]!, sum: sumUs / 1e6 }); | |
| 37 | } | |
| 38 | return [ | |
| 39 | { | |
| 40 | type: "histogram", | |
| 41 | name: "forge_http_request_duration_seconds", | |
| 42 | help: "How long the forge took to answer, by route pattern, over the last hour.", | |
| 43 | samples, | |
| 44 | }, | |
| 45 | ]; | |
| 46 | } | |
| 47 | ||
| 48 | export function metricsScrape(ctx: Ctx): Response { | |
| 49 | const headers = { "cache-control": "no-store" }; | |
| 50 | const user = ctx.auth.user; | |
| 51 | if (user === undefined) | |
| 52 | return new Response("credentials needed\n", { | |
| 53 | status: 401, | |
| 54 | headers: { ...headers, "content-type": "text/plain; charset=utf-8", "www-authenticate": 'Bearer realm="forge"' }, | |
| 55 | }); | |
| 56 | if (!user.isAdmin) | |
| 57 | return new Response("not found\n", { status: 404, headers: { ...headers, "content-type": "text/plain; charset=utf-8" } }); | |
| 58 | timingOf(ctx.app.db).flush(); | |
| 59 | return new Response(openMetrics(forgeFamilies(ctx.app.db)), { | |
| 60 | status: 200, | |
| 61 | headers: { ...headers, "content-type": CONTENT_TYPE }, | |
| 62 | }); | |
| 63 | } |
test/design-audit.test.ts +1 −1
| @@ -11,7 +11,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8"); | ||
| 11 | 11 | |
| 12 | 12 | /** Routes that answer a file, a fragment, a redirect hop or a callback. */ |
| 13 | 13 | 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$|audit\.csv$|metrics$|fleet\/graph\/live$|fleet\/graph\.csv$|settings\/origins\/callback$|home\/archived\/|settings\/backups\/live$)/; | |
| 15 | 15 | |
| 16 | 16 | const getRoutes = [ |
| 17 | 17 | ...server.matchAll(/router\.add\(\s*"GET",\s*"([^"]+)"/g), |
test/forge-looks.test.ts +1
| @@ -27,6 +27,7 @@ const NOT_A_PAGE: Record<string, string> = { | ||
| 27 | 27 | "/manifest.webmanifest": "the install manifest, JSON", |
| 28 | 28 | "/opensearch.xml": "the browser search description, XML", |
| 29 | 29 | "/sw.js": "the service worker script", |
| 30 | "/metrics": "OpenMetrics text for a scraper, not a page", | |
| 30 | 31 | "/audit.csv": "a CSV download of /audit", |
| 31 | 32 | "/claim": "answers 404 to an admin: it exists only for a link-holder", |
| 32 | 33 | "/first-admin": "the setup form for a forge with no admin yet", |
test/metrics-route.test.ts added +92
| @@ -0,0 +1,92 @@ | ||
| 1 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 2 | import { readFileSync } from "node:fs"; | |
| 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 { timingOf } from "../src/core/route_timing.ts"; | |
| 8 | import { createToken } from "../src/core/tokens.ts"; | |
| 9 | import { createUser } from "../src/core/users.ts"; | |
| 10 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 11 | import { quietLogs } from "./helpers/globals.ts"; | |
| 12 | ||
| 13 | quietLogs(); | |
| 14 | ||
| 15 | let dir: string; | |
| 16 | let app: App; | |
| 17 | let servers: Servers; | |
| 18 | let adminRo: string; | |
| 19 | let memberRo: string; | |
| 20 | ||
| 21 | async function user(name: string, adminIfFirst: boolean) { | |
| 22 | const r = await createUser(app.db, { | |
| 23 | origin: "seed", | |
| 24 | trusted: true, | |
| 25 | username: name, | |
| 26 | email: `${name}@forge.local`, | |
| 27 | password: "a-good-passphrase", | |
| 28 | adminIfFirst, | |
| 29 | }); | |
| 30 | if (!r.ok) throw new Error(r.error); | |
| 31 | return r.value; | |
| 32 | } | |
| 33 | ||
| 34 | beforeAll(async () => { | |
| 35 | dir = await mkdtemp(join(tmpdir(), "forge-metrics-")); | |
| 36 | app = createApp({ dataDir: dir, port: 0 }); | |
| 37 | servers = await serve(app); | |
| 38 | adminRo = createToken(app.db, (await user("alice", true)).id, "scrape", "ro").token; | |
| 39 | memberRo = createToken(app.db, (await user("bob", false)).id, "t", "ro").token; | |
| 40 | }); | |
| 41 | ||
| 42 | afterAll(async () => { | |
| 43 | servers.stop(); | |
| 44 | app.close(); | |
| 45 | await rm(dir, { recursive: true, force: true }); | |
| 46 | }); | |
| 47 | ||
| 48 | const scrape = (token?: string) => | |
| 49 | fetch(`${servers.url}/metrics`, { headers: token ? { authorization: `Bearer ${token}` } : {} }); | |
| 50 | ||
| 51 | const count = (body: string, pattern: string): number => { | |
| 52 | const m = body.match(new RegExp(`forge_http_request_duration_seconds_count\\{pattern="${pattern}"\\} (\\d+)`)); | |
| 53 | return m ? Number(m[1]) : 0; | |
| 54 | }; | |
| 55 | ||
| 56 | test("no credentials is 401", async () => { | |
| 57 | expect((await scrape()).status).toBe(401); | |
| 58 | }); | |
| 59 | ||
| 60 | test("a non-admin's token is 404", async () => { | |
| 61 | expect((await scrape(memberRo)).status).toBe(404); | |
| 62 | }); | |
| 63 | ||
| 64 | test("an admin's ro token gets OpenMetrics, no-store, with the security headers", async () => { | |
| 65 | const res = await scrape(adminRo); | |
| 66 | expect(res.status).toBe(200); | |
| 67 | expect(res.headers.get("content-type")).toBe("application/openmetrics-text; version=1.0.0; charset=utf-8"); | |
| 68 | expect(res.headers.get("cache-control")).toBe("no-store"); | |
| 69 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 70 | expect(res.headers.get("referrer-policy")).toBeTruthy(); | |
| 71 | const body = await res.text(); | |
| 72 | expect(body.startsWith("# TYPE forge_http_request_duration_seconds histogram")).toBe(true); | |
| 73 | expect(body.endsWith("# EOF\n")).toBe(true); | |
| 74 | }); | |
| 75 | ||
| 76 | test("a recorded request moves its bucket", async () => { | |
| 77 | const before = await (await scrape(adminRo)).text(); | |
| 78 | timingOf(app.db).record("/probe/:x", 3); | |
| 79 | const after = await (await scrape(adminRo)).text(); | |
| 80 | expect(count(after, "/probe/:x")).toBe(count(before, "/probe/:x") + 1); | |
| 81 | expect(after).toContain('forge_http_request_duration_seconds_bucket{pattern="/probe/:x",le="0.002"} 0'); | |
| 82 | expect(after).toContain('forge_http_request_duration_seconds_bucket{pattern="/probe/:x",le="0.005"} 1'); | |
| 83 | }); | |
| 84 | ||
| 85 | test("every family served is listed in docs/METRICS.md", async () => { | |
| 86 | const doc = readFileSync(join(import.meta.dir, "..", "docs", "METRICS.md"), "utf8"); | |
| 87 | const body = await (await scrape(adminRo)).text(); | |
| 88 | for (const m of body.matchAll(/^# TYPE (\S+) (\S+)$/gm)) { | |
| 89 | expect(doc).toContain(`### \`${m[1]}\``); | |
| 90 | expect(doc).toContain(`Type: ${m[2]}`); | |
| 91 | } | |
| 92 | }); |
new above
offline