Public: anyone can read this; the crew can change it.
Every answered request is counted by route pattern, surface and viewer role #1857
scout/forge:scout/1808-every-answered-request-is-counted-by-rou → main 6 commits fork
6 files
changed +348
−4
scripts/gate.ts +1
| @@ -28,6 +28,7 @@ export type Exclusion = { | ||
| 28 | 28 | |
| 29 | 29 | export const GATE: readonly string[] = [ |
| 30 | 30 | "test/accounts-retire.test.ts", |
| 31 | "test/usage-count.test.ts", | |
| 31 | 32 | "test/cloud-use.test.ts", |
| 32 | 33 | "test/accounts.test.ts", |
| 33 | 34 | "test/asks-mute.test.ts", |
src/core/schema.ts +15
| @@ -1810,6 +1810,21 @@ export const migrations: readonly string[] = [ | ||
| 1810 | 1810 | ALTER TABLE run ADD COLUMN placement TEXT NOT NULL DEFAULT ''; |
| 1811 | 1811 | ALTER TABLE run ADD COLUMN node TEXT NOT NULL DEFAULT ''; |
| 1812 | 1812 | `, |
| 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 | `, | |
| 1813 | 1828 | ]; |
| 1814 | 1829 | |
| 1815 | 1830 | /** |
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[]; | |
| 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 = | ||
| 17 | 17 | export interface Match<H> { |
| 18 | 18 | handler: H; |
| 19 | 19 | params: Params; |
| 20 | /** The pattern the route was added with: what a count is keyed by. */ | |
| 21 | pattern: string; | |
| 20 | 22 | } |
| 21 | 23 | |
| 22 | 24 | interface CompiledRoute<H> { |
| 23 | 25 | method: string; |
| 24 | 26 | segments: Segment[]; |
| 25 | 27 | handler: H; |
| 28 | pattern: string; | |
| 26 | 29 | } |
| 27 | 30 | |
| 28 | 31 | function compile(pattern: string): Segment[] { |
| @@ -66,7 +69,7 @@ export class Router<H> { | ||
| 66 | 69 | } |
| 67 | 70 | |
| 68 | 71 | 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 }); | |
| 70 | 73 | return this; |
| 71 | 74 | } |
| 72 | 75 | |
| @@ -80,7 +83,7 @@ export class Router<H> { | ||
| 80 | 83 | const decoded = parts.slice(i).map(decodeSegment); |
| 81 | 84 | if (decoded.some((d) => d === undefined)) continue outer; |
| 82 | 85 | params[segment.name] = decoded.join("/"); |
| 83 | return { handler: route.handler, params }; | |
| 86 | return { handler: route.handler, params, pattern: route.pattern }; | |
| 84 | 87 | } |
| 85 | 88 | const part = parts[i]; |
| 86 | 89 | if (part === undefined) continue outer; |
| @@ -99,7 +102,7 @@ export class Router<H> { | ||
| 99 | 102 | } |
| 100 | 103 | } |
| 101 | 104 | if (parts.length !== route.segments.length) continue; |
| 102 | return { handler: route.handler, params }; | |
| 105 | return { handler: route.handler, params, pattern: route.pattern }; | |
| 103 | 106 | } |
| 104 | 107 | return undefined; |
| 105 | 108 | } |
src/http/server.ts +30 −1
| @@ -397,6 +397,14 @@ import { feedRoutes } from "./feed.ts"; | ||
| 397 | 397 | import { mcpRoutes } from "./mcp.ts"; |
| 398 | 398 | import { oauthRoutes } from "./oauth.ts"; |
| 399 | 399 | 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"; | |
| 400 | 408 | import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts"; |
| 401 | 409 | import { parseCidrs } from "../kernel/cidr.ts"; |
| 402 | 410 | import { |
| @@ -1885,6 +1893,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1885 | 1893 | childHttps.clear(); |
| 1886 | 1894 | closeHostedChildren(app); |
| 1887 | 1895 | flushAccess(); |
| 1896 | flushAllUsage(); | |
| 1888 | 1897 | web.stop(true); |
| 1889 | 1898 | internal.stop(true); |
| 1890 | 1899 | // Our socket goes with us; a corpse is only ever an unclean exit's. |
| @@ -1911,7 +1920,17 @@ async function answer( | ||
| 1911 | 1920 | limiter: RateLimiter, |
| 1912 | 1921 | request: Request, |
| 1913 | 1922 | ): 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. | |
| 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); | |
| 1915 | 1934 | return request.method === "HEAD" |
| 1916 | 1935 | ? new Response(null, { status: response.status, headers: response.headers }) |
| 1917 | 1936 | : response; |
| @@ -1938,6 +1957,11 @@ async function answerGet( | ||
| 1938 | 1957 | ? apiRouter.match(routeMethod, url.pathname) |
| 1939 | 1958 | : router.match(routeMethod, url.pathname); |
| 1940 | 1959 | if (!matched) { |
| 1960 | noteRoute(request, { | |
| 1961 | pattern: UNMATCHED, | |
| 1962 | role: "anon", | |
| 1963 | surface: surfaceOf(url.pathname), | |
| 1964 | }); | |
| 1941 | 1965 | // A path under no route at all is what a mistyped or stale studio |
| 1942 | 1966 | // URL lands on. A browser gets the forge's own page for it, same as |
| 1943 | 1967 | // any other 404; an API client — anything under `/api/` — keeps the |
| @@ -1962,6 +1986,11 @@ async function answerGet( | ||
| 1962 | 1986 | return noRoute(request.method, url.pathname); |
| 1963 | 1987 | } |
| 1964 | 1988 | const auth = await resolveAuth(app, request); |
| 1989 | noteRoute(request, { | |
| 1990 | pattern: matched.pattern, | |
| 1991 | role: roleOf(auth.user), | |
| 1992 | surface: surfaceOf(url.pathname), | |
| 1993 | }); | |
| 1965 | 1994 | // From here a body's cap depends on who is asking (`http/limits.ts`), and |
| 1966 | 1995 | // a stream this request opens is the account's, to end with it. |
| 1967 | 1996 | 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 | }); |
new above
offline