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

A usage counter batches request counts in memory and writes them to usage_count in one transaction #2003

Parked opened this
Closed without merging

scout/forge:scout/1917-a-usage-counter-batches-request-counts-i → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
16 files changed +723 −2
README.md +2
@@ -580,6 +580,8 @@ Where the whole forge waits is a forge admin's: `/flow` shows each stage from re
580580
581581 The terminal also has an Access command (`:` → Access), a site admin's: it reads the same last-day non-browser requests as Settings → Access and the `access` MCP tool, newest first, and filters them with `s` (since), `u` (user agent) and `p` (path), `c` to clear.
582582
583 Every answered request that matches a route is counted in memory by hour, route pattern (never the path), method, status class, the verified account's role (`anon`, `user`, `admin`, `agent`) and surface (`api`, `mcp`, `web`), and written to `usage_count` about once a second (`core/usage_count.ts`). A site admin reads the counts at Settings → Traffic, with the `traffic` MCP tool (write scope), or with the terminal's Traffic command (`:` → Traffic).
584
583585 `docs/PLANNING.md` is how issues depend on issues: the edge, the map, and
584586 what "ready now" means to a person and to the crew. The map also shows each
585587 pillar's ask-to-live: the median hours from an issue opening to its change live
scripts/gate.ts +3
@@ -252,6 +252,9 @@ export const GATE: readonly string[] = [
252252 "test/branch_tell.test.ts",
253253 "test/tell_from.test.ts",
254254 "test/usage.test.ts",
255 "test/usage-count.test.ts",
256 "test/usage-count-wired.test.ts",
257 "test/tui-traffic.test.ts",
255258 "test/tokens.test.ts",
256259 "test/credentials.test.ts",
257260 "test/standing.test.ts",
src/actions/traffic.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * Request counts per route and hour (`core/usage_count.ts`), read by the
3 * forge's owner: a forge admin only, never an agent, and everyone else is
4 * told `not_found`. The page, the `traffic` MCP tool and the terminal all
5 * read through here.
6 */
7
8 import type { App } from "../app.ts";
9 import { hourOf, readUsage, type UsageRow } from "../core/usage_count.ts";
10 import type { User } from "../core/users.ts";
11 import { err, ok, type Result } from "../kernel/result.ts";
12
13 /** The most rows one read returns, newest hour first. */
14 export const TRAFFIC_ROWS = 500;
15
16 /** The hour a day ago, the default window. */
17 export const dayAgo = (): string => hourOf(new Date(Date.now() - 86_400_000));
18
19 export function listTraffic(
20 app: App,
21 actor: User | undefined,
22 sinceHour: string = dayAgo(),
23 ): Result<UsageRow[], "not_found" | "bad_hour"> {
24 if (actor?.isAdmin !== true || actor.kind === "agent") return err("not_found");
25 if (!/^\d{4}-\d{2}-\d{2}T\d{2}$/.test(sinceHour)) return err("bad_hour");
26 // What is counted but not yet written is part of the answer.
27 app.requests.flush();
28 const rows = readUsage(app.db, sinceHour);
29 return ok(rows.reverse().slice(0, TRAFFIC_ROWS));
30 }
src/app.ts +6
@@ -26,6 +26,7 @@ import {
2626 type Log,
2727 } from "./kernel/log.ts";
2828 import { RefusedLedger } from "./kernel/internal_refused.ts";
29 import { createUsageCounter, type UsageCounter } from "./core/usage_count.ts";
2930 import { closeReadersUnder } from "./git/read.ts";
3031
3132 export interface ForgeConfig {
@@ -190,6 +191,8 @@ export interface App {
190191 readonly hookAddress: { current: string };
191192 /** Per-boot secret every internal request must carry (`FORGE_HOOK_SECRET` in a hook's env). */
192193 readonly hookSecret: string;
194 /** Request counts per route and hour, batched (`core/usage_count.ts`); flushed on `close`. */
195 readonly requests: UsageCounter;
193196 /** What `vitals` turns into needs: this forge's own, not the process's. */
194197 readonly signals: { errors: ErrorLedger; refused: RefusedLedger };
195198 close(): void;
@@ -220,6 +223,7 @@ export function createApp(config: ForgeConfig): App {
220223 // and the forks whose default branch is still a copy of this one's.
221224 follow({ db, reposRoot, bus });
222225
226 const requests = createUsageCounter(db);
223227 const owner = id();
224228 const errors = forgeErrorLedger(owner);
225229 return {
@@ -227,6 +231,7 @@ export function createApp(config: ForgeConfig): App {
227231 db,
228232 bus,
229233 log: createLog("forge", owner),
234 requests,
230235 signals: { errors, refused: new RefusedLedger() },
231236 reposRoot,
232237 // This process's own: two forges share a data directory for the length
@@ -240,6 +245,7 @@ export function createApp(config: ForgeConfig): App {
240245 // otherwise. One data dir is one forge, so closing the forge is where
241246 // that is said.
242247 releaseErrorLedger(errors);
248 requests.stop();
243249 closeReadersUnder(reposRoot);
244250 db.close();
245251 },
src/core/migrations/20261015233000-usage-count.ts added +14
@@ -0,0 +1,14 @@
1 // Request counts, batched in memory and written an hour at a time (#1917,
2 // core/usage_count.ts). Not the spend ledger (`usage`).
3 export default `
4 CREATE TABLE usage_count (
5 hour TEXT NOT NULL,
6 pattern TEXT NOT NULL,
7 method TEXT NOT NULL,
8 status TEXT NOT NULL,
9 role TEXT NOT NULL,
10 surface TEXT NOT NULL,
11 n INTEGER NOT NULL,
12 PRIMARY KEY (hour, pattern, method, status, role, surface)
13 ) WITHOUT ROWID;
14 `;
src/core/usage_count.ts added +171
@@ -0,0 +1,171 @@
1 /**
2 * Usage count — how many requests each route took, per hour. Not the spend
3 * ledger (`usage.ts`). `count` is one in-memory increment and runs no query;
4 * `flush` writes every pending key in one transaction, as an upsert on
5 * (hour, pattern, method, status class, role, surface). The counter flushes
6 * by itself about a second after the first pending count, or soon after 500
7 * keys are pending, and on `stop()`.
8 *
9 * Anything outside the closed sets (role, surface, status class, method) is
10 * refused at the call, so the table cannot grow from request input.
11 */
12
13 import type { Database } from "bun:sqlite";
14
15 export type UsageRole = "anon" | "user" | "admin" | "agent";
16 export type UsageSurface = "api" | "mcp" | "web";
17 export const USAGE_ROLES: readonly UsageRole[] = ["anon", "user", "admin", "agent"];
18 export const USAGE_SURFACES: readonly UsageSurface[] = ["api", "mcp", "web"];
19
20 const METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
21
22 export interface UsageHit {
23 /** The route pattern (`/api/v1/repos/:id`), never the raw path. */
24 readonly pattern: string;
25 readonly method: string;
26 /** The HTTP status code, e.g. 404; kept as its class, `4xx`. */
27 readonly status: number;
28 readonly role: UsageRole;
29 readonly surface: UsageSurface;
30 }
31
32 export interface UsageRow {
33 readonly hour: string;
34 readonly pattern: string;
35 readonly method: string;
36 readonly status: string;
37 readonly role: UsageRole;
38 readonly surface: UsageSurface;
39 readonly n: number;
40 }
41
42 export interface UsageCounter {
43 count(hit: UsageHit): void;
44 flush(): void;
45 stop(): void;
46 }
47
48 export interface UsageCounterOptions {
49 readonly now?: () => Date;
50 readonly flushMs?: number;
51 readonly maxKeys?: number;
52 }
53
54 /** The UTC hour a time falls in, `2026-10-15T14`. */
55 export const hourOf = (d: Date): string => d.toISOString().slice(0, 13);
56
57 const HOUR = /^\d{4}-\d{2}-\d{2}T\d{2}$/;
58 const SEP = "\u0000";
59 /** Flushes a batch may fail before it is dropped. */
60 const MAX_TRIES = 3;
61
62 /** Refuse what is not in the closed sets; return the key's parts. */
63 function check(hit: UsageHit): string[] {
64 const { pattern, method, status, role, surface } = hit;
65 if (typeof pattern !== "string" || pattern === "" || pattern.length > 200 || pattern.includes(SEP)) {
66 throw new Error("usage count: bad pattern");
67 }
68 if (!METHODS.includes(method)) throw new Error("usage count: bad method");
69 if (!Number.isInteger(status) || status < 200 || status > 599) {
70 throw new Error("usage count: bad status");
71 }
72 if (!USAGE_ROLES.includes(role)) throw new Error("usage count: bad role");
73 if (!USAGE_SURFACES.includes(surface)) throw new Error("usage count: bad surface");
74 return [pattern, method, `${Math.floor(status / 100)}xx`, role, surface];
75 }
76
77 export function createUsageCounter(
78 db: Database,
79 opts: UsageCounterOptions = {},
80 ): UsageCounter {
81 const now = opts.now ?? (() => new Date());
82 const flushMs = opts.flushMs ?? 1000;
83 const maxKeys = opts.maxKeys ?? 500;
84 const pending = new Map<string, number>();
85 let timer: ReturnType<typeof setTimeout> | null = null;
86 let soon = false;
87
88 const clear = (): void => {
89 if (timer) clearTimeout(timer);
90 timer = null;
91 };
92
93 const up = db.prepare(
94 `INSERT INTO usage_count (hour, pattern, method, status, role, surface, n)
95 VALUES (?, ?, ?, ?, ?, ?, ?)
96 ON CONFLICT (hour, pattern, method, status, role, surface)
97 DO UPDATE SET n = n + excluded.n`,
98 );
99 let failed = 0;
100
101 function flush(): void {
102 clear();
103 if (pending.size === 0) return;
104 const batch = [...pending];
105 pending.clear();
106 try {
107 db.transaction(() => {
108 for (const [key, n] of batch) up.run(...(key.split(SEP) as [string, string, string, string, string, string]), n);
109 })();
110 failed = 0;
111 } catch (e) {
112 // Keep what was counted for another try, but only so many: a batch
113 // that never goes in is dropped, not carried forever.
114 if (++failed < MAX_TRIES) {
115 for (const [key, n] of batch) pending.set(key, (pending.get(key) ?? 0) + n);
116 } else failed = 0;
117 throw e;
118 }
119 }
120
121 const tick = (): void => {
122 try {
123 flush();
124 } catch {
125 // Counting must never take the server down; a batch that failed is
126 // back in `pending` unless it was dropped, and goes in with the next.
127 if (pending.size > 0 && !timer) {
128 timer = setTimeout(tick, flushMs);
129 timer.unref?.();
130 }
131 }
132 };
133
134 return {
135 count(hit) {
136 const key = [hourOf(now()), ...check(hit)].join(SEP);
137 pending.set(key, (pending.get(key) ?? 0) + 1);
138 if (pending.size >= maxKeys && !soon) {
139 // Not in this call: `count` runs no query.
140 soon = true;
141 queueMicrotask(() => {
142 soon = false;
143 tick();
144 });
145 } else if (!timer) {
146 timer = setTimeout(tick, flushMs);
147 timer.unref?.();
148 }
149 },
150 flush,
151 stop() {
152 clear();
153 try {
154 flush();
155 } catch {
156 // Closing must not fail on a counter; what was pending is lost.
157 }
158 },
159 };
160 }
161
162 /** Every row from `sinceHour` (`2026-10-15T14`) on, oldest first. */
163 export function readUsage(db: Database, sinceHour: string): UsageRow[] {
164 if (!HOUR.test(sinceHour)) throw new Error("usage count: bad hour");
165 return db
166 .prepare(
167 `SELECT hour, pattern, method, status, role, surface, n FROM usage_count
168 WHERE hour >= ? ORDER BY hour, pattern, method, status, role, surface`,
169 )
170 .all(sinceHour) as UsageRow[];
171 }
src/http/mcp.ts +20
@@ -20,6 +20,7 @@
2020 import { voteVariant } from "../actions/variants.ts";
2121 import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
2222 import { listAccess } from "../actions/access_log.ts";
23 import { listTraffic } from "../actions/traffic.ts";
2324 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
2425 import { conflictedPulls, conflictedSays } from "../flow/conflicted.ts";
2526 import { readPipeline, verdict } from "../flow/pipeline.ts";
@@ -2006,6 +2007,25 @@ const TOOLS: readonly Tool[] = [
20062007 return good({ requests: listed.value });
20072008 },
20082009 },
2010 {
2011 name: "traffic",
2012 description:
2013 "How many requests each route took, per UTC hour, for a forge admin: newest hour first, at most 500 rows of hour, method, route pattern (never the path), status class (2xx…5xx), role (anon, user, admin, agent) and surface (api, mcp, web), with the count. `since` is an hour like 2026-10-15T09 (the last day when absent). Needs a write-scope token. The same as Settings → Traffic.",
2014 inputSchema: {
2015 type: "object",
2016 properties: { since: { type: "string", maxLength: 13 } },
2017 },
2018 writes: true,
2019 run(ctx, user, args) {
2020 const since = typeof args.since === "string" && args.since !== "" ? args.since.slice(0, 13) : undefined;
2021 const listed = listTraffic(ctx.app, user, since);
2022 if (!listed.ok)
2023 return listed.error === "bad_hour"
2024 ? bad("invalid", "since is an hour like 2026-10-15T09")
2025 : bad("not_found", "no such tool here");
2026 return good({ counts: listed.value });
2027 },
2028 },
20092029 {
20102030 name: "capacity",
20112031 description:
src/http/server.ts +47 −2
@@ -9,6 +9,7 @@ import { signupOptions, signupPasskey } from "../web/pages/signup-passkey.ts";
99 import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts";
1010 import { unsealReleased } from "../actions/sealed.ts";
1111 import { accessPage } from "../web/pages/access.ts";
12 import { trafficPage } from "../web/pages/traffic.ts";
1213 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
1314 import { flowPage } from "../web/pages/flow.ts";
1415 import { resiliencePage } from "../web/pages/resilience.ts";
@@ -444,7 +445,8 @@ import {
444445 } from "../core/idempotency.ts";
445446 import { sseStream, viewerStream } from "./sse.ts";
446447 import { Router } from "./router.ts";
447 import { getUserById } from "../core/users.ts";
448 import { getUserById, type User } from "../core/users.ts";
449 import type { UsageRole } from "../core/usage_count.ts";
448450 import { appsRuntime } from "../apps/runtime.ts";
449451 import {
450452 appWebSocket,
@@ -726,6 +728,7 @@ export function buildRouter(): Router<Handler> {
726728 router.add("POST", "/settings/cloud/audit", cloudAudit);
727729 router.add("POST", "/settings/cloud/remove", cloudRemove);
728730 router.add("GET", "/settings/access", accessPage);
731 router.add("GET", "/settings/traffic", trafficPage);
729732 router.add("GET", "/settings/capacity", capacityPage);
730733 router.add("POST", "/settings/capacity", capacitySet);
731734 router.add("GET", "/boards", boardsList);
@@ -1955,6 +1958,42 @@ export async function serve(app: App): Promise<Servers> {
19551958 };
19561959 }
19571960
1961 /** What `answerGet` learned about a request that matched a route, for the count. */
1962 interface Seen {
1963 pattern?: string;
1964 method?: string;
1965 role?: UsageRole;
1966 }
1967
1968 /** The count's role comes from the verified account, never from a header or cookie. */
1969 function roleOf(user: User | undefined): UsageRole {
1970 if (user === undefined) return "anon";
1971 if (user.kind === "agent") return "agent";
1972 return user.isAdmin ? "admin" : "user";
1973 }
1974
1975 /**
1976 * One matched request, counted under its route pattern (never the raw path,
1977 * so the table stays as small as the route table). A miss is not counted.
1978 * Counting is a memory increment and may never fail a response.
1979 */
1980 function countRequest(app: App, request: Request, response: Response, seen: Seen): void {
1981 if (seen.pattern === undefined || seen.method === undefined || seen.role === undefined) return;
1982 const path = new URL(request.url).pathname;
1983 const surface = path.startsWith("/api/") ? "api" : path === "/mcp" || path.startsWith("/mcp/") ? "mcp" : "web";
1984 try {
1985 app.requests.count({
1986 pattern: seen.pattern,
1987 method: seen.method,
1988 status: response.status,
1989 role: seen.role,
1990 surface,
1991 });
1992 } catch {
1993 // An odd status or pattern is not worth a failed request.
1994 }
1995 }
1996
19581997 /**
19591998 * One request against the forge's own routes: liveness and readiness, the route that
19601999 * matched or the two shapes of "no route", the limiter, and the handler.
@@ -1973,7 +2012,9 @@ async function answer(
19732012 limiter: RateLimiter,
19742013 request: Request,
19752014 ): Promise<Response> {
1976 const response = await answerGet(app, router, apiRouter, limiter, request);
2015 const seen: Seen = {};
2016 const response = await answerGet(app, router, apiRouter, limiter, request, seen);
2017 countRequest(app, request, response, seen);
19772018 return request.method === "HEAD"
19782019 ? new Response(null, { status: response.status, headers: response.headers })
19792020 : response;
@@ -1985,6 +2026,7 @@ async function answerGet(
19852026 apiRouter: Router<Handler>,
19862027 limiter: RateLimiter,
19872028 request: Request,
2029 seen: Seen = {},
19882030 ): Promise<Response> {
19892031 const url = publicUrl(request, app.config.url);
19902032 if (url.pathname === "/healthz")
@@ -2024,6 +2066,9 @@ async function answerGet(
20242066 return noRoute(request.method, url.pathname);
20252067 }
20262068 const auth = await resolveAuth(app, request);
2069 seen.pattern = matched.pattern;
2070 seen.method = routeMethod;
2071 seen.role = roleOf(auth.user);
20272072 // From here a body's cap depends on who is asking (`http/limits.ts`), and
20282073 // a stream this request opens is the account's, to end with it.
20292074 if (auth.user !== undefined) {
src/tui/forge.ts +9
@@ -38,6 +38,7 @@ import { pullScreen } from "./screens/pull.ts";
3838 import { blobScreen } from "./screens/repo.ts";
3939 import { dashboardScreen } from "./screens/dashboard.ts";
4040 import { accessScreen } from "./screens/access.ts";
41 import { trafficScreen } from "./screens/traffic.ts";
4142 import { resilienceLines, resilienceScreen } from "./screens/resilience.ts";
4243 import { flowLines, flowScreen } from "./screens/flow.ts";
4344 import { stalledScreen } from "./screens/stalled.ts";
@@ -248,6 +249,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
248249 hint: "what outside agents tried",
249250 run: () => ctx.push(accessScreen(session, ctx)),
250251 });
252 // How many requests each route took, per hour: a site admin's, as Settings → Traffic says it.
253 if (session.user?.isAdmin === true && session.user.kind !== "agent")
254 commands.push({
255 id: "traffic",
256 title: "Traffic",
257 hint: "requests per route and hour",
258 run: () => ctx.push(trafficScreen(session, ctx)),
259 });
251260 commands.push({
252261 id: "family",
253262 title: "Family",
src/tui/screens/traffic.ts added +64
@@ -0,0 +1,64 @@
1 /**
2 * Request counts per route and hour in the terminal, a forge admin's: the
3 * last day, newest first — `listTraffic`, the action the settings page and
4 * the `traffic` MCP tool read. Who may read is the action's call, not this
5 * screen's: anyone else gets an empty screen.
6 */
7
8 import { listTraffic } from "../../actions/traffic.ts";
9 import type { UsageRow } from "../../core/usage_count.ts";
10 import type { Ctx, Screen } from "../app/app.ts";
11 import { binding } from "../app/keys.ts";
12 import { fill, len, split } from "../ui/layout.ts";
13 import { style } from "../term/style.ts";
14 import { truncate } from "../term/width.ts";
15 import type { Session } from "../session.ts";
16 import { ListState, drawList, type ListRow } from "./common.ts";
17
18 export function trafficScreen(f: Session, ctx: Ctx): Screen {
19 const state = new ListState();
20 let rows: UsageRow[] = [];
21 let loaded = false;
22
23 const reload = (): void => {
24 const listed = listTraffic(f.app, f.user);
25 rows = listed.ok ? listed.value : [];
26 loaded = true;
27 state.clamp(rows.length);
28 ctx.invalidate();
29 };
30
31 const listRows = (): ListRow[] =>
32 rows.map((r) => ({
33 title: `${r.method} ${r.pattern}`,
34 secondary: String(r.n),
35 meta: `${r.hour}:00 UTC · ${r.status} · ${r.role} · ${r.surface}`,
36 }));
37
38 const screen: Screen = {
39 title: "Traffic",
40 keys: [binding(["j", "k"], "move cursor"), binding(["r"], "reload")],
41 load() {
42 reload();
43 return Promise.resolve();
44 },
45 render(area, s) {
46 const c = ctx.theme.c;
47 const [head, list] = split(area, "v", [len(1), fill(1)]);
48 const note = !loaded
49 ? "Loading…"
50 : rows.length === 0
51 ? "Nothing counted in the last day."
52 : `${rows.length} count${rows.length === 1 ? "" : "s"}, newest hour first`;
53 s.text(head!.x, head!.y, truncate(note, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
54 drawList(s, list!, c, state, listRows());
55 },
56 key(e) {
57 if (state.key(e, rows.length)) return true;
58 if (e.ctrl || e.alt || e.key !== "r") return false;
59 reload();
60 return true;
61 },
62 };
63 return screen;
64 }
src/web/pages/origins.ts +7
@@ -82,6 +82,7 @@ export type AccountSection =
8282 | "secrets"
8383 | "capacity"
8484 | "access"
85 | "traffic"
8586 | "limits"
8687 | "cloud";
8788
@@ -140,6 +141,12 @@ export function accountSections(
140141 icon: "activity" as const,
141142 current: current === "access",
142143 },
144 {
145 label: "Traffic",
146 href: "/settings/traffic",
147 icon: "activity" as const,
148 current: current === "traffic",
149 },
143150 {
144151 label: "Limits",
145152 href: "/admin/limits",
src/web/pages/traffic.ts added +57
@@ -0,0 +1,57 @@
1 /**
2 * How many requests each route took, per hour, for a forge admin
3 * (`core/usage_count.ts`): counts only, by route pattern, status class,
4 * role and surface — no path, address or credential is ever kept.
5 */
6
7 import { listTraffic } from "../../actions/traffic.ts";
8 import type { Ctx } from "../../http/context.ts";
9 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
10 import { html } from "../html.ts";
11 import { page } from "../layout.ts";
12 import { card, icon, row } from "../ui.ts";
13 import { accountSections } from "./origins.ts";
14
15 // GET /settings/traffic
16 export function trafficPage(ctx: Ctx): Response {
17 if (!ctx.auth.user) return signInFirst(ctx);
18 const asked = ctx.url.searchParams.get("since")?.slice(0, 13);
19 const listed = listTraffic(ctx.app, ctx.auth.user, asked || undefined);
20 if (!listed.ok && listed.error === "not_found") return notFoundPage(ctx);
21 const rows = (listed.ok ? listed.value : []).map((r) =>
22 row({
23 lead: icon("activity"),
24 title: html`<span class="mono">${r.method} ${r.pattern}</span>
25 <span class="mono">${String(r.n)}</span>`,
26 meta: html`${r.hour}:00 UTC · ${r.status} · ${r.role} · ${r.surface}`,
27 }),
28 );
29 const body = card(
30 html`<div class="card-body">
31 <p class="muted small">
32 Requests answered, per hour (UTC), by the route that answered them,
33 newest first, for the last day (<span class="mono">?since=2026-10-15T09</span>
34 goes further back). The route is its pattern, never the path; the role is
35 the verified account's. ${listed.ok ? "" : "That hour is not valid."}
36 </p>
37 </div>
38 ${rows.length === 0
39 ? html`<div class="card-body">
40 <p class="muted small" id="traffic-none">Nothing counted in that time.</p>
41 </div>`
42 : html`<ul class="list" id="traffic-list">
43 ${rows}
44 </ul>`}`,
45 {
46 head: html`${icon("activity")}
47 <h2>Requests per hour</h2>`,
48 pad: false,
49 },
50 );
51 return page({
52 ctx,
53 title: "Traffic",
54 body: html`<div class="page-head"><h1>Traffic</h1></div>
55 ${settingsLayout(accountSections("traffic", { admin: true }), body, "Account settings")}`,
56 });
57 }
test/mcp.test.ts +1
@@ -206,6 +206,7 @@ describe("the forge over MCP", () => {
206206 "hold",
207207 "plan",
208208 "access",
209 "traffic",
209210 "capacity",
210211 "flow",
211212 "limits",
test/tui-traffic.test.ts added +80
@@ -0,0 +1,80 @@
1 /** The traffic screen: a forge admin sees the counts; others have no such command. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App as Forge } from "../src/app.ts";
7 import { createUser, getUserByName } from "../src/core/users.ts";
8 import { createForgeApp } from "../src/tui/forge.ts";
9 import type { TuiIdentity } from "../src/tui/session.ts";
10 import { headlessTerminal } from "../src/tui/term/terminal.ts";
11 import { quietLogs } from "./helpers/globals.ts";
12 import { settleApp } from "./helpers/tui.ts";
13
14 quietLogs();
15
16 describe("traffic in the terminal", () => {
17 let dataDir: string;
18 let forge: Forge;
19
20 function boot(username: string) {
21 const terminal = headlessTerminal(140, 32);
22 const user = getUserByName(forge.db, username)!;
23 const identity: TuiIdentity = { sshUsername: "t", remoteAddress: "127.0.0.1", user };
24 const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false });
25 app.start();
26 const key = (k: string) =>
27 app.dispatch({ type: "key", key: k, ctrl: k.startsWith("ctrl+"), alt: false, shift: false });
28 const press = async (...keys: string[]) => {
29 for (const k of keys) key(k.startsWith("ctrl+") ? k.slice(5) : k);
30 await settleApp(app);
31 };
32 const ctrl = async (k: string) => {
33 app.dispatch({ type: "key", key: k, ctrl: true, alt: false, shift: false });
34 await settleApp(app);
35 };
36 const type = async (text: string) => {
37 for (const ch of text) key(ch);
38 await settleApp(app);
39 };
40 return { text: () => app.screen.toText(), press, ctrl, type, stop: () => app.stop() };
41 }
42
43 beforeAll(async () => {
44 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-traffic-"));
45 forge = createApp({ dataDir, port: 0 });
46 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
47 const made = await createUser(forge.db, {
48 trusted: true,
49 username,
50 email: `${username}@forge.local`,
51 password: "a-good-passphrase",
52 adminIfFirst,
53 });
54 if (!made.ok) throw new Error(made.error);
55 }
56 forge.requests.count({ pattern: "/api/v1/repos", method: "GET", status: 200, role: "user", surface: "api" });
57 });
58
59 afterAll(async () => {
60 forge.close();
61 await rm(dataDir, { recursive: true, force: true });
62 });
63
64 const open = async (h: ReturnType<typeof boot>) => {
65 await h.ctrl("k");
66 await h.type("Traffic");
67 await h.press("enter");
68 };
69
70 test("an admin reads the counts; a member has no such command", async () => {
71 const h = boot("alice");
72 await open(h);
73 expect(h.text()).toContain("GET /api/v1/repos");
74 h.stop();
75 const b = boot("bob");
76 await open(b);
77 expect(b.text()).not.toContain("GET /api/v1/repos");
78 b.stop();
79 });
80 });
test/usage-count-wired.test.ts added +121
@@ -0,0 +1,121 @@
1 /**
2 * The request counter in the server: a real request lands as a row under
3 * its route pattern, with the role of the verified account, and only a
4 * forge admin reads the counts (page and `traffic` MCP tool).
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 } from "../src/core/usage_count.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16
17 describe("requests are counted", () => {
18 let dataDir: string;
19 let app: App;
20 let servers: Servers;
21 let adminRw: string;
22 let bobRw: string;
23
24 const rows = () => {
25 app.requests.flush();
26 return readUsage(app.db, "2000-01-01T00");
27 };
28 const mcp = async (token: string, args: Record<string, unknown>) => {
29 const res = await fetch(`${servers.url}/mcp`, {
30 method: "POST",
31 headers: {
32 authorization: `Bearer ${token}`,
33 "content-type": "application/json",
34 accept: "application/json, text/event-stream",
35 },
36 body: JSON.stringify({
37 jsonrpc: "2.0",
38 id: 1,
39 method: "tools/call",
40 params: { name: "traffic", arguments: args },
41 }),
42 });
43 const body = (await res.json()) as {
44 result: { isError?: boolean; content: { text: string }[] };
45 };
46 return { error: body.result.isError === true, text: body.result.content[0]!.text };
47 };
48
49 beforeAll(async () => {
50 dataDir = await mkdtemp(join(tmpdir(), "forge-traffic-"));
51 app = createApp({ dataDir, port: 0 });
52 servers = await serve(app);
53 const a = await createUser(app.db, {
54 trusted: true,
55 username: "alice",
56 email: "[email protected]",
57 password: "a-good-passphrase",
58 adminIfFirst: true,
59 });
60 const b = await createUser(app.db, {
61 trusted: true,
62 username: "bob",
63 email: "[email protected]",
64 password: "a-good-passphrase",
65 });
66 if (!a.ok || !b.ok) throw new Error("users");
67 adminRw = createToken(app.db, a.value.id, "t", "rw").token;
68 bobRw = createToken(app.db, b.value.id, "t", "rw").token;
69 });
70
71 afterAll(async () => {
72 servers.stop();
73 app.close();
74 await rm(dataDir, { recursive: true, force: true });
75 });
76
77 test("a real request is a row under its route pattern and verified role", async () => {
78 expect(rows()).toEqual([]);
79 await fetch(`${servers.url}/api/v1/repos`);
80 await fetch(`${servers.url}/api/v1/repos`, {
81 headers: { authorization: `Bearer ${bobRw}`, "x-forge-role": "admin" },
82 });
83 await fetch(`${servers.url}/api/v1/repos/nobody/nothing`);
84 await fetch(`${servers.url}/api/v1/no-such-route/anything`);
85 const got = rows();
86 const key = (r: (typeof got)[number]) => `${r.method} ${r.pattern} ${r.status} ${r.role} ${r.surface}`;
87 expect(got.map(key).sort()).toEqual([
88 "GET /api/v1/repos 2xx anon api",
89 "GET /api/v1/repos 2xx user api",
90 "GET /api/v1/repos/:owner/:name 4xx anon api",
91 ]);
92 expect(got.every((r) => r.n === 1)).toBe(true);
93 });
94
95 test("an admin reads the counts by MCP; anyone else is told nothing exists", async () => {
96 await fetch(`${servers.url}/api/v1/repos`, { headers: { authorization: `Bearer ${adminRw}` } });
97 const read = await mcp(adminRw, {});
98 expect(read.error).toBe(false);
99 expect(read.text).toContain("/api/v1/repos");
100 expect(read.text).toContain('"role":"admin"');
101 expect((await mcp(adminRw, { since: "yesterday" })).error).toBe(true);
102 const bob = await mcp(bobRw, {});
103 expect(bob.error).toBe(true);
104 expect(bob.text).toContain("not_found");
105 });
106
107 test("the settings page is the admin's", async () => {
108 const anon = await fetch(`${servers.url}/settings/traffic`, { redirect: "manual" });
109 expect(anon.status).not.toBe(200);
110 const res = await fetch(`${servers.url}/signin`, {
111 method: "POST",
112 redirect: "manual",
113 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
114 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
115 });
116 const cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
117 const page = await fetch(`${servers.url}/settings/traffic`, { headers: { cookie } });
118 expect(page.status).toBe(200);
119 expect(await page.text()).toContain("/api/v1/repos");
120 });
121 });
test/usage-count.test.ts added +91
@@ -0,0 +1,91 @@
1 /** The request counter: batched in memory, written in one transaction. */
2
3 import { describe, expect, test } from "bun:test";
4 import { Database } from "bun:sqlite";
5 import { migrations } from "../src/core/schema.ts";
6 import { migrate } from "../src/kernel/migrate.ts";
7 import { createUsageCounter, readUsage, type UsageHit } from "../src/core/usage_count.ts";
8
9 const db = () => {
10 const d = new Database(":memory:");
11 migrate(d, migrations);
12 return d;
13 };
14 const hit: UsageHit = { pattern: "/api/v1/repos", method: "GET", status: 200, role: "user", surface: "api" };
15
16 describe("usage count", () => {
17 test("three counts of one key are one row of 3 after a flush, none before", () => {
18 const d = db();
19 const c = createUsageCounter(d, { now: () => new Date("2026-10-15T14:05:00Z") });
20 c.count(hit);
21 c.count({ ...hit, status: 204 });
22 c.count(hit);
23 expect(readUsage(d, "2026-10-15T00")).toEqual([]);
24 c.flush();
25 expect(readUsage(d, "2026-10-15T00")).toEqual([
26 { hour: "2026-10-15T14", pattern: "/api/v1/repos", method: "GET", status: "2xx", role: "user", surface: "api", n: 3 },
27 ]);
28 c.count(hit);
29 c.stop();
30 expect(readUsage(d, "2026-10-15T00")[0]!.n).toBe(4);
31 });
32
33 test("two hours make two rows; sinceHour filters", () => {
34 const d = db();
35 let t = "2026-10-15T14:59:00Z";
36 const c = createUsageCounter(d, { now: () => new Date(t) });
37 c.count(hit);
38 t = "2026-10-15T15:00:00Z";
39 c.count(hit);
40 c.flush();
41 expect(readUsage(d, "2026-10-15T00").map((r) => r.hour)).toEqual(["2026-10-15T14", "2026-10-15T15"]);
42 expect(readUsage(d, "2026-10-15T15")).toHaveLength(1);
43 });
44
45 test("anything outside the closed sets is refused", () => {
46 const c = createUsageCounter(db());
47 for (const bad of [
48 { role: "root" }, { surface: "ssh" }, { status: 99 }, { status: 600 }, { status: 2.5 },
49 { method: "BREW" }, { pattern: "" },
50 ]) {
51 expect(() => c.count({ ...hit, ...bad } as unknown as UsageHit)).toThrow();
52 }
53 expect(() => readUsage(db(), "yesterday")).toThrow();
54 });
55
56 test("flushes by itself after the interval and at the key cap", async () => {
57 const d = db();
58 const c = createUsageCounter(d, { flushMs: 10 });
59 c.count(hit);
60 await Bun.sleep(40);
61 expect(readUsage(d, "2000-01-01T00")).toHaveLength(1);
62 const e = db();
63 const k = createUsageCounter(e, { flushMs: 60000, maxKeys: 3 });
64 for (const p of ["/a", "/b", "/c"]) k.count({ ...hit, pattern: p });
65 expect(readUsage(e, "2000-01-01T00")).toHaveLength(0);
66 await Bun.sleep(0);
67 expect(readUsage(e, "2000-01-01T00")).toHaveLength(3);
68 k.stop();
69 c.stop();
70 });
71 });
72
73 describe("usage count failures", () => {
74 test("a batch that never goes in is dropped after a few tries", () => {
75 const d = new Database(":memory:");
76 migrate(d, migrations);
77 const c = createUsageCounter(d);
78 d.run("DROP TABLE usage_count");
79 c.count(hit);
80 expect(() => c.flush()).toThrow();
81 expect(() => c.flush()).toThrow();
82 expect(() => c.flush()).toThrow();
83 // Dropped: with the table back, nothing is left to write.
84 d.run(
85 "CREATE TABLE usage_count (hour TEXT, pattern TEXT, method TEXT, status TEXT, role TEXT, surface TEXT, n INTEGER, PRIMARY KEY (hour, pattern, method, status, role, surface))",
86 );
87 c.flush();
88 expect(readUsage(d, "2000-01-01T00")).toEqual([]);
89 expect(() => c.stop()).not.toThrow();
90 });
91 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs