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

Every answered request is counted by route pattern, surface and viewer role #1873

Parked opened this
Closed without merging

scout/forge:scout/1808-every-answered-request-is-counted-by-rou → main 6 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +348 −4
scripts/gate.ts +1
@@ -28,6 +28,7 @@ export type Exclusion = {
2828
2929 export const GATE: readonly string[] = [
3030 "test/accounts-retire.test.ts",
31 "test/usage-count.test.ts",
3132 "test/cloud-use.test.ts",
3233 "test/accounts.test.ts",
3334 "test/asks-mute.test.ts",
src/core/schema.ts +15
@@ -1810,6 +1810,21 @@ export const migrations: readonly string[] = [
18101810 ALTER TABLE run ADD COLUMN placement TEXT NOT NULL DEFAULT '';
18111811 ALTER TABLE run ADD COLUMN node TEXT NOT NULL DEFAULT '';
18121812 `,
1813 // 92 — every answered request counted by hour, route pattern, method,
1814 // status class, viewer role and surface (#1808, core/usage_count.ts).
1815 // Telemetry, not state: a lost batch is a gap in a chart.
1816 `
1817 CREATE TABLE usage_count (
1818 hour TEXT NOT NULL,
1819 route TEXT NOT NULL,
1820 method TEXT NOT NULL,
1821 status_class TEXT NOT NULL,
1822 role TEXT NOT NULL CHECK (role IN ('anon', 'user', 'admin', 'agent')),
1823 surface TEXT NOT NULL CHECK (surface IN ('api', 'mcp', 'web')),
1824 n INTEGER NOT NULL,
1825 PRIMARY KEY (hour, route, method, status_class, role, surface)
1826 ) WITHOUT ROWID;
1827 `,
18131828 ];
18141829
18151830 /**
src/core/usage_count.ts added +172
@@ -0,0 +1,172 @@
1 /**
2 * Usage count — how many requests the forge answered, by hour, route
3 * pattern, method, status class, viewer role and surface. The pattern is the
4 * router's (`/:owner/:name`), never the path, so three ids on one route are
5 * one row and the table cannot outgrow the route table.
6 *
7 * A request pays for one map increment. The counts wait in memory and are
8 * written in one transaction a second later (or at 500 distinct keys), so
9 * the common request adds no query. A lost batch is a gap in a chart, not a
10 * lost fact: this is telemetry, and nothing here ever throws into a request.
11 *
12 * Roles: `anon`, `user`, `admin`, `agent`. Surfaces: `api` (under /api/),
13 * `mcp`, `web` (everything else). A path no route claims is noted `anon`
14 * whoever asked: it is not resolved to a viewer, by design (no session read
15 * on a miss). Old hours are pruned (90 days) when the hour turns.
16 * `usage_count` is not the run ledger in `usage.ts`; that one is what
17 * agents spent.
18 */
19
20 import type { Database } from "bun:sqlite";
21
22 export type UsageRole = "anon" | "user" | "admin" | "agent";
23 export type UsageSurface = "api" | "mcp" | "web";
24
25 export interface RouteNote {
26 readonly pattern: string;
27 readonly role: UsageRole;
28 readonly surface: UsageSurface;
29 }
30
31 export interface UsageRow {
32 readonly hour: string;
33 readonly route: string;
34 readonly method: string;
35 readonly statusClass: string;
36 readonly role: UsageRole;
37 readonly surface: UsageSurface;
38 readonly n: number;
39 }
40
41 /** Route used for a path no route claims. */
42 export const UNMATCHED = "(unmatched)";
43 const FLUSH_MS = 1000;
44 const FLUSH_KEYS = 500;
45 const KEEP_DAYS = 90;
46 const METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]);
47
48 export const roleOf = (
49 user: { kind: string; isAdmin: boolean } | undefined,
50 ): UsageRole =>
51 user === undefined
52 ? "anon"
53 : user.kind === "agent"
54 ? "agent"
55 : user.isAdmin
56 ? "admin"
57 : "user";
58
59 export const surfaceOf = (pathname: string): UsageSurface =>
60 pathname === "/api" || pathname.startsWith("/api/")
61 ? "api"
62 : pathname === "/mcp" || pathname.startsWith("/mcp/")
63 ? "mcp"
64 : "web";
65
66 const notes = new WeakMap<Request, RouteNote>();
67
68 /** The router and auth say what a request was; `countAnswer` reads it. */
69 export function noteRoute(request: Request, note: RouteNote): void {
70 notes.set(request, note);
71 }
72
73 const waiting = new Map<Database, Map<string, number>>();
74 const sweptHour = new WeakMap<Database, string>();
75 let timer: ReturnType<typeof setTimeout> | undefined;
76
77 const hourOf = (at: Date): string => at.toISOString().slice(0, 13);
78
79 /** Count one answered request. A request nobody noted (a probe) is not counted. */
80 export function countAnswer(
81 db: Database,
82 request: Request,
83 status: number,
84 at: Date = new Date(),
85 ): void {
86 try {
87 const note = notes.get(request);
88 if (note === undefined) return;
89 const method = METHODS.has(request.method) ? request.method : "OTHER";
90 const key = JSON.stringify([
91 hourOf(at),
92 note.pattern,
93 method,
94 `${Math.floor(status / 100)}xx`,
95 note.role,
96 note.surface,
97 ]);
98 let counts = waiting.get(db);
99 if (counts === undefined) waiting.set(db, (counts = new Map()));
100 counts.set(key, (counts.get(key) ?? 0) + 1);
101 if (counts.size >= FLUSH_KEYS) flushUsage(db);
102 else if (timer === undefined) {
103 timer = setTimeout(flushAllUsage, FLUSH_MS);
104 timer.unref();
105 }
106 } catch {
107 // telemetry; the request is the work
108 }
109 }
110
111 /** Write what waits for one database, in one transaction. Never throws. */
112 export function flushUsage(db: Database, at: Date = new Date()): void {
113 const counts = waiting.get(db);
114 waiting.delete(db);
115 if (counts === undefined) return;
116 try {
117 const put = db.query(
118 `INSERT INTO usage_count (hour, route, method, status_class, role, surface, n)
119 VALUES (?, ?, ?, ?, ?, ?, ?)
120 ON CONFLICT (hour, route, method, status_class, role, surface)
121 DO UPDATE SET n = n + excluded.n`,
122 );
123 db.transaction(() => {
124 for (const [key, n] of counts) {
125 const [hour, route, method, cls, role, surface] = JSON.parse(key) as string[];
outdated

This prunes once per process lifetime. A long-lived forge keeps every hour forever. Sweep when hourOf(at) changes from the last sweep instead.

126 put.run(hour!, route!, method!, cls!, role!, surface!, n);
127 }
128 if (sweptHour.get(db) !== hourOf(at)) {
129 sweptHour.set(db, hourOf(at));
130 const cutoff = new Date(at.getTime() - KEEP_DAYS * 86_400_000);
131 db.query("DELETE FROM usage_count WHERE hour < ?").run(hourOf(cutoff));
132 }
133 })();
134 } catch {
135 // a closed database or a lost batch is a gap in a chart
136 }
137 }
138
139 /** Flush every database that waits. */
140 export function flushAllUsage(): void {
141 clearTimeout(timer);
142 timer = undefined;
143 for (const db of [...waiting.keys()]) flushUsage(db);
144 }
145
146 /** The counts for a database, pending ones included, busiest first. */
147 export function readUsage(db: Database): UsageRow[] {
148 flushUsage(db);
149 return db
150 .query<
151 {
152 hour: string;
153 route: string;
154 method: string;
155 status_class: string;
156 role: UsageRole;
157 surface: UsageSurface;
158 n: number;
159 },
160 []
161 >("SELECT * FROM usage_count ORDER BY n DESC, hour, route, method")
162 .all()
163 .map((r) => ({
164 hour: r.hour,
165 route: r.route,
166 method: r.method,
167 statusClass: r.status_class,
168 role: r.role,
169 surface: r.surface,
170 n: r.n,
171 }));
172 }
src/http/router.ts +6 −3
@@ -17,12 +17,15 @@ type Segment =
1717 export interface Match<H> {
1818 handler: H;
1919 params: Params;
20 /** The pattern the route was added with: what a count is keyed by. */
21 pattern: string;
2022 }
2123
2224 interface CompiledRoute<H> {
2325 method: string;
2426 segments: Segment[];
2527 handler: H;
28 pattern: string;
2629 }
2730
2831 function compile(pattern: string): Segment[] {
@@ -66,7 +69,7 @@ export class Router<H> {
6669 }
6770
6871 add(method: string, pattern: string, handler: H): this {
69 this.routes.push({ method, segments: compile(pattern), handler });
72 this.routes.push({ method, segments: compile(pattern), handler, pattern });
7073 return this;
7174 }
7275
@@ -80,7 +83,7 @@ export class Router<H> {
8083 const decoded = parts.slice(i).map(decodeSegment);
8184 if (decoded.some((d) => d === undefined)) continue outer;
8285 params[segment.name] = decoded.join("/");
83 return { handler: route.handler, params };
86 return { handler: route.handler, params, pattern: route.pattern };
8487 }
8588 const part = parts[i];
8689 if (part === undefined) continue outer;
@@ -99,7 +102,7 @@ export class Router<H> {
99102 }
100103 }
101104 if (parts.length !== route.segments.length) continue;
102 return { handler: route.handler, params };
105 return { handler: route.handler, params, pattern: route.pattern };
103106 }
104107 return undefined;
105108 }
src/http/server.ts +30 −1
@@ -397,6 +397,14 @@ import { feedRoutes } from "./feed.ts";
397397 import { mcpRoutes } from "./mcp.ts";
398398 import { oauthRoutes } from "./oauth.ts";
399399 import { flushAccess, recordAccess } from "./access_log.ts";
400 import {
401 UNMATCHED,
402 countAnswer,
403 flushAllUsage,
404 noteRoute,
405 roleOf,
406 surfaceOf,
407 } from "../core/usage_count.ts";
400408 import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts";
401409 import { parseCidrs } from "../kernel/cidr.ts";
402410 import {
@@ -1885,6 +1893,7 @@ export async function serve(app: App): Promise<Servers> {
18851893 childHttps.clear();
18861894 closeHostedChildren(app);
18871895 flushAccess();
1896 flushAllUsage();
18881897 web.stop(true);
18891898 internal.stop(true);
18901899 // Our socket goes with us; a corpse is only ever an unclean exit's.
@@ -1911,7 +1920,17 @@ async function answer(
19111920 limiter: RateLimiter,
19121921 request: Request,
19131922 ): Promise<Response> {
1914 const response = await answerGet(app, router, apiRouter, limiter, request);
1923 // The one place an answered request is counted (`core/usage_count.ts`).
1924 // A handler that throws is answered 500 by `error()` below, so it is
1925 // counted as the 500 it will become, then rethrown for that to answer.
outdated

A throw from answerGet never reaches this line: Bun's error() answers 500/403 and nothing is counted. Count inside a try/catch here (status 500 on a throw, then rethrow) and test it.

1926 let response: Response;
1927 try {
1928 response = await answerGet(app, router, apiRouter, limiter, request);
1929 } catch (error) {
1930 countAnswer(app.db, request, 500);
1931 throw error;
1932 }
1933 countAnswer(app.db, request, response.status);
19151934 return request.method === "HEAD"
19161935 ? new Response(null, { status: response.status, headers: response.headers })
19171936 : response;
@@ -1938,6 +1957,11 @@ async function answerGet(
19381957 ? apiRouter.match(routeMethod, url.pathname)
19391958 : router.match(routeMethod, url.pathname);
19401959 if (!matched) {
1960 noteRoute(request, {
1961 pattern: UNMATCHED,
1962 role: "anon",
1963 surface: surfaceOf(url.pathname),
1964 });
19411965 // A path under no route at all is what a mistyped or stale studio
19421966 // URL lands on. A browser gets the forge's own page for it, same as
19431967 // any other 404; an API client — anything under `/api/` — keeps the
@@ -1962,6 +1986,11 @@ async function answerGet(
19621986 return noRoute(request.method, url.pathname);
19631987 }
19641988 const auth = await resolveAuth(app, request);
1989 noteRoute(request, {
1990 pattern: matched.pattern,
1991 role: roleOf(auth.user),
1992 surface: surfaceOf(url.pathname),
1993 });
19651994 // From here a body's cap depends on who is asking (`http/limits.ts`), and
19661995 // a stream this request opens is the account's, to end with it.
19671996 if (auth.user !== undefined) {
test/usage-count.test.ts added +124
@@ -0,0 +1,124 @@
1 /**
2 * Every answered request is counted (#1808) by hour, route pattern, method,
3 * status class, viewer role and surface — batched, one write for many
4 * requests, and never per path.
5 */
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 { createApp, type App } from "../src/app.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { readUsage, countAnswer, noteRoute, flushUsage } from "../src/core/usage_count.ts";
15 import { forgeHttp } from "../src/http/server.ts";
16
17 describe("usage count", () => {
18 let dataDir: string;
19 let app: App;
20 let http: ReturnType<typeof forgeHttp>;
21 let agentToken: string;
22
23 const get = (path: string, token?: string) =>
24 http.handle(
25 new Request(`http://localhost${path}`, {
26 headers: token === undefined ? {} : { authorization: `Bearer ${token}` },
27 }),
28 );
29 const rows = (route: string) => readUsage(app.db).filter((r) => r.route === route);
30 const total = (route: string) => rows(route).reduce((n, r) => n + r.n, 0);
31
32 beforeAll(async () => {
33 dataDir = await mkdtemp(join(tmpdir(), "forge-usage-"));
34 app = createApp({ dataDir, port: 0 });
35 http = forgeHttp(app);
36 const agent = await createUser(app.db, {
37 trusted: true,
38 username: "robot",
39 email: "[email protected]",
40 agent: true,
41 });
42 if (!agent.ok) throw new Error("agent");
43 agentToken = createToken(app.db, agent.value.id, "t", "ro").token;
44 });
45
46 afterAll(async () => {
47 app.close();
48 await rm(dataDir, { recursive: true, force: true });
49 });
50
51 test("three ids on one route land on one pattern", async () => {
52 for (const name of ["one", "two", "three"]) await get(`/api/v1/users/${name}`);
53 const found = rows("/api/v1/users/:username");
54 expect(found).toHaveLength(1);
55 expect(found[0]).toMatchObject({
56 method: "GET",
57 statusClass: "4xx",
58 role: "anon",
59 surface: "api",
60 n: 3,
61 });
62 expect(readUsage(app.db).some((r) => r.route.includes("three"))).toBe(false);
63 });
64
65 test("an agent's API call is counted as agent/api", async () => {
66 const res = await get("/api/v1/user", agentToken);
67 expect(res.status).toBe(200);
68 const found = rows("/api/v1/user");
69 expect(found).toHaveLength(1);
70 expect(found[0]).toMatchObject({ role: "agent", surface: "api", statusClass: "2xx", n: 1 });
71 });
72
73 test("a path no route claims is one row, and is counted as unmatched", async () => {
74 await get("/api/v1/no-such-thing-1");
75 await get("/api/v1/no-such-thing-2");
76 expect(total("(unmatched)")).toBe(2);
77 });
78
79 test("counting is batched: nothing is written until the flush", () => {
80 const request = new Request("http://localhost/x");
81 noteRoute(request, { pattern: "/batched", role: "user", surface: "web" });
82 const before = app.db.query("SELECT total_changes() AS c").get() as { c: number };
83 for (let i = 0; i < 50; i++) countAnswer(app.db, request, 200);
84 const mid = app.db.query("SELECT total_changes() AS c").get() as { c: number };
85 expect(mid.c).toBe(before.c);
86 flushUsage(app.db);
87 expect(total("/batched")).toBe(50);
88 });
89
90 test("a request nobody noted (a probe) is not counted", async () => {
91 const before = readUsage(app.db).length;
92 await get("/healthz");
93 expect(readUsage(app.db)).toHaveLength(before);
94 });
95
96 test("a handler that throws is counted as one 5xx and still rethrown", async () => {
97 app.db.exec("ALTER TABLE user RENAME TO user_gone");
98 try {
99 const thrown = await get("/api/v1/users/whoever").then(
100 () => false,
101 () => true,
102 );
103 expect(thrown).toBe(true);
104 } finally {
105 app.db.exec("ALTER TABLE user_gone RENAME TO user");
106 }
107 const found = rows("/api/v1/users/:username").filter((r) => r.statusClass === "5xx");
108 expect(found.reduce((n, r) => n + r.n, 0)).toBe(1);
109 });
110
111 test("the 90-day sweep runs again when the hour turns", () => {
112 const old = new Date(Date.now() - 200 * 86_400_000);
113 const request = new Request("http://localhost/old");
114 noteRoute(request, { pattern: "/old", role: "user", surface: "web" });
115 countAnswer(app.db, request, 200, old);
116 flushUsage(app.db, new Date());
117 // this hour was already swept by an earlier flush: the old row stays
118 expect(total("/old")).toBe(1);
119 countAnswer(app.db, request, 200, new Date());
120 flushUsage(app.db, new Date(Date.now() + 3_600_000));
121 expect(rows("/old").every((r) => r.hour >= old.toISOString().slice(0, 13))).toBe(true);
122 expect(rows("/old").some((r) => r.hour === old.toISOString().slice(0, 13))).toBe(false);
123 });
124 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs