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

Every answered request is counted by route pattern, surface and viewer role into a usage table #1654

Closed opened this
Closed without merging

scout/forge:scout/1564-every-answered-request-is-counted-by-rou → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +300 −6
scripts/gate.ts +1
@@ -26,6 +26,7 @@ export type Exclusion = {
2626
2727 export const GATE: readonly string[] = [
2828 "test/accounts.test.ts",
29 "test/usage-count.test.ts",
2930 "test/agents.test.ts",
3031 "test/app-domains.test.ts",
3132 "test/app.test.ts",
src/core/schema.ts +16
@@ -1639,6 +1639,22 @@ export const migrations: readonly string[] = [
16391639 ALTER TABLE run ADD COLUMN variant_group TEXT;
16401640 CREATE INDEX pull_variant_group ON pull(variant_group) WHERE variant_group IS NOT NULL;
16411641 `,
1642 // 79 — what is asked of the forge (#1564, `core/usage_count.ts`): one
1643 // counted row per hour, route pattern, method, status class, viewer role
1644 // and surface. Never a path, an id or a person.
1645 `
1646 CREATE TABLE request_count (
1647 hour TEXT NOT NULL,
1648 route TEXT NOT NULL,
1649 method TEXT NOT NULL,
1650 status_class TEXT NOT NULL,
1651 role TEXT NOT NULL,
1652 surface TEXT NOT NULL,
1653 n INTEGER NOT NULL CHECK (n >= 0),
1654 PRIMARY KEY (hour, route, method, status_class, role, surface)
1655 ) WITHOUT ROWID;
1656
1657 `,
16421658 ];
16431659
16441660 /**
src/core/usage_count.ts added +160
@@ -0,0 +1,160 @@
1 /**
2 * Usage count — what is asked of the forge, counted: one row per hour,
3 * route pattern, method, status class, viewer role and surface. The pattern
4 * is the route's (`/:owner/:name/issues/:n`), never the raw path, so the
5 * table's size is the size of the route table and it holds no id, name or
6 * person. (`usage.ts` is the other ledger: what agent runs spent.)
7 *
8 * Counts gather in memory and are written in one transaction a moment
9 * later, so the common request pays a map update and no database write.
10 * A crash loses at most that moment of counts; they are a gauge, not truth.
11 */
12
13 import type { Database } from "bun:sqlite";
14 import { canAdmin, canWrite, getRepo } from "./repos.ts";
15 import type { User } from "./users.ts";
16
17 export type Role = "stranger" | "reader" | "writer" | "owner" | "admin" | "agent";
18 export type Surface = "page" | "fragment" | "api" | "mcp" | "ssh";
19
20 export interface Seen {
21 readonly route: string;
22 readonly method: string;
23 readonly status: number;
24 readonly role: Role;
25 readonly surface: Surface;
26 }
27
28 export interface CountRow {
29 readonly hour: string;
30 readonly route: string;
31 readonly method: string;
32 readonly statusClass: string;
33 readonly role: Role;
34 readonly surface: Surface;
35 readonly n: number;
36 }
37
38 const METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]);
39 /** Counts wait this long before they are written. */
40 const FLUSH_MS = 2_000;
41 /** And no more than this many distinct keys wait at all. */
42 const FLUSH_KEYS = 500;
43
44 const SEP = "\u0000";
45
46 export class UsageCounter {
47 private pending = new Map<string, number>();
48 private timer: ReturnType<typeof setTimeout> | undefined;
49
50 constructor(
51 private readonly db: Database,
52 private readonly now: () => Date = () => new Date(),
53 ) {}
54
55 /** Count one answered request. Never throws, never touches the database. */
56 note(seen: Seen): void {
57 const hour = this.now().toISOString().slice(0, 13) + ":00:00Z";
58 const method = METHODS.has(seen.method) ? seen.method : "OTHER";
59 const statusClass = `${Math.floor(seen.status / 100)}xx`;
60 const key = [hour, seen.route, method, statusClass, seen.role, seen.surface].join(SEP);
61 this.pending.set(key, (this.pending.get(key) ?? 0) + 1);
62 if (this.pending.size >= FLUSH_KEYS) this.flush();
63 else if (this.timer === undefined) {
64 this.timer = setTimeout(() => this.flush(), FLUSH_MS);
65 this.timer.unref();
66 }
67 }
68
69 /** Write what has gathered. A closed or busy database drops it, quietly. */
70 flush(): void {
71 if (this.timer !== undefined) clearTimeout(this.timer);
72 this.timer = undefined;
73 const batch = this.pending;
74 this.pending = new Map();
75 if (batch.size === 0) return;
76 try {
77 const upsert = this.db.query(
78 `INSERT INTO request_count (hour, route, method, status_class, role, surface, n)
79 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
80 ON CONFLICT (hour, route, method, status_class, role, surface)
81 DO UPDATE SET n = n + excluded.n`,
82 );
83 this.db.transaction(() => {
84 for (const [key, n] of batch) {
85 const [hour, route, method, statusClass, role, surface] = key.split(SEP);
86 upsert.run(hour!, route!, method!, statusClass!, role!, surface!, n);
87 }
88 })();
89 } catch {
90 // A gauge: losing a moment of it must never fail a request.
91 }
92 }
93 }
94
95 /** The counted rows, newest hour first. */
96 export function listCounts(db: Database): CountRow[] {
97 return db
98 .query<
99 {
100 hour: string;
101 route: string;
102 method: string;
103 status_class: string;
104 role: Role;
105 surface: Surface;
106 n: number;
107 },
108 []
109 >(`SELECT * FROM request_count ORDER BY hour DESC, route, method, status_class, role, surface`)
110 .all()
111 .map((r) => ({
112 hour: r.hour,
113 route: r.route,
114 method: r.method,
115 statusClass: r.status_class,
116 role: r.role,
117 surface: r.surface,
118 n: r.n,
119 }));
120 }
121
122 /**
123 * Who is asking, in the six words the table keeps. On a repository's own
124 * routes (`:owner/:name`) the role is what they may do there; elsewhere a
125 * signed-in person is a reader. Admin and agent are what the account is.
126 */
127 export function viewerRole(
128 db: Database,
129 user: User | undefined,
130 params: Readonly<Record<string, string>>,
131 ): Role {
132 if (user === undefined) return "stranger";
133 if (user.kind === "agent") return "agent";
134 if (user.isAdmin) return "admin";
135 const { owner, name } = params;
136 if (owner === undefined || name === undefined) return "reader";
137 const repo = getRepo(db, owner, name);
138 if (repo === undefined) return "reader";
139 if (canAdmin(db, repo, user)) return "owner";
140 return canWrite(db, repo, user) ? "writer" : "reader";
141 }
142
143 /** Which door a request came through. */
144 export function surfaceOf(pathname: string, search: URLSearchParams): Surface {
145 if (pathname === "/mcp" || pathname.startsWith("/mcp/")) return "mcp";
146 if (pathname === "/api" || pathname.startsWith("/api/")) return "api";
147 return search.has("fragment") ? "fragment" : "page";
148 }
149
150 const counters = new WeakMap<Database, UsageCounter>();
151
152 /** The one counter a database has. */
153 export function counterFor(db: Database): UsageCounter {
154 let counter = counters.get(db);
155 if (counter === undefined) {
156 counter = new UsageCounter(db);
157 counters.set(db, counter);
158 }
159 return counter;
160 }
src/http/router.ts +6 −3
@@ -16,11 +16,14 @@ type Segment =
1616
1717 export interface Match<H> {
1818 handler: H;
19 /** The pattern string the route was added under, never the raw path. */
20 pattern: string;
1921 params: Params;
2022 }
2123
2224 interface CompiledRoute<H> {
2325 method: string;
26 pattern: string;
2427 segments: Segment[];
2528 handler: H;
2629 }
@@ -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, pattern, segments: compile(pattern), handler });
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, pattern: route.pattern, params };
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, pattern: route.pattern, params };
103106 }
104107 return undefined;
105108 }
src/http/server.ts +28 −3
@@ -370,6 +370,13 @@ import { targetForShortCode } from "../origins/oauth.ts";
370370 import { apiRoutes } from "./api.ts";
371371 import { feedRoutes } from "./feed.ts";
372372 import { mcpRoutes } from "./mcp.ts";
373 import {
374 counterFor,
375 surfaceOf,
376 viewerRole,
377 type Role,
378 type Seen,
379 } from "../core/usage_count.ts";
373380 import { oauthRoutes } from "./oauth.ts";
374381 import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts";
375382 import { parseCidrs } from "../kernel/cidr.ts";
@@ -1784,6 +1791,7 @@ export async function serve(app: App): Promise<Servers> {
17841791 stop() {
17851792 endOpen();
17861793 clearInterval(sweep);
1794 counterFor(app.db).flush();
17871795 for (const http of childHttps.values()) http.close();
17881796 childHttps.clear();
17891797 closeHostedChildren(app);
@@ -1813,7 +1821,16 @@ async function answer(
18131821 limiter: RateLimiter,
18141822 request: Request,
18151823 ): Promise<Response> {
1816 const response = await answerGet(app, router, apiRouter, limiter, request);
1824 const seen: Pick<Seen, "route" | "role"> = { route: "(no route)", role: "stranger" };
1825 const response = await answerGet(app, router, apiRouter, limiter, request, seen);
1826 // The one place an answered request is counted (`core/usage_count.ts`).
1827 const url = new URL(request.url);
1828 counterFor(app.db).note({
1829 ...seen,
1830 method: request.method,
1831 status: response.status,
1832 surface: surfaceOf(url.pathname, url.searchParams),
1833 });
18171834 return request.method === "HEAD"
18181835 ? new Response(null, { status: response.status, headers: response.headers })
18191836 : response;
@@ -1825,11 +1842,17 @@ async function answerGet(
18251842 apiRouter: Router<Handler>,
18261843 limiter: RateLimiter,
18271844 request: Request,
1845 seen: { route: string; role: Role },
18281846 ): Promise<Response> {
18291847 const url = publicUrl(request, app.config.url);
1830 if (url.pathname === "/healthz")
1848 if (url.pathname === "/healthz") {
1849 seen.route = "/healthz";
18311850 return liveResponse(() => app.db.query("select 1").get(), app.log);
1832 if (url.pathname === "/readyz") return readyResponse();
1851 }
1852 if (url.pathname === "/readyz") {
1853 seen.route = "/readyz";
1854 return readyResponse();
1855 }
18331856 const routeMethod = request.method === "HEAD" ? "GET" : request.method;
18341857 // The one place a path decides its own shape of miss: anything under
18351858 // `/api` matches only against the API's own routes, so a studio route as
@@ -1863,7 +1886,9 @@ async function answerGet(
18631886 }
18641887 return noRoute(request.method, url.pathname);
18651888 }
1889 seen.route = matched.pattern;
18661890 const auth = await resolveAuth(app, request);
1891 seen.role = viewerRole(app.db, auth.user, matched.params);
18671892 // From here a body's cap depends on who is asking (`http/limits.ts`), and
18681893 // a stream this request opens is the account's, to end with it.
18691894 if (auth.user !== undefined) {
test/usage-count.test.ts added +89
@@ -0,0 +1,89 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { createAgent } from "../src/actions/crew.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { createIssue } from "../src/core/issues.ts";
9 import { createToken } from "../src/core/tokens.ts";
10 import { createUser, getUserByName } from "../src/core/users.ts";
11 import { counterFor, listCounts } from "../src/core/usage_count.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13
14 describe("every answered request is counted by route pattern, surface and role", () => {
15 let dataDir: string;
16 let app: App;
17 let servers: Servers;
18 let agentToken = "";
19
20 beforeAll(async () => {
21 dataDir = await mkdtemp(join(tmpdir(), "forge-usage-count-"));
22 app = createApp({ dataDir, port: 0 });
23 servers = await serve(app);
24 const alice = await createUser(app.db, {
25 username: "alice",
26 email: "[email protected]",
27 password: "usage-count-pass",
28 adminIfFirst: true,
29 trusted: true,
30 });
31 if (!alice.ok) throw new Error("user");
32 const made = await createRepo(app, alice.value, { name: "yard", visibility: "public" });
33 if (!made.ok) throw new Error("repo");
34 for (const title of ["one", "two", "three"])
35 createIssue(app.db, { repoId: made.value.id, authorId: alice.value.id, title });
36 const bot = await createAgent(app, alice.value, { username: "yardbot" });
37 if (!bot.ok) throw new Error("agent");
38 const user = getUserByName(app.db, "yardbot");
39 agentToken = createToken(app.db, user!.id, "run", "rw").token;
40 }, 30_000);
41
42 afterAll(async () => {
43 servers.stop();
44 app.close();
45 await rm(dataDir, { recursive: true, force: true });
46 });
47
48 test("three issues with different numbers land on one route pattern", async () => {
49 for (const n of [1, 2, 3]) {
50 const res = await fetch(`${servers.url}/alice/yard/issues/${n}`);
51 expect(res.status).toBe(200);
52 // the floor stays on the counted response
53 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
54 await res.text();
55 }
56 counterFor(app.db).flush();
57 const rows = listCounts(app.db).filter((r) => r.route.includes("issues/:number"));
58 expect(rows).toHaveLength(1);
59 expect(rows[0]).toMatchObject({
60 route: "/:owner/:name/issues/:number",
61 method: "GET",
62 statusClass: "2xx",
63 role: "stranger",
64 surface: "page",
65 n: 3,
66 });
67 expect(listCounts(app.db).some((r) => /\/alice\//.test(r.route))).toBe(false);
68 });
69
70 test("an agent's API call is counted as agent/api", async () => {
71 const res = await fetch(`${servers.url}/api/v1/repos/alice/yard`, {
72 headers: { authorization: `Bearer ${agentToken}` },
73 });
74 expect(res.status).toBe(200);
75 await res.text();
76 counterFor(app.db).flush();
77 const rows = listCounts(app.db).filter((r) => r.role === "agent");
78 expect(rows).toHaveLength(1);
79 expect(rows[0]).toMatchObject({ surface: "api", statusClass: "2xx", n: 1 });
80 expect(rows[0]!.route.startsWith("/api/")).toBe(true);
81 });
82
83 test("a path under no route is one row, never its raw path", async () => {
84 for (const p of ["/nope/a/b/c/d", "/zzz/y/x/w/v"]) await (await fetch(`${servers.url}${p}`)).text();
85 counterFor(app.db).flush();
86 const rows = listCounts(app.db).filter((r) => r.statusClass === "4xx");
87 expect(rows.map((r) => r.route)).not.toContain("/nope/a/b/c/d");
88 });
89 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs