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 #3716

Parked opened this in answer to
Closed without merging

mason/forge:mason/3690-observability-1-get-metrics-speaks-openm → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +1165 −0
CLAUDE.md +4
@@ -150,6 +150,10 @@ src/
150150 response leaves with), api (every /api/v1 route), server
151151 (auth resolution, git smart HTTP, web routes, hook socket), sse
152152 design/ shared design tokens: themes (palettes both surfaces render)
153 metrics/ GET /metrics (docs/METRICS.md): openmetrics (the text writer,
154 both formats, names checked), http (latency by route since
155 boot), series (every family, read from the tables and runtime);
156 the door is http/metrics.ts (an admin, or FORGE_METRICS_TOKEN)
153157 origins/ other forges as one Provider interface: discover (version-endpoint
154158 probe), providers/{github,forgejo} (+ http: paging, ETags, rate
155159 limits), oauth (device grant + PKCE code flow), credential (lazy
README.md +4
@@ -458,6 +458,10 @@ inside it that git does not ignore), `PORT` (`3000`), `FORGE_SSH_PORT` (`2222`;
458458 `FORGE_HOST` (`localhost`, the hostname in clone URLs). `FORGE_DRAIN_LINGER_S`
459459 (`10`, 0 to 120) is how long a forge sent SIGTERM keeps answering while
460460 routers learn it is going, so a roll refuses nobody (`docs/ops/ROLL.md`).
461 `GET /metrics` answers the forge's own series as OpenMetrics for Prometheus
462 and Grafana — pulls landed, ask→live, checks, red main, crew runs and spend,
463 HTTP latency by route, cells, releases, apps — to an admin's bearer or to
464 `FORGE_METRICS_TOKEN`, the scrape token (`docs/METRICS.md` names every series).
461465 Connecting origins
462466 adds `FORGE_URL` (the canonical public base URL, needed for OAuth callbacks),
463467 `FORGE_GITHUB_CLIENT_ID` / `FORGE_GITHUB_CLIENT_SECRET`, and
docs/METRICS.md added +70
@@ -0,0 +1,70 @@
1 # Metrics
2
3 `GET /metrics` answers the forge's own series as text a scraper reads:
4 [OpenMetrics 1.0](https://github.com/prometheus/OpenMetrics/blob/main/specification/OpenMetrics.md)
5 when the request's `Accept` names `application/openmetrics-text` (Prometheus
6 asks for it by default), and the Prometheus text format 0.0.4 otherwise.
7 Point Prometheus, Grafana Agent or Alloy at it and build Grafana boards on top.
8
9 ## Who may read it
10
11 - **A forge admin**: a bearer token of theirs (any scope) or their signed-in
12 session. An agent account is refused even with an admin grant; the crew
13 reads telemetry through `telemetry:read`, which cuts private repositories out.
14 - **The scrape token**: set `FORGE_METRICS_TOKEN` in the forge's environment
15 and send it as the bearer. It opens `/metrics` and nothing else, is compared
16 in constant time, and is never handed to an app or an agent.
17
18 Anyone else gets a 401 (`WWW-Authenticate: Bearer realm="metrics"`) or, signed
19 in without the right, a 403. The answer is never cached.
20
21 ```yaml
22 # prometheus.yml
23 scrape_configs:
24 - job_name: forge
25 scheme: https
26 metrics_path: /metrics
27 authorization:
28 credentials_file: /etc/prometheus/forge-metrics-token
29 static_configs:
30 - targets: ["forge.example.com"]
31 ```
32
33 ## Series
34
35 Counters are totals over what the forge's database holds, so they move when
36 the event is written and do not reset on restart; the HTTP histogram is kept in
37 memory and starts again with the process, as Prometheus expects of a counter.
38 Labels name repositories as `owner/name` and crew members by username.
39
40 | Family | Type | Labels | What it says |
41 | --- | --- | --- | --- |
42 | `forge_build` | info | `version`, `commit` | The forge release answering the scrape (`forge_build_info`). |
43 | `forge_pulls_landed` | counter | `repo` | Pulls merged (`forge_pulls_landed_total`). |
44 | `forge_ask_to_live_median_seconds` | gauge | — | Median time from an issue being asked to its pull serving in production, over what went live in the last 24 hours; absent when nothing did. The same number `/boards` shows. |
45 | `forge_runs` | gauge | `kind` (agent, check, deploy), `state` (queued, running) | Runs waiting or working now: the check queue, the crew at work, deploys in flight. |
46 | `forge_check_queue_oldest_seconds` | gauge | — | How long the oldest queued check has waited; 0 when none waits. |
47 | `forge_check_duration_seconds` | histogram | `outcome` (ok, failed) | How long finished checks ran, start to finish. Buckets from 30 s to an hour. |
48 | `forge_main_red` | gauge | `repo` | 1 while the default branch's last finished check failed (the rule that holds pulls' checks), else 0. |
49 | `forge_main_red_seconds` | counter | `repo` | Time the default branch has spent red: each failed main check counts from when it finished until the next main check finished, or until now (`forge_main_red_seconds_total`). |
50 | `forge_crew_runs` | counter | `member`, `outcome` (ok, failed, cancelled) | Crew runs finished (`forge_crew_runs_total`). |
51 | `forge_crew_spend_usd` | counter | `member` | What crew runs cost, in US dollars (`forge_crew_spend_usd_total`). |
52 | `forge_crew_tokens` | counter | `member`, `direction` (in, out) | Model tokens crew runs used (`forge_crew_tokens_total`). |
53 | `forge_http_request_duration_seconds` | histogram | `route`, `method`, `code` (2xx…5xx) | How long the forge took to answer, the `Server-Timing: total` of each response, by the route pattern that matched (never the raw path; `(unmatched)` for none). Buckets from 1 ms to 2.5 s. |
54 | `forge_cpu_cores` | gauge | `target` | CPU cores in use at the last machine sample (every 15 s): `node`, `forge`, each cell (`check:…`, an app's environment), each core (`cpu:000`…). Absent when the last sample is over two minutes old. |
55 | `forge_memory_bytes` | gauge | `target` | Memory in use at the last machine sample, same targets and freshness. |
56 | `forge_releases` | counter | `outcome` (ok, failed) | Forge releases rolled out (`forge_releases_total`). |
57 | `forge_app_environments` | gauge | `env` (production, preview), `state` (running, asleep, deploying, stopped, failed) | App environments now; absent on a forge that runs no apps. |
58
59 ## Queries to start from
60
61 ```promql
62 # p95 latency by route, last 5 minutes
63 histogram_quantile(0.95, sum by (le, route) (rate(forge_http_request_duration_seconds_bucket[5m])))
64 # pulls landed per day
65 sum(increase(forge_pulls_landed_total[1d]))
66 # minutes main was red today
67 sum by (repo) (increase(forge_main_red_seconds_total[1d])) / 60
68 # crew spend per member, last 24 hours
69 sum by (member) (increase(forge_crew_spend_usd_total[24h]))
70 ```
src/app.ts +5
@@ -60,6 +60,11 @@ export interface ForgeConfig {
6060 * in by the platform. Unset, those headers are a claim and are ignored.
6161 */
6262 edgeToken?: string;
63 /**
64 * The bearer a scraper sends to read `/metrics` (`FORGE_METRICS_TOKEN`):
65 * that page and nothing else. Unset, only an admin reads it.
66 */
67 metricsToken?: string;
6368 /**
6469 * Let anyone, not only an admin, migrate from a host inside the network
6570 * (loopback, private ranges): a forge run for one person on one machine.
src/apps/runtime.ts +8
@@ -468,6 +468,14 @@ export class AppsRuntime {
468468 return this.describe(state);
469469 }
470470
471 /** Every environment of every app, as `status` words its state: what `/metrics` counts. */
472 states(): { env: EnvName; state: EnvState }[] {
473 return [...this.envs.values()].map((s) => {
474 const { env, state } = this.describe(s);
475 return { env, state };
476 });
477 }
478
471479 /** Every environment of an app, production first. */
472480 status(record: AppRecord): EnvStatus[] {
473481 const out: EnvStatus[] = [];
src/core/reserved.ts +1
@@ -100,6 +100,7 @@ export const SYSTEM_NAMES: readonly string[] = [
100100 "sitemap.xml",
101101 "releases",
102102 "releases.json",
103 "metrics",
103104 "sw.js",
104105 "tell",
105106 "theme",
src/http/metrics.ts added +49
@@ -0,0 +1,49 @@
1 /**
2 * GET /metrics: the forge's own series for Prometheus, Grafana Agent or
3 * anything else that scrapes (`docs/METRICS.md`). OpenMetrics when the
4 * scraper's Accept names it, the Prometheus text format otherwise.
5 *
6 * Two ways in: a person who administers the forge (a bearer token of
7 * theirs, or their session), or the scrape token the operator set
8 * (`FORGE_METRICS_TOKEN`), compared in constant time and good for this page
9 * alone. An agent is refused even with an admin's grant; the crew reads its
10 * telemetry through `telemetry:read`, which cuts private repositories out.
11 */
12
13 import { createHash, timingSafeEqual } from "node:crypto";
14 import { forgeFamilies } from "../metrics/series.ts";
15 import { CONTENT_TYPE, formatFor, render } from "../metrics/openmetrics.ts";
16 import type { Ctx } from "./context.ts";
17 import { forbidden, requireScope, unauthorized } from "./respond.ts";
18
19 const digest = (text: string): Buffer => createHash("sha256").update(text).digest();
20
21 /** Whether the request carries the scrape token; false when none is set. */
22 export function scrapeTokenMatches(request: Request, token: string | undefined): boolean {
23 if (token === undefined || token === "") return false;
24 const header = request.headers.get("authorization") ?? "";
25 if (!header.startsWith("Bearer ")) return false;
26 return timingSafeEqual(digest(header.slice("Bearer ".length).trim()), digest(token));
27 }
28
29 function refusal(ctx: Ctx): Response | undefined {
30 if (scrapeTokenMatches(ctx.request, ctx.app.config.metricsToken)) return undefined;
31 const user = ctx.auth.user;
32 if (user === undefined) {
33 const res = unauthorized();
34 res.headers.set("www-authenticate", 'Bearer realm="metrics"');
35 return res;
36 }
37 const denied = requireScope(ctx, "ro");
38 if (denied !== undefined) return denied;
39 return user.isAdmin && user.kind !== "agent" ? undefined : forbidden();
40 }
41
42 export function metricsResponse(ctx: Ctx): Response {
43 const denied = refusal(ctx);
44 if (denied !== undefined) return denied;
45 const format = formatFor(ctx.request.headers.get("accept"));
46 return new Response(render(forgeFamilies(ctx.app), format), {
47 headers: { "content-type": CONTENT_TYPE[format], "cache-control": "no-store" },
48 });
49 }
src/http/server.ts +5
@@ -470,6 +470,8 @@ import {
470470 type RouteTiming,
471471 } from "../core/route_timing.ts";
472472 import { methodOf, noteUsage, roleOf, surfaceOf, takeUsage } from "./usage_tag.ts";
473 import { httpLatency } from "../metrics/http.ts";
474 import { metricsResponse } from "./metrics.ts";
473475 import { oauthRoutes } from "./oauth.ts";
474476 import { flushAccess, recordAccess } from "./access_log.ts";
475477 import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts";
@@ -657,6 +659,8 @@ export function buildRouter(): Router<Handler> {
657659 router.add("GET", "/.well-known/change-password", changePassword);
658660 router.add("GET", "/robots.txt", robotsTxt);
659661 router.add("GET", "/releases.json", releasesJson);
662 // The forge's own series for a scraper (`docs/METRICS.md`): an admin, or the scrape token.
663 router.add("GET", "/metrics", metricsResponse);
660664 router.add("GET", "/sitemap.xml", sitemapXml);
661665 router.add("GET", "/manifest.webmanifest", webManifest);
662666 router.add("GET", "/opensearch.xml", openSearch);
@@ -2158,6 +2162,7 @@ export async function serve(app: App): Promise<Servers> {
21582162 timings.set(owner.db, timing);
21592163 }
21602164 timing.record(tag.pattern, ms);
2165 httpLatency(owner.db).record(tag.pattern, methodOf(request.method), response.status, ms);
21612166 } catch (error) {
21622167 owner.log.warn("could not time a request", { error: String(error) });
21632168 }
src/main.ts +4
@@ -136,6 +136,9 @@ const canonicalUrl = hosted ? hostedAt : (process.env.FORGE_URL ?? "").trim();
136136 // FORGE_EDGE_TOKEN is the platform edge's secret: with it, the edge's
137137 // identity headers sign people in; without it they are ignored.
138138 const edgeToken = (process.env.FORGE_EDGE_TOKEN ?? "").trim();
139 // FORGE_METRICS_TOKEN is what a scraper sends as its bearer to read
140 // /metrics without an admin's token (`http/metrics.ts`).
141 const metricsToken = (process.env.FORGE_METRICS_TOKEN ?? "").trim();
139142
140143 const dataDir = dataDirOf(process.env);
141144 // One answer for boot and `--preflight` (kernel/preflight.ts): the data
@@ -191,6 +194,7 @@ const app = createApp({
191194 : { host: process.env.FORGE_HOST }),
192195 ...(canonicalUrl === "" ? {} : { url: new URL(canonicalUrl).origin }),
193196 ...(edgeToken === "" ? {} : { edgeToken }),
197 ...(metricsToken === "" ? {} : { metricsToken }),
194198 // Hosted, the host says how this forge's terminal is reached; printed
195199 // verbatim wherever the forge tells people how to connect.
196200 ...(hosted && (process.env.FORGE_APP_SSH ?? "").trim() !== ""
src/metrics/http.ts added +80
@@ -0,0 +1,80 @@
1 /**
2 * How long the forge took to answer, by route, since this process started:
3 * the same duration the response's `Server-Timing: total` carries, kept as
4 * a histogram a scraper turns into rates and quantiles. In memory, one per
5 * database (a hosted child counts in its own), because a counter that
6 * resets when the process does is what Prometheus expects; the hourly table
7 * the boards read is `core/route_timing.ts`.
8 *
9 * The key is the route pattern the router matched, never the raw path, and
10 * the status as its class, so what strangers type cannot grow it.
11 */
12
13 import type { Database } from "bun:sqlite";
14 import { EDGES_MS } from "../core/route_timing.ts";
15 import type { HistogramPoint } from "./openmetrics.ts";
16
17 /** Upper bounds in seconds: the route timing's own edges. */
18 export const EDGES_S: readonly number[] = EDGES_MS.map((ms) => ms / 1000);
19
20 interface Cell {
21 readonly route: string;
22 readonly method: string;
23 readonly code: string;
24 readonly counts: number[];
25 sum: number;
26 }
27
28 export interface HttpLatency {
29 record(route: string, method: string, status: number, ms: number): void;
30 points(): HistogramPoint[];
31 }
32
33 const byDb = new WeakMap<Database, HttpLatency>();
34
35 /** The status as its class: `2xx` … `5xx`. */
36 const classOf = (status: number): string => `${Math.min(5, Math.max(1, Math.floor(status / 100)))}xx`;
37
38 function bucketOf(seconds: number): number {
39 for (let i = 0; i < EDGES_S.length; i++) if (seconds <= EDGES_S[i]!) return i;
40 return EDGES_S.length;
41 }
42
43 export function createHttpLatency(): HttpLatency {
44 const cells = new Map<string, Cell>();
45 return {
46 record(route, method, status, ms) {
47 const code = classOf(status);
48 const key = `${route}\u0000${method}\u0000${code}`;
49 let cell = cells.get(key);
50 if (cell === undefined) {
51 cell = { route, method, code, counts: new Array<number>(EDGES_S.length + 1).fill(0), sum: 0 };
52 cells.set(key, cell);
53 }
54 const seconds = Math.max(0, ms) / 1000;
55 cell.counts[bucketOf(seconds)]!++;
56 cell.sum += seconds;
57 },
58 points() {
59 return [...cells.values()]
60 .sort((a, b) =>
61 a.route !== b.route ? (a.route < b.route ? -1 : 1) : `${a.method}${a.code}` < `${b.method}${b.code}` ? -1 : 1,
62 )
63 .map((c) => ({
64 labels: { route: c.route, method: c.method, code: c.code },
65 counts: [...c.counts],
66 sum: c.sum,
67 }));
68 },
69 };
70 }
71
72 /** The histogram this database's requests are counted in. */
73 export function httpLatency(db: Database): HttpLatency {
74 let latency = byDb.get(db);
75 if (latency === undefined) {
76 latency = createHttpLatency();
77 byDb.set(db, latency);
78 }
79 return latency;
80 }
src/metrics/openmetrics.ts added +154
@@ -0,0 +1,154 @@
1 /**
2 * The text a scraper reads: metric families written as OpenMetrics 1.0
3 * (`application/openmetrics-text`) or, for a client that asks for nothing
4 * newer, the Prometheus text format 0.0.4 it grew out of. Plain data in, a
5 * string out; no state.
6 *
7 * Names are the forge's own constants, so a bad one is a defect, not an
8 * input: it is refused here before a scrape could carry it. Label values are
9 * input (a repository's name, an agent's), so they are escaped, never trusted.
10 */
11
12 import { defect } from "../kernel/error.ts";
13
14 export type Labels = Readonly<Record<string, string>>;
15
16 export interface Point {
17 readonly labels: Labels;
18 readonly value: number;
19 }
20
21 export interface HistogramPoint {
22 readonly labels: Labels;
23 /** Observations per bucket, not cumulative: one per edge, then one above the last. */
24 readonly counts: readonly number[];
25 readonly sum: number;
26 }
27
28 interface Base {
29 /** The family's name: for a counter without `_total`, for an info without `_info`, which the sample gains. */
30 readonly name: string;
31 readonly help: string;
32 /** A base unit (`seconds`, `bytes`); the name must end with it. */
33 readonly unit?: string;
34 }
35
36 export type Family =
37 | (Base & { readonly type: "counter" | "gauge"; readonly points: readonly Point[] })
38 /** What is true now, as labels on a sample that is always 1: the running version. */
39 | (Base & { readonly type: "info"; readonly points: readonly { readonly labels: Labels }[] })
40 | (Base & {
41 readonly type: "histogram";
42 /** Upper bounds, ascending; `+Inf` is added. */
43 readonly edges: readonly number[];
44 readonly points: readonly HistogramPoint[];
45 });
46
47 export type Format = "openmetrics" | "prometheus";
48
49 export const CONTENT_TYPE: Record<Format, string> = {
50 openmetrics: "application/openmetrics-text; version=1.0.0; charset=utf-8",
51 prometheus: "text/plain; version=0.0.4; charset=utf-8",
52 };
53
54 const METRIC_NAME = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
55 const LABEL_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
56 const RESERVED_SUFFIX = /_(total|created|bucket|count|sum|info)$/;
57
58 /** Which format a scraper asked for: OpenMetrics when its Accept names it. */
59 export function formatFor(accept: string | null): Format {
60 return /application\/openmetrics-text/i.test(accept ?? "") ? "openmetrics" : "prometheus";
61 }
62
63 /** A number as both formats write it. */
64 export function number(n: number): string {
65 if (Number.isNaN(n)) return "NaN";
66 if (n === Infinity) return "+Inf";
67 if (n === -Infinity) return "-Inf";
68 return String(n);
69 }
70
71 const escapeLabel = (v: string): string =>
72 v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
73
74 const escapeHelp = (v: string, format: Format): string => {
75 const out = v.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
76 return format === "openmetrics" ? out.replace(/"/g, '\\"') : out;
77 };
78
79 function labelText(labels: Labels, extra?: readonly [string, string]): string {
80 const pairs = Object.entries(labels);
81 if (extra !== undefined) pairs.push([extra[0], extra[1]]);
82 if (pairs.length === 0) return "";
83 return `{${pairs.map(([k, v]) => `${k}="${escapeLabel(v)}"`).join(",")}}`;
84 }
85
86 function check(family: Family): void {
87 const { name, unit } = family;
88 if (!METRIC_NAME.test(name) || RESERVED_SUFFIX.test(name))
89 defect("metric_name", `not a family name: ${name}`);
90 if (unit !== undefined && !name.endsWith(`_${unit}`))
91 defect("metric_unit", `${name} does not end with its unit ${unit}`);
92 const seen = new Set<string>();
93 for (const point of family.points) {
94 const keys = Object.keys(point.labels);
95 for (const key of keys)
96 if (!LABEL_NAME.test(key) || key.startsWith("__") || (family.type === "histogram" && key === "le"))
97 defect("metric_label", `${name}: not a label name: ${key}`);
98 const set = labelText(point.labels);
99 if (seen.has(set)) defect("metric_labels", `${name}: two points with ${set || "no labels"}`);
100 seen.add(set);
101 }
102 if (family.type === "histogram") {
103 for (let i = 1; i < family.edges.length; i++)
104 if (!(family.edges[i]! > family.edges[i - 1]!)) defect("metric_edges", `${name}: edges not ascending`);
105 for (const point of family.points)
106 if (point.counts.length !== family.edges.length + 1)
107 defect("metric_counts", `${name}: ${point.counts.length} counts for ${family.edges.length} edges`);
108 }
109 }
110
111 function familyText(family: Family, format: Format): string[] {
112 check(family);
113 const { name } = family;
114 // Prometheus 0.0.4 names a family by its sample and has no info type; OpenMetrics names it by its stem.
115 const suffix = family.type === "counter" ? "_total" : family.type === "info" ? "_info" : "";
116 const head = format === "prometheus" ? `${name}${suffix}` : name;
117 const type = family.type === "info" && format === "prometheus" ? "gauge" : family.type;
118 const lines = [`# TYPE ${head} ${type}`];
119 if (family.unit !== undefined && format === "openmetrics") lines.push(`# UNIT ${head} ${family.unit}`);
120 lines.push(`# HELP ${head} ${escapeHelp(family.help, format)}`);
121 if (family.type === "info") {
122 for (const p of family.points) lines.push(`${name}_info${labelText(p.labels)} 1`);
123 return lines;
124 }
125 if (family.type !== "histogram") {
126 for (const p of family.points) lines.push(`${name}${suffix}${labelText(p.labels)} ${number(p.value)}`);
127 return lines;
128 }
129 for (const p of family.points) {
130 let running = 0;
131 family.edges.forEach((edge, i) => {
132 running += p.counts[i]!;
133 lines.push(`${name}_bucket${labelText(p.labels, ["le", number(edge)])} ${running}`);
134 });
135 running += p.counts[family.edges.length]!;
136 lines.push(`${name}_bucket${labelText(p.labels, ["le", "+Inf"])} ${running}`);
137 lines.push(`${name}_count${labelText(p.labels)} ${running}`);
138 lines.push(`${name}_sum${labelText(p.labels)} ${number(p.sum)}`);
139 }
140 return lines;
141 }
142
143 /** Every family, in order, as one exposition. Two families may not share a name. */
144 export function render(families: readonly Family[], format: Format): string {
145 const names = new Set<string>();
146 const lines: string[] = [];
147 for (const family of families) {
148 if (names.has(family.name)) defect("metric_family", `two families named ${family.name}`);
149 names.add(family.name);
150 lines.push(...familyText(family, format));
151 }
152 if (format === "openmetrics") lines.push("# EOF");
153 return `${lines.join("\n")}\n`;
154 }
src/metrics/series.ts added +278
@@ -0,0 +1,278 @@
1 /**
2 * The forge's own series (`docs/METRICS.md` names each): what landed, how
3 * long asks take to go live, how the checks and main fare, what the crew ran
4 * and spent, how fast the forge answered, what the machine and its cells use,
5 * releases, and which app environments are up or asleep.
6 *
7 * Read when a scraper asks, from the tables every page already reads and the
8 * runtime in memory: nothing here is kept for the scrape alone, except the
9 * HTTP histogram (`metrics/http.ts`). Counters are totals over what the
10 * database holds, so each moves when its event is written. No authz: the
11 * door (`http/metrics.ts`) lets only an admin or the scrape token in.
12 */
13
14 import type { Database } from "bun:sqlite";
15 import type { App } from "../app.ts";
16 import { appsRuntime, type EnvState } from "../apps/runtime.ts";
17 import { readThroughput } from "../flow/throughput.ts";
18 import { running } from "../kernel/version.ts";
19 import { EDGES_S, httpLatency } from "./http.ts";
20 import type { Family, HistogramPoint, Point } from "./openmetrics.ts";
21
22 /** Check durations' upper bounds in seconds: half a minute to an hour. */
23 export const CHECK_EDGES_S = [30, 60, 120, 300, 600, 900, 1200, 1800, 2700, 3600] as const;
24
25 /** A machine sample older than this is no longer "now", so it is not said. */
26 const MACHINE_FRESH_MS = 2 * 60_000;
27
28 const ENV_STATES: readonly EnvState[] = ["running", "asleep", "deploying", "stopped", "failed"];
29
30 /** Seconds between two ISO columns, in SQL. */
31 const seconds = (from: string, to: string) => `((julianday(${to}) - julianday(${from})) * 86400.0)`;
32
33 /** `owner/name` of the repository `alias` is, in SQL. */
34 const REPO_NAME = "(SELECT u.username || '/' || r.name FROM repo r JOIN user u ON u.id = r.owner_id WHERE r.id = ";
35
36 function pullsLanded(db: Database): Point[] {
37 return db
38 .query<{ repo: string; n: number }, []>(
39 `SELECT u.username || '/' || r.name AS repo, COUNT(*) AS n
40 FROM pull p JOIN issue i ON i.id = p.issue_id JOIN repo r ON r.id = i.repo_id
41 JOIN user u ON u.id = r.owner_id
42 WHERE p.merged_at IS NOT NULL GROUP BY r.id ORDER BY repo`,
43 )
44 .all()
45 .map((r) => ({ labels: { repo: r.repo }, value: r.n }));
46 }
47
48 function runsNow(db: Database): Point[] {
49 const counts = new Map(
50 db
51 .query<{ kind: string; state: string; n: number }, []>(
52 "SELECT kind, state, COUNT(*) AS n FROM run WHERE state IN ('queued','running') GROUP BY kind, state",
53 )
54 .all()
55 .map((r) => [`${r.kind} ${r.state}`, r.n]),
56 );
57 const out: Point[] = [];
58 for (const kind of ["agent", "check", "deploy"])
59 for (const state of ["queued", "running"])
60 out.push({ labels: { kind, state }, value: counts.get(`${kind} ${state}`) ?? 0 });
61 return out;
62 }
63
64 function oldestQueuedCheck(db: Database, now: Date): Point[] {
65 const row = db
66 .query<{ at: string | null }, []>("SELECT MIN(created_at) AS at FROM run WHERE kind = 'check' AND state = 'queued'")
67 .get();
68 const at = row?.at ?? null;
69 return [{ labels: {}, value: at === null ? 0 : Math.max(0, (now.getTime() - Date.parse(at)) / 1000) }];
70 }
71
72 function checkDurations(db: Database): HistogramPoint[] {
73 const bucket = `CASE ${CHECK_EDGES_S.map((e, i) => `WHEN d <= ${e} THEN ${i}`).join(" ")} ELSE ${CHECK_EDGES_S.length} END`;
74 const rows = db
75 .query<{ state: string; b: number; n: number; s: number }, []>(
76 `SELECT state, ${bucket} AS b, COUNT(*) AS n, SUM(d) AS s FROM (
77 SELECT state, MAX(0, ${seconds("started_at", "finished_at")}) AS d FROM run
78 WHERE kind = 'check' AND state IN ('ok','failed')
79 AND started_at IS NOT NULL AND finished_at IS NOT NULL)
80 GROUP BY state, b`,
81 )
82 .all();
83 return ["ok", "failed"].map((outcome) => {
84 const counts = new Array<number>(CHECK_EDGES_S.length + 1).fill(0);
85 let sum = 0;
86 for (const r of rows)
87 if (r.state === outcome) {
88 counts[r.b] = r.n;
89 sum += r.s;
90 }
91 return { labels: { outcome }, counts, sum };
92 });
93 }
94
95 /**
96 * Each repository's red main: whether its default branch's last finished
97 * check failed (the rule `checks/red_main.ts` holds pulls by), and how long
98 * it has been red in all — every failed main check counts from when it
99 * finished until the next one did, or until now.
100 */
101 function redMain(db: Database, now: Date): { red: Point[]; seconds: Point[] } {
102 const rows = db
103 .query<{ repo: string; red: number; s: number }, [string]>(
104 `SELECT ${REPO_NAME}repo_id) AS repo,
105 MAX(CASE WHEN next IS NULL AND state = 'failed' THEN 1 ELSE 0 END) AS red,
106 SUM(CASE WHEN state = 'failed' THEN MAX(0, ${seconds("at", "COALESCE(next, ?1)")}) ELSE 0 END) AS s
107 FROM (SELECT x.repo_id, x.state, COALESCE(x.finished_at, x.created_at) AS at,
108 LEAD(COALESCE(x.finished_at, x.created_at)) OVER (PARTITION BY x.repo_id ORDER BY x.id) AS next
109 FROM run x JOIN repo ON repo.id = x.repo_id
110 WHERE x.kind = 'check' AND x.issue_id IS NULL AND x.env = repo.default_branch
111 AND x.state IN ('ok','failed'))
112 GROUP BY repo_id ORDER BY repo`,
113 )
114 .all(now.toISOString());
115 return {
116 red: rows.map((r) => ({ labels: { repo: r.repo }, value: r.red })),
117 seconds: rows.map((r) => ({ labels: { repo: r.repo }, value: r.s })),
118 };
119 }
120
121 function crewRuns(db: Database): Point[] {
122 return db
123 .query<{ member: string; state: string; n: number }, []>(
124 `SELECT u.username AS member, x.state AS state, COUNT(*) AS n
125 FROM run x JOIN user u ON u.id = x.actor_id
126 WHERE x.kind = 'agent' AND x.state IN ('ok','failed','cancelled')
127 GROUP BY u.username, x.state ORDER BY member, state`,
128 )
129 .all()
130 .map((r) => ({ labels: { member: r.member, outcome: r.state }, value: r.n }));
131 }
132
133 function crewSpend(db: Database): { usd: Point[]; tokens: Point[] } {
134 const rows = db
135 .query<{ member: string; usd: number; tin: number; tout: number }, []>(
136 `SELECT u.username AS member, SUM(g.cost_usd) AS usd, SUM(g.tokens_in) AS tin, SUM(g.tokens_out) AS tout
137 FROM usage g JOIN user u ON u.id = g.agent_id GROUP BY u.username ORDER BY member`,
138 )
139 .all();
140 return {
141 usd: rows.map((r) => ({ labels: { member: r.member }, value: r.usd })),
142 tokens: rows.flatMap((r) => [
143 { labels: { member: r.member, direction: "in" }, value: r.tin },
144 { labels: { member: r.member, direction: "out" }, value: r.tout },
145 ]),
146 };
147 }
148
149 function machine(db: Database, now: Date): { cpu: Point[]; memory: Point[] } {
150 const rows = db
151 .query<{ target: string; cpu: number | null; mem: number | null }, [string]>(
152 `SELECT target, cpu_cores AS cpu, memory_bytes AS mem FROM machine_sample
153 WHERE step = 15 AND at = (SELECT MAX(at) FROM machine_sample WHERE step = 15) AND at >= ?1
154 ORDER BY target`,
155 )
156 .all(new Date(now.getTime() - MACHINE_FRESH_MS).toISOString());
157 return {
158 cpu: rows.flatMap((r) => (r.cpu === null ? [] : [{ labels: { target: r.target }, value: r.cpu }])),
159 memory: rows.flatMap((r) => (r.mem === null ? [] : [{ labels: { target: r.target }, value: r.mem }])),
160 };
161 }
162
163 function releases(db: Database): Point[] {
164 const counts = new Map(
165 db
166 .query<{ ok: number; n: number }, []>("SELECT ok, COUNT(*) AS n FROM release GROUP BY ok")
167 .all()
168 .map((r) => [r.ok === 1, r.n]),
169 );
170 return [
171 { labels: { outcome: "ok" }, value: counts.get(true) ?? 0 },
172 { labels: { outcome: "failed" }, value: counts.get(false) ?? 0 },
173 ];
174 }
175
176 function appEnvironments(app: App): Point[] {
177 const runtime = appsRuntime(app);
178 if (runtime === undefined) return [];
179 const counts = new Map<string, number>();
180 for (const s of runtime.states()) {
181 const k = `${s.env === "production" ? "production" : "preview"} ${s.state}`;
182 counts.set(k, (counts.get(k) ?? 0) + 1);
183 }
184 return ["production", "preview"].flatMap((env) =>
185 ENV_STATES.map((state) => ({ labels: { env, state }, value: counts.get(`${env} ${state}`) ?? 0 })),
186 );
187 }
188
189 /** Every family, in the order `docs/METRICS.md` lists them. */
190 export function forgeFamilies(app: App, now = new Date()): Family[] {
191 const { db } = app;
192 const version = running();
193 const askToLive = readThroughput(db, [], now).medianAskToLiveMs;
194 const red = redMain(db, now);
195 const spend = crewSpend(db);
196 const cells = machine(db, now);
197 return [
198 {
199 name: "forge_build",
200 type: "info",
201 help: "The forge release answering this scrape.",
202 points: [{ labels: { version: version.version, commit: version.commit ?? "" } }],
203 },
204 { name: "forge_pulls_landed", type: "counter", help: "Pulls merged, by repository.", points: pullsLanded(db) },
205 {
206 name: "forge_ask_to_live_median_seconds",
207 type: "gauge",
208 unit: "seconds",
209 help: "Median time from an issue being asked to its pull serving in production, over what went live in the last 24 hours.",
210 points: askToLive === null ? [] : [{ labels: {}, value: askToLive / 1000 }],
211 },
212 { name: "forge_runs", type: "gauge", help: "Runs queued or running now, by kind (agent, check, deploy).", points: runsNow(db) },
213 {
214 name: "forge_check_queue_oldest_seconds",
215 type: "gauge",
216 unit: "seconds",
217 help: "How long the oldest queued check has waited; 0 when none waits.",
218 points: oldestQueuedCheck(db, now),
219 },
220 {
221 name: "forge_check_duration_seconds",
222 type: "histogram",
223 unit: "seconds",
224 help: "How long finished checks ran, start to finish, by outcome.",
225 edges: CHECK_EDGES_S,
226 points: checkDurations(db),
227 },
228 {
229 name: "forge_main_red",
230 type: "gauge",
231 help: "1 while a repository's default branch's last finished check failed, else 0.",
232 points: red.red,
233 },
234 {
235 name: "forge_main_red_seconds",
236 type: "counter",
237 unit: "seconds",
238 help: "Time a repository's default branch has spent red: from each failed main check until the next one finished.",
239 points: red.seconds,
240 },
241 { name: "forge_crew_runs", type: "counter", help: "Crew runs finished, by member and outcome.", points: crewRuns(db) },
242 { name: "forge_crew_spend_usd", type: "counter", help: "What crew runs cost in US dollars, by member.", points: spend.usd },
243 {
244 name: "forge_crew_tokens",
245 type: "counter",
246 help: "Model tokens crew runs used, by member and direction (in, out).",
247 points: spend.tokens,
248 },
249 {
250 name: "forge_http_request_duration_seconds",
251 type: "histogram",
252 unit: "seconds",
253 help: "How long the forge took to answer (Server-Timing total), by route pattern, method and status class, since this process started.",
254 edges: EDGES_S,
255 points: httpLatency(db).points(),
256 },
257 {
258 name: "forge_cpu_cores",
259 type: "gauge",
260 help: "CPU cores in use at the last machine sample, by target: node, forge, each cell, each core.",
261 points: cells.cpu,
262 },
263 {
264 name: "forge_memory_bytes",
265 type: "gauge",
266 unit: "bytes",
267 help: "Memory in use at the last machine sample, by target: node, forge, each cell.",
268 points: cells.memory,
269 },
270 { name: "forge_releases", type: "counter", help: "Forge releases rolled out, by outcome.", points: releases(db) },
271 {
272 name: "forge_app_environments",
273 type: "gauge",
274 help: "App environments now, by env (production, preview) and state (running, asleep, deploying, stopped, failed).",
275 points: appEnvironments(app),
276 },
277 ];
278 }
test/helpers/openmetrics.ts added +203
@@ -0,0 +1,203 @@
1 /**
2 * A strict OpenMetrics 1.0 text parser, for tests: it throws on anything the
3 * spec's ABNF or its family rules refuse, so a scrape that parses here is
4 * one Prometheus will take. Checked: `# EOF` last and nothing after; no blank
5 * lines; one TYPE, UNIT and HELP per family, before its samples; a family's
6 * lines together and its name used once; each sample's name one its type
7 * allows (`_total` for a counter, `_bucket`/`_count`/`_sum` for a histogram,
8 * `_info` for an info); a unit the name ends with; label names valid and
9 * unrepeated, values escaped only as `\\`, `\"`, `\n`; numbers as the spec
10 * writes them; a counter never negative or NaN; an info always 1; no two
11 * samples with one name and label set; a histogram's `le` ascending to
12 * `+Inf`, cumulative, with `_count` equal to its `+Inf` bucket and a `_sum`.
13 */
14
15 export interface ParsedSample {
16 readonly name: string;
17 readonly labels: Readonly<Record<string, string>>;
18 readonly value: number;
19 }
20
21 export interface ParsedFamily {
22 readonly name: string;
23 type: string;
24 help?: string;
25 unit?: string;
26 readonly samples: ParsedSample[];
27 }
28
29 const METRIC_NAME = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
30 const LABEL_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
31 const NUMBER = /^(?:[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[+-]?Inf|NaN)$/;
32 const TYPES = new Set(["counter", "gauge", "histogram", "gaugehistogram", "stateset", "info", "summary", "unknown"]);
33 const SUFFIXES: Record<string, readonly string[]> = {
34 counter: ["_total", "_created"],
35 gauge: [""],
36 histogram: ["_bucket", "_count", "_sum", "_created"],
37 gaugehistogram: ["_bucket", "_gcount", "_gsum"],
38 stateset: [""],
39 info: ["_info"],
40 summary: ["", "_count", "_sum", "_created"],
41 unknown: [""],
42 };
43
44 const fail = (line: number, why: string): never => {
45 throw new Error(`openmetrics line ${line}: ${why}`);
46 };
47
48 function parseNumber(text: string, line: number): number {
49 if (!NUMBER.test(text)) fail(line, `not a number: ${text}`);
50 if (text.endsWith("Inf")) return text.startsWith("-") ? -Infinity : Infinity;
51 return text === "NaN" ? NaN : Number(text);
52 }
53
54 /** `{a="1",b="2"}` from `at` in `text`; returns the labels and where they end. */
55 function parseLabels(text: string, at: number, line: number): { labels: Record<string, string>; end: number } {
56 const labels: Record<string, string> = {};
57 let i = at + 1;
58 if (text[i] === "}") return { labels, end: i + 1 };
59 for (;;) {
60 const eq = text.indexOf("=", i);
61 if (eq === -1) fail(line, "label without =");
62 const name = text.slice(i, eq);
63 if (!LABEL_NAME.test(name)) fail(line, `not a label name: ${name}`);
64 if (name in labels) fail(line, `label repeated: ${name}`);
65 if (text[eq + 1] !== '"') fail(line, `label ${name} not quoted`);
66 let value = "";
67 let j = eq + 2;
68 for (;;) {
69 const c = text[j];
70 if (c === undefined) fail(line, "label value not closed");
71 if (c === '"') break;
72 if (c === "\\") {
73 const n = text[j + 1];
74 if (n === "\\") value += "\\";
75 else if (n === '"') value += '"';
76 else if (n === "n") value += "\n";
77 else fail(line, `bad escape \\${n ?? ""}`);
78 j += 2;
79 continue;
80 }
81 value += c;
82 j++;
83 }
84 labels[name] = value;
85 i = j + 1;
86 if (text[i] === "}") return { labels, end: i + 1 };
87 if (text[i] !== ",") fail(line, "labels not separated by a comma");
88 i++;
89 }
90 }
91
92 const setKey = (labels: Record<string, string>): string =>
93 JSON.stringify(Object.entries(labels).sort(([a], [b]) => (a < b ? -1 : 1)));
94
95 function checkHistogram(family: ParsedFamily): void {
96 const sets = new Map<string, { le: number[]; counts: number[]; count?: number; sum?: number }>();
97 for (const s of family.samples) {
98 const { le, ...rest } = s.labels;
99 const key = setKey(rest);
100 const set = sets.get(key) ?? { le: [], counts: [] };
101 sets.set(key, set);
102 if (s.name.endsWith("_bucket")) {
103 if (le === undefined) throw new Error(`${family.name}: a bucket without le`);
104 if (!NUMBER.test(le)) throw new Error(`${family.name}: le not a number: ${le}`);
105 set.le.push(le === "+Inf" ? Infinity : Number(le));
106 set.counts.push(s.value);
107 } else if (s.name.endsWith("_count")) set.count = s.value;
108 else if (s.name.endsWith("_sum")) set.sum = s.value;
109 }
110 for (const [key, set] of sets) {
111 if (set.le.at(-1) !== Infinity) throw new Error(`${family.name} ${key}: no +Inf bucket last`);
112 for (let i = 1; i < set.le.length; i++) {
113 if (!(set.le[i]! > set.le[i - 1]!)) throw new Error(`${family.name} ${key}: le not ascending`);
114 if (set.counts[i]! < set.counts[i - 1]!) throw new Error(`${family.name} ${key}: buckets not cumulative`);
115 }
116 if (set.count !== set.counts.at(-1)) throw new Error(`${family.name} ${key}: _count is not the +Inf bucket`);
117 if (set.sum === undefined) throw new Error(`${family.name} ${key}: no _sum`);
118 }
119 }
120
121 export function parseOpenMetrics(text: string): Map<string, ParsedFamily> {
122 if (!text.endsWith("# EOF\n")) throw new Error("openmetrics: does not end with # EOF and a newline");
123 const lines = text.slice(0, -"# EOF\n".length).split("\n");
124 lines.pop(); // the newline before # EOF
125 const families = new Map<string, ParsedFamily>();
126 const seen = new Set<string>();
127 let current: ParsedFamily | undefined;
128 let sampled = false;
129 const open = (name: string, n: number): ParsedFamily => {
130 if (current?.name === name) return current;
131 if (families.has(name)) fail(n, `family ${name} interleaved or repeated`);
132 current = { name, type: "unknown", samples: [] };
133 families.set(name, current);
134 sampled = false;
135 return current;
136 };
137 lines.forEach((raw, index) => {
138 const n = index + 1;
139 if (raw === "") fail(n, "blank line");
140 if (raw.startsWith("#")) {
141 const m = /^# (TYPE|HELP|UNIT) ([^ ]+)(?: (.*))?$/.exec(raw);
142 if (m === null) fail(n, `not a metadata line: ${raw}`);
143 const [, kind, name, rest = ""] = m!;
144 if (!METRIC_NAME.test(name!)) fail(n, `not a metric name: ${name}`);
145 const family = open(name!, n);
146 if (sampled) fail(n, `${kind} after ${name}'s samples`);
147 if (kind === "TYPE") {
148 if (!TYPES.has(rest)) fail(n, `not a type: ${rest}`);
149 if (family.type !== "unknown" || family.samples.length) fail(n, `TYPE repeated for ${name}`);
150 family.type = rest;
151 } else if (kind === "HELP") {
152 if (family.help !== undefined) fail(n, `HELP repeated for ${name}`);
153 if (!/^(?:[^\\]|\\[\\"n])*$/.test(rest)) fail(n, "bad escape in HELP");
154 family.help = rest.replace(/\\(.)/g, (_, c: string) => (c === "n" ? "\n" : c));
155 } else {
156 if (family.unit !== undefined) fail(n, `UNIT repeated for ${name}`);
157 if (rest !== "" && !name!.endsWith(`_${rest}`)) fail(n, `${name} does not end with its unit ${rest}`);
158 family.unit = rest;
159 }
160 return;
161 }
162 const nameEnd = raw.search(/[{ ]/);
163 if (nameEnd <= 0) fail(n, `not a sample: ${raw}`);
164 const name = raw.slice(0, nameEnd);
165 if (!METRIC_NAME.test(name)) fail(n, `not a metric name: ${name}`);
166 let labels: Record<string, string> = {};
167 let rest = raw.slice(nameEnd);
168 if (rest.startsWith("{")) {
169 const parsed = parseLabels(raw, nameEnd, n);
170 labels = parsed.labels;
171 rest = raw.slice(parsed.end);
172 }
173 const parts = rest.split(" ");
174 if (parts[0] !== "" || parts.length < 2 || parts.length > 3) fail(n, `bad value part: ${rest}`);
175 const value = parseNumber(parts[1]!, n);
176 if (parts[2] !== undefined) parseNumber(parts[2], n);
177 if (current === undefined) fail(n, `${name} before any family`);
178 const family = current!;
179 const suffix = SUFFIXES[family.type]!.find((s) => name === `${family.name}${s}`);
180 if (suffix === undefined) fail(n, `${name} is not a sample of ${family.type} ${family.name}`);
181 if (family.type === "counter" && (Number.isNaN(value) || value < 0)) fail(n, `counter ${name} is ${value}`);
182 if (family.type === "info" && value !== 1) fail(n, `info ${name} is ${value}, not 1`);
183 const key = `${name} ${setKey(labels)}`;
184 if (seen.has(key)) fail(n, `sample repeated: ${key}`);
185 seen.add(key);
186 sampled = true;
187 family.samples.push({ name, labels, value });
188 });
189 for (const family of families.values()) if (family.type === "histogram") checkHistogram(family);
190 return families;
191 }
192
193 /** The value of the sample `name` whose labels include `labels`; undefined when none. */
194 export function valueOf(
195 families: Map<string, ParsedFamily>,
196 name: string,
197 labels: Record<string, string> = {},
198 ): number | undefined {
199 for (const family of families.values())
200 for (const s of family.samples)
201 if (s.name === name && Object.entries(labels).every(([k, v]) => s.labels[k] === v)) return s.value;
202 return undefined;
203 }
test/metrics.test.ts added +300
@@ -0,0 +1,300 @@
1 /**
2 * GET /metrics speaks OpenMetrics (#3690): the writer's text parses with a
3 * strict parser in both formats a scraper may ask for; only an admin or the
4 * scrape token reads it; and each of the forge's series moves when its
5 * event is written.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { readFileSync } from "node:fs";
12 import { createApp, type App } from "../src/app.ts";
13 import { AppsRuntime } from "../src/apps/runtime.ts";
14 import { createAgent } from "../src/actions/crew.ts";
15 import { createRepo } from "../src/actions/repos.ts";
16 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { recordUsage } from "../src/core/usage.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { createHttpLatency } from "../src/metrics/http.ts";
22 import { formatFor, render, type Family } from "../src/metrics/openmetrics.ts";
23 import { forgeFamilies } from "../src/metrics/series.ts";
24 import { recordRelease } from "../src/release/record.ts";
25 import { parseOpenMetrics, valueOf } from "./helpers/openmetrics.ts";
26
27 const SAMPLE: Family[] = [
28 { name: "x_build", type: "info", help: "b", points: [{ labels: { version: "1.2.3" } }] },
29 {
30 name: "x_landed",
31 type: "counter",
32 help: 'pulls "merged"\nback\\slash',
33 points: [{ labels: { repo: 'we"ird\\na\nme' }, value: 3 }],
34 },
35 { name: "x_age_seconds", type: "gauge", unit: "seconds", help: "a", points: [{ labels: {}, value: 0.25 }] },
36 {
37 name: "x_took_seconds",
38 type: "histogram",
39 unit: "seconds",
40 help: "t",
41 edges: [0.1, 1],
42 points: [{ labels: { route: "/" }, counts: [2, 0, 1], sum: 7.5 }],
43 },
44 ];
45
46 describe("the OpenMetrics writer", () => {
47 test("its text parses strictly, label values escaped and read back whole", () => {
48 const text = render(SAMPLE, "openmetrics");
49 const parsed = parseOpenMetrics(text);
50 expect([...parsed.keys()]).toEqual(["x_build", "x_landed", "x_age_seconds", "x_took_seconds"]);
51 expect(parsed.get("x_landed")!.help).toBe('pulls "merged"\nback\\slash');
52 expect(valueOf(parsed, "x_landed_total", { repo: 'we"ird\\na\nme' })).toBe(3);
53 expect(valueOf(parsed, "x_build_info", { version: "1.2.3" })).toBe(1);
54 expect(parsed.get("x_age_seconds")!.unit).toBe("seconds");
55 expect(valueOf(parsed, "x_took_seconds_bucket", { le: "0.1" })).toBe(2);
56 expect(valueOf(parsed, "x_took_seconds_bucket", { le: "1" })).toBe(2);
57 expect(valueOf(parsed, "x_took_seconds_bucket", { le: "+Inf" })).toBe(3);
58 expect(valueOf(parsed, "x_took_seconds_count")).toBe(3);
59 expect(valueOf(parsed, "x_took_seconds_sum")).toBe(7.5);
60 });
61
62 test("the Prometheus text format names families by their sample and carries no UNIT or EOF", () => {
63 const text = render(SAMPLE, "prometheus");
64 expect(text).toContain("# TYPE x_landed_total counter\n");
65 expect(text).toContain("# TYPE x_build_info gauge\n");
66 expect(text).not.toContain("# UNIT");
67 expect(text).not.toContain("# EOF");
68 expect(text).toContain('x_landed_total{repo="we\\"ird\\\\na\\nme"} 3\n');
69 });
70
71 test("a scraper gets OpenMetrics only when it asks", () => {
72 expect(formatFor("application/openmetrics-text;version=1.0.0,text/plain;q=0.5")).toBe("openmetrics");
73 expect(formatFor("text/plain")).toBe("prometheus");
74 expect(formatFor(null)).toBe("prometheus");
75 });
76
77 test("a name, unit or label set the spec refuses is a defect, never a scrape", () => {
78 const bad: Family[][] = [
79 [{ name: "x_total", type: "counter", help: "", points: [] }],
80 [{ name: "9x", type: "gauge", help: "", points: [] }],
81 [{ name: "x_age", type: "gauge", unit: "seconds", help: "", points: [] }],
82 [{ name: "x", type: "gauge", help: "", points: [{ labels: { "a-b": "1" }, value: 1 }] }],
83 [{ name: "x", type: "gauge", help: "", points: [{ labels: {}, value: 1 }, { labels: {}, value: 2 }] }],
84 [{ name: "x", type: "histogram", help: "", edges: [1], points: [{ labels: { le: "1" }, counts: [0, 0], sum: 0 }] }],
85 [{ name: "x", type: "histogram", help: "", edges: [2, 1], points: [] }],
86 [
87 { name: "x", type: "gauge", help: "", points: [] },
88 { name: "x", type: "gauge", help: "", points: [] },
89 ],
90 ];
91 for (const families of bad) expect(() => render(families, "openmetrics")).toThrow();
92 });
93
94 test("the strict parser refuses what the spec refuses", () => {
95 const refused = [
96 "# TYPE a counter\na_total 1\n", // no EOF
97 "# TYPE a counter\na 1\n# EOF\n", // a counter's sample without _total
98 "# TYPE a counter\na_total -1\n# EOF\n",
99 "# TYPE a gauge\n\na 1\n# EOF\n", // blank line
100 '# TYPE a gauge\na{b="\\t"} 1\n# EOF\n', // a bad escape
101 "# TYPE a gauge\na 1\na 2\n# EOF\n", // a repeated sample
102 "# TYPE a gauge\n# TYPE b gauge\nb 1\n# TYPE a gauge\n# EOF\n", // a family repeated
103 "# TYPE a_b gauge\n# UNIT a_b seconds\n# EOF\n", // a unit the name lacks
104 '# TYPE h histogram\nh_bucket{le="1"} 2\nh_bucket{le="+Inf"} 1\nh_count 1\nh_sum 0\n# EOF\n',
105 "# TYPE a gauge\na 1\n# EOF\nmore\n",
106 ];
107 for (const text of refused) expect(() => parseOpenMetrics(text)).toThrow();
108 });
109
110 test("the HTTP histogram keys by route, method and status class", () => {
111 const h = createHttpLatency();
112 h.record("/healthz", "GET", 200, 0.5);
113 h.record("/healthz", "GET", 204, 3000);
114 h.record("/:owner", "GET", 404, 7);
115 const points = h.points();
116 expect(points.map((p) => p.labels)).toEqual([
117 { route: "/:owner", method: "GET", code: "4xx" },
118 { route: "/healthz", method: "GET", code: "2xx" },
119 ]);
120 expect(points[1]!.counts[0]).toBe(1);
121 expect(points[1]!.counts.at(-1)).toBe(1);
122 expect(points[1]!.sum).toBeCloseTo(3.0005, 6);
123 });
124 });
125
126 describe("GET /metrics", () => {
127 const SCRAPE = "scrape-token-for-the-test-only";
128 let dataDir: string;
129 let app: App;
130 let servers: Servers;
131 let alice: User;
132 let muse: User;
133 let repoId: string;
134 let tokens: Record<string, string>;
135
136 const scrape = (auth: string | undefined, accept = "application/openmetrics-text; version=1.0.0") =>
137 fetch(`${servers.url}/metrics`, {
138 headers: { accept, ...(auth === undefined ? {} : { authorization: `Bearer ${auth}` }) },
139 });
140 const families = async () => {
141 const res = await scrape(SCRAPE);
142 expect(res.status).toBe(200);
143 return parseOpenMetrics(await res.text());
144 };
145
146 beforeAll(async () => {
147 dataDir = await mkdtemp(join(tmpdir(), "forge-metrics-"));
148 app = createApp({ dataDir, port: 0, metricsToken: SCRAPE });
149 servers = await serve(app);
150 const mk = async (username: string, adminIfFirst = false) => {
151 const u = await createUser(app.db, {
152 origin: "seed",
153 trusted: true,
154 username,
155 email: `${username}@forge.local`,
156 password: "a-good-passphrase",
157 adminIfFirst,
158 });
159 if (!u.ok) throw new Error(u.error);
160 return u.value;
161 };
162 alice = await mk("alice", true);
163 const bob = await mk("bob");
164 const made = await createAgent(app, alice, { username: "muse" });
165 if (!made.ok) throw new Error(String(made.error));
166 muse = made.value.user;
167 const repo = await createRepo(app, alice, { name: "garden", visibility: "private" });
168 if (!repo.ok) throw new Error("repo");
169 repoId = repo.value.id;
170 tokens = {
171 alice: createToken(app.db, alice.id, "t", "ro").token,
172 bob: createToken(app.db, bob.id, "t", "admin").token,
173 muse: createToken(app.db, muse.id, "t", "admin").token,
174 };
175 });
176
177 afterAll(async () => {
178 servers.stop();
179 app.close();
180 await rm(dataDir, { recursive: true, force: true });
181 });
182
183 test("nobody is asked for a bearer, a member and an agent are refused, a wrong token is nobody", async () => {
184 const anon = await scrape(undefined);
185 expect(anon.status).toBe(401);
186 expect(anon.headers.get("www-authenticate")).toBe('Bearer realm="metrics"');
187 expect((await scrape("not-the-scrape-token")).status).toBe(401);
188 expect((await scrape(`${SCRAPE}x`)).status).toBe(401);
189 expect((await scrape(tokens["bob"])).status).toBe(403);
190 expect((await scrape(tokens["muse"])).status).toBe(403);
191 });
192
193 test("an admin's bearer and the scrape token read it, OpenMetrics or Prometheus text, never cached", async () => {
194 const admin = await scrape(tokens["alice"]);
195 expect(admin.status).toBe(200);
196 expect(admin.headers.get("content-type")).toBe("application/openmetrics-text; version=1.0.0; charset=utf-8");
197 expect(admin.headers.get("cache-control")).toBe("no-store");
198 expect(admin.headers.get("x-content-type-options")).toBe("nosniff");
199 parseOpenMetrics(await admin.text());
200 const plain = await scrape(SCRAPE, "text/plain");
201 expect(plain.headers.get("content-type")).toBe("text/plain; version=0.0.4; charset=utf-8");
202 expect(await plain.text()).toContain("# TYPE forge_pulls_landed_total counter");
203 });
204
205 test("a forge running apps says every environment state, production and preview, from its runtime", async () => {
206 expect(valueOf(await families(), "forge_app_environments", { env: "production", state: "asleep" })).toBeUndefined();
207 const runtime = new AppsRuntime(app, { domain: "apps.test", scheme: "http", forgeUrl: servers.url });
208 const now = await families();
209 expect(now.get("forge_app_environments")!.samples).toHaveLength(10);
210 expect(valueOf(now, "forge_app_environments", { env: "preview", state: "running" })).toBe(0);
211 expect(runtime.states()).toEqual([]);
212 await runtime.stop();
213 });
214
215 test("every family is in docs/METRICS.md, and every family it names is scraped", async () => {
216 const doc = readFileSync(join(import.meta.dir, "../docs/METRICS.md"), "utf8");
217 const documented = new Set([...doc.matchAll(/^\| `(forge_[a-z_]+)`/gm)].map((m) => m[1]!));
218 const scraped = forgeFamilies(app).map((f) => f.name);
219 expect([...documented].sort()).toEqual([...scraped].sort());
220 });
221
222 test("a landed pull, a finished check, a red main, a crew run and its spend, a release, a sample and a request each move their series", async () => {
223 const before = await families();
224 const repo = { repo: "alice/garden" };
225 expect(valueOf(before, "forge_pulls_landed_total", repo)).toBeUndefined();
226 expect(valueOf(before, "forge_releases_total", { outcome: "ok" })).toBe(0);
227 expect(valueOf(before, "forge_runs", { kind: "check", state: "queued" })).toBe(0);
228
229 app.db
230 .query("INSERT INTO issue (id, repo_id, number, kind, title, author_id) VALUES ('P1', ?1, 1, 'pull', 'p', ?2)")
231 .run(repoId, alice.id);
232 app.db
233 .query(
234 "INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) VALUES ('P1', 'main', 'f', 'a', 'b', ?1)",
235 )
236 .run(new Date().toISOString());
237
238 const queued = createRun(app.db, { repoId, kind: "check", env: "main", commitOid: "c".repeat(40), reason: "push" });
239 const mid = await families();
240 expect(valueOf(mid, "forge_pulls_landed_total", repo)).toBe(1);
241 expect(valueOf(mid, "forge_runs", { kind: "check", state: "queued" })).toBe(1);
242 claimRun(app.db, queued.id);
243 finishRun(app.db, queued.id, { state: "failed", summary: "check failed: 1 test failed" });
244
245 const agentRun = createRun(app.db, { repoId, kind: "agent", actorId: muse.id, reason: "assigned" });
246 claimRun(app.db, agentRun.id);
247 finishRun(app.db, agentRun.id, { state: "ok", summary: "done" });
248 recordUsage(app.db, {
249 runId: agentRun.id,
250 repoId,
251 issueId: null,
252 agentId: muse.id,
253 subscriptionId: null,
254 tokensIn: 1200,
255 tokensOut: 300,
256 costUsd: 0.75,
257 wallMs: 1000,
258 outcome: "ok",
259 at: new Date().toISOString(),
260 });
261 recordRelease(app.db, { sha: "d".repeat(40), repoId, pullNumber: 1, ok: true, line: "landed" });
262 app.db
263 .query(
264 "INSERT INTO machine_sample (at, step, target, cpu_cores, memory_bytes) VALUES (?1, 15, 'check:R1', 1.5, 1048576)",
265 )
266 .run(new Date().toISOString());
267 expect((await fetch(`${servers.url}/healthz`)).status).toBe(200);
268
269 const after = await families();
270 expect(valueOf(after, "forge_check_duration_seconds_count", { outcome: "failed" })).toBe(1);
271 expect(valueOf(after, "forge_runs", { kind: "check", state: "queued" })).toBe(0);
272 expect(valueOf(after, "forge_main_red", repo)).toBe(1);
273 expect(valueOf(after, "forge_crew_runs_total", { member: "muse", outcome: "ok" })).toBe(1);
274 expect(valueOf(after, "forge_crew_spend_usd_total", { member: "muse" })).toBe(0.75);
275 expect(valueOf(after, "forge_crew_tokens_total", { member: "muse", direction: "in" })).toBe(1200);
276 expect(valueOf(after, "forge_releases_total", { outcome: "ok" })).toBe(1);
277 expect(valueOf(after, "forge_cpu_cores", { target: "check:R1" })).toBe(1.5);
278 expect(valueOf(after, "forge_memory_bytes", { target: "check:R1" })).toBe(1048576);
279 expect(valueOf(after, "forge_http_request_duration_seconds_count", { route: "/healthz", code: "2xx" })).toBe(1);
280 expect(
281 valueOf(after, "forge_http_request_duration_seconds_count", { route: "/metrics", code: "2xx" }),
282 ).toBeGreaterThanOrEqual(3);
283
284 // Red time keeps counting while main stays red, and stops when a green check finishes.
285 const red = (at: Date): number => {
286 const family = forgeFamilies(app, at).find((f) => f.name === "forge_main_red_seconds");
287 if (family?.type !== "counter") throw new Error("forge_main_red_seconds is a counter");
288 return family.points.find((p) => p.labels["repo"] === "alice/garden")!.value;
289 };
290 const hourOn = new Date(Date.now() + 3_600_000);
291 expect(red(hourOn)).toBeGreaterThan(3590);
292 const green = createRun(app.db, { repoId, kind: "check", env: "main", commitOid: "e".repeat(40), reason: "push" });
293 claimRun(app.db, green.id);
294 finishRun(app.db, green.id, { state: "ok", summary: "check passed" });
295 const stopped = red(hourOn);
296 expect(stopped).toBeLessThan(60);
297 expect(red(new Date(Date.now() + 7_200_000))).toBe(stopped);
298 expect(valueOf(await families(), "forge_main_red", repo)).toBe(0);
299 });
300 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs