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 #1708
scout/forge:scout/1564-every-answered-request-is-counted-by-rou → main 7 commits fork 8 threads · 8 unresolved
scripts/gate.ts +1
| @@ -27,6 +27,7 @@ export type Exclusion = { | ||
| 27 | 27 | export const GATE: readonly string[] = [ |
| 28 | 28 | "test/accounts-retire.test.ts", |
| 29 | 29 | "test/accounts.test.ts", |
| 30 | "test/usage-count.test.ts", | |
| 30 | 31 | "test/agents.test.ts", |
| 31 | 32 | "test/app-domains.test.ts", |
| 32 | 33 | "test/app.test.ts", |
src/core/schema.ts +15
| @@ -1670,6 +1670,21 @@ export const migrations: readonly string[] = [ | ||
| 1670 | 1670 | reason TEXT |
| 1671 | 1671 | ); |
| 1672 | 1672 | `, |
| 1673 | // 81 — what is asked of the forge (#1564, `core/usage_count.ts`): one | |
| 1674 | // counted row per hour, route pattern, method, status class, viewer role | |
| 1675 | // and surface. Never a path, an id or a person. | |
| 1676 | ` | |
| 1677 | CREATE TABLE request_count ( | |
| 1678 | hour TEXT NOT NULL, | |
| 1679 | route TEXT NOT NULL, | |
| 1680 | method TEXT NOT NULL, | |
| 1681 | status_class TEXT NOT NULL, | |
| 1682 | role TEXT NOT NULL, | |
| 1683 | surface TEXT NOT NULL, | |
| 1684 | n INTEGER NOT NULL CHECK (n >= 0), | |
| 1685 | PRIMARY KEY (hour, route, method, status_class, role, surface) | |
| 1686 | ) WITHOUT ROWID; | |
| 1687 | `, | |
| 1673 | 1688 | ]; |
| 1674 | 1689 | |
| 1675 | 1690 | /** |
src/core/usage_count.ts added +190
| @@ -0,0 +1,190 @@ | ||
| 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 | /** Rows older than this many days are dropped when counts are written. */ | |
| 42 | export const RETAIN_DAYS = 90; | |
| 43 | /** And no more than this many distinct keys wait at all. */ | |
| 44 | const FLUSH_KEYS = 500; | |
| 45 | ||
| 46 | const SEP = "\u0000"; | |
| 47 | ||
| 48 | export class UsageCounter { | |
| 49 | private pending = new Map<string, number>(); | |
| 50 | private timer: ReturnType<typeof setTimeout> | undefined; | |
| 51 | ||
| 52 | constructor( | |
| 53 | private readonly db: Database, | |
| 54 | private readonly now: () => Date = () => new Date(), | |
| 55 | ) {} | |
| 56 | ||
| 57 | /** Count one answered request. Never throws, never touches the database. */ | |
| 58 | note(seen: Seen): void { | |
| 59 | const hour = this.now().toISOString().slice(0, 13) + ":00:00Z"; | |
| 60 | const method = METHODS.has(seen.method) ? seen.method : "OTHER"; | |
| 61 | const statusClass = `${Math.floor(seen.status / 100)}xx`; | |
| 62 | const key = [hour, seen.route, method, statusClass, seen.role, seen.surface].join(SEP); | |
| 63 | this.pending.set(key, (this.pending.get(key) ?? 0) + 1); | |
| 64 | if (this.pending.size >= FLUSH_KEYS) this.flush(); | |
| 65 | else if (this.timer === undefined) { | |
| 66 | this.timer = setTimeout(() => this.flush(), FLUSH_MS); | |
| 67 | this.timer.unref(); | |
| 68 | } | |
| 69 | } | |
| 70 | ||
| 71 | /** Drop hours past the retention, so the table has a size. Never throws. */ | |
| 72 | prune(): void { | |
| 73 | const cutoff = new Date(this.now().getTime() - RETAIN_DAYS * 86_400_000) | |
| 74 | .toISOString() | |
| 75 | .slice(0, 13) + ":00:00Z"; | |
| 76 | try { | |
| 77 | this.db.query("DELETE FROM request_count WHERE hour < ?1").run(cutoff); | |
| 78 | } catch { | |
| 79 | // Same as a flush: a gauge never fails a request. | |
| 80 | } | |
| 81 | } | |
| 82 | ||
| 83 | /** Write what has gathered. A closed or busy database drops it, quietly. */ | |
| 84 | flush(): void { | |
| 85 | if (this.timer !== undefined) clearTimeout(this.timer); | |
| 86 | this.timer = undefined; | |
| 87 | const batch = this.pending; | |
| 88 | this.pending = new Map(); | |
| 89 | if (batch.size === 0) return; | |
| 90 | this.prune(); | |
| 91 | try { | |
| 92 | const upsert = this.db.query( | |
| 93 | `INSERT INTO request_count (hour, route, method, status_class, role, surface, n) | |
| 94 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) | |
| 95 | ON CONFLICT (hour, route, method, status_class, role, surface) | |
| 96 | DO UPDATE SET n = n + excluded.n`, | |
| 97 | ); | |
| 98 | this.db.transaction(() => { | |
| 99 | for (const [key, n] of batch) { | |
| 100 | const [hour, route, method, statusClass, role, surface] = key.split(SEP); | |
| 101 | upsert.run(hour!, route!, method!, statusClass!, role!, surface!, n); | |
| 102 | } | |
| 103 | })(); | |
| 104 | } catch { | |
| 105 | // A gauge: losing a moment of it must never fail a request. | |
| 106 | } | |
| 107 | } | |
| 108 | } | |
| 109 | ||
| 110 | /** The counted rows, newest hour first. */ | |
| 111 | export function listCounts(db: Database): CountRow[] { | |
| 112 | return db | |
| 113 | .query< | |
| 114 | { | |
| 115 | hour: string; | |
| 116 | route: string; | |
| 117 | method: string; | |
| 118 | status_class: string; | |
| 119 | role: Role; | |
| 120 | surface: Surface; | |
| 121 | n: number; | |
| 122 | }, | |
| 123 | [] | |
| 124 | >(`SELECT * FROM request_count ORDER BY hour DESC, route, method, status_class, role, surface`) | |
| 125 | .all() | |
| 126 | .map((r) => ({ | |
| 127 | hour: r.hour, | |
| 128 | route: r.route, | |
| 129 | method: r.method, | |
| 130 | statusClass: r.status_class, | |
| 131 | role: r.role, | |
| 132 | surface: r.surface, | |
| 133 | n: r.n, | |
| 134 | })); | |
| 135 | } | |
| 136 | ||
| 137 | /** | |
| 138 | * Who is asking, in the six words the table keeps. On a repository's own | |
| 139 | * routes (`:owner/:name`) the role is what they may do there; elsewhere a | |
outdated
No test reaches this branch, the |
||
| 140 | * signed-in person is a reader. Admin and agent are what the account is. | |
| 141 | */ | |
| 142 | export function viewerRole( | |
| 143 | db: Database, | |
| 144 | user: User | undefined, | |
| 145 | params: Readonly<Record<string, string>>, | |
| 146 | ): Role { | |
| 147 | if (user === undefined) return "stranger"; | |
outdated
Fragments are also requested with the |
||
| 148 | if (user.kind === "agent") return "agent"; | |
| 149 | if (user.isAdmin) return "admin"; | |
| 150 | const { owner, name } = params; | |
| 151 | if (owner === undefined || name === undefined) return "reader"; | |
| 152 | const repo = getRepo(db, owner, name); | |
| 153 | if (repo === undefined) return "reader"; | |
| 154 | if (canAdmin(db, repo, user)) return "owner"; | |
| 155 | return canWrite(db, repo, user) ? "writer" : "reader"; | |
| 156 | } | |
| 157 | ||
| 158 | /** Which door a request came through. */ | |
| 159 | export function surfaceOf( | |
| 160 | pathname: string, | |
| 161 | search: URLSearchParams, | |
| 162 | headers?: Headers, | |
| 163 | ): Surface { | |
| 164 | if (pathname === "/mcp" || pathname.startsWith("/mcp/")) return "mcp"; | |
| 165 | if (pathname === "/api" || pathname.startsWith("/api/")) return "api"; | |
| 166 | return search.has("fragment") || headers?.get("x-forge-fragment") === "1" ? "fragment" : "page"; | |
| 167 | } | |
| 168 | ||
| 169 | /** | |
| 170 | * The pattern an ssh session is counted under: the door and, for an exec, | |
| 171 | * the git service it asks for — never the command's text, a path or a name. | |
| 172 | */ | |
| 173 | export function sshRoute(kind: "shell" | "exec", service: string | undefined): string { | |
| 174 | if (kind === "shell") return "ssh:shell"; | |
| 175 | return service === "git-upload-pack" || service === "git-receive-pack" | |
| 176 | ? `ssh:exec:${service}` | |
| 177 | : "ssh:exec:other"; | |
| 178 | } | |
| 179 | ||
| 180 | const counters = new WeakMap<Database, UsageCounter>(); | |
| 181 | ||
| 182 | /** The one counter a database has. */ | |
| 183 | export function counterFor(db: Database): UsageCounter { | |
| 184 | let counter = counters.get(db); | |
| 185 | if (counter === undefined) { | |
| 186 | counter = new UsageCounter(db); | |
| 187 | counters.set(db, counter); | |
| 188 | } | |
| 189 | return counter; | |
| 190 | } |
src/http/router.ts +6 −3
| @@ -16,11 +16,14 @@ type Segment = | ||
| 16 | 16 | |
| 17 | 17 | export interface Match<H> { |
| 18 | 18 | handler: H; |
| 19 | /** The pattern string the route was added under, never the raw path. */ | |
| 20 | pattern: string; | |
| 19 | 21 | params: Params; |
| 20 | 22 | } |
| 21 | 23 | |
| 22 | 24 | interface CompiledRoute<H> { |
| 23 | 25 | method: string; |
| 26 | pattern: string; | |
| 24 | 27 | segments: Segment[]; |
| 25 | 28 | handler: H; |
| 26 | 29 | } |
| @@ -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, pattern, segments: compile(pattern), handler }); | |
| 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, pattern: route.pattern, params }; | |
| 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, pattern: route.pattern, params }; | |
| 103 | 106 | } |
| 104 | 107 | return undefined; |
| 105 | 108 | } |
src/http/server.ts +28 −3
| @@ -376,6 +376,13 @@ import { targetForShortCode } from "../origins/oauth.ts"; | ||
| 376 | 376 | import { apiRoutes } from "./api.ts"; |
| 377 | 377 | import { feedRoutes } from "./feed.ts"; |
| 378 | 378 | import { mcpRoutes } from "./mcp.ts"; |
| 379 | import { | |
| 380 | counterFor, | |
| 381 | surfaceOf, | |
| 382 | viewerRole, | |
| 383 | type Role, | |
| 384 | type Seen, | |
| 385 | } from "../core/usage_count.ts"; | |
| 379 | 386 | import { oauthRoutes } from "./oauth.ts"; |
| 380 | 387 | import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts"; |
| 381 | 388 | import { parseCidrs } from "../kernel/cidr.ts"; |
| @@ -1798,6 +1805,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1798 | 1805 | stop() { |
| 1799 | 1806 | endOpen(); |
| 1800 | 1807 | clearInterval(sweep); |
| 1808 | counterFor(app.db).flush(); | |
| 1801 | 1809 | for (const http of childHttps.values()) http.close(); |
| 1802 | 1810 | childHttps.clear(); |
| 1803 | 1811 | closeHostedChildren(app); |
| @@ -1827,7 +1835,16 @@ async function answer( | ||
| 1827 | 1835 | limiter: RateLimiter, |
| 1828 | 1836 | request: Request, |
| 1829 | 1837 | ): Promise<Response> { |
| 1830 | const response = await answerGet(app, router, apiRouter, limiter, request); | |
| 1838 | const seen: Pick<Seen, "route" | "role"> = { route: "(no route)", role: "stranger" }; | |
| 1839 | const response = await answerGet(app, router, apiRouter, limiter, request, seen); | |
| 1840 | // The one place an answered request is counted (`core/usage_count.ts`). | |
| 1841 | const url = new URL(request.url); | |
| 1842 | counterFor(app.db).note({ | |
| 1843 | ...seen, | |
| 1844 | method: request.method, | |
| 1845 | status: response.status, | |
| 1846 | surface: surfaceOf(url.pathname, url.searchParams, request.headers), | |
| 1847 | }); | |
| 1831 | 1848 | return request.method === "HEAD" |
| 1832 | 1849 | ? new Response(null, { status: response.status, headers: response.headers }) |
| 1833 | 1850 | : response; |
| @@ -1839,11 +1856,17 @@ async function answerGet( | ||
| 1839 | 1856 | apiRouter: Router<Handler>, |
| 1840 | 1857 | limiter: RateLimiter, |
| 1841 | 1858 | request: Request, |
| 1859 | seen: { route: string; role: Role }, | |
| 1842 | 1860 | ): Promise<Response> { |
| 1843 | 1861 | const url = publicUrl(request, app.config.url); |
| 1844 | if (url.pathname === "/healthz") | |
| 1862 | if (url.pathname === "/healthz") { | |
| 1863 | seen.route = "/healthz"; | |
| 1845 | 1864 | return liveResponse(() => app.db.query("select 1").get(), app.log); |
| 1846 | if (url.pathname === "/readyz") return readyResponse(); | |
| 1865 | } | |
| 1866 | if (url.pathname === "/readyz") { | |
| 1867 | seen.route = "/readyz"; | |
| 1868 | return readyResponse(); | |
| 1869 | } | |
| 1847 | 1870 | const routeMethod = request.method === "HEAD" ? "GET" : request.method; |
| 1848 | 1871 | // The one place a path decides its own shape of miss: anything under |
| 1849 | 1872 | // `/api` matches only against the API's own routes, so a studio route as |
| @@ -1877,7 +1900,9 @@ async function answerGet( | ||
| 1877 | 1900 | } |
| 1878 | 1901 | return noRoute(request.method, url.pathname); |
| 1879 | 1902 | } |
| 1903 | seen.route = matched.pattern; | |
| 1880 | 1904 | const auth = await resolveAuth(app, request); |
| 1905 | seen.role = viewerRole(app.db, auth.user, matched.params); | |
This is the right place for it: the role is taken from |
||
| 1881 | 1906 | // From here a body's cap depends on who is asking (`http/limits.ts`), and |
| 1882 | 1907 | // a stream this request opens is the account's, to end with it. |
| 1883 | 1908 | if (auth.user !== undefined) { |
src/tui/ssh.ts +30 −1
| @@ -16,6 +16,7 @@ import type { App as Forge } from "../app.ts"; | ||
| 16 | 16 | import { findKeyByFingerprint, touchKey } from "../core/keys.ts"; |
| 17 | 17 | import { canRead, canWrite, getRepo } from "../core/repos.ts"; |
| 18 | 18 | import { getUserById, isActive, type User } from "../core/users.ts"; |
| 19 | import { counterFor, sshRoute, viewerRole } from "../core/usage_count.ts"; | |
| 19 | 20 | import { createRepo } from "../actions/repos.ts"; |
| 20 | 21 | import { hookEnv } from "../git/hooks.ts"; |
| 21 | 22 | import { repoDir } from "../git/repos.ts"; |
| @@ -200,6 +201,7 @@ export function forgeSshSession(forge: Forge): (session: SshSession) => void { | ||
| 200 | 201 | if (identity.user !== undefined) |
| 201 | 202 | endOnSuspension(forge, session, identity.user); |
| 202 | 203 | if (session.kind === "shell") { |
| 204 | countSession(forge, session, identity.user, 200); | |
| 203 | 205 | // The login name is decorative for the forge — any name opens the |
| 204 | 206 | // terminal UI — unless it names an app, in which case it opens |
| 205 | 207 | // that app's own terminal (docs/APPS.md). |
| @@ -223,6 +225,30 @@ export function forgeSshSession(forge: Forge): (session: SshSession) => void { | ||
| 223 | 225 | }; |
| 224 | 226 | } |
| 225 | 227 | |
| 228 | /** | |
| 229 | * One shell or exec, counted at the terminal door (`core/usage_count.ts`). | |
| 230 | * A shell is counted when it opens; an exec once the git service has decided, | |
| 231 | * under its real outcome: 200 served, 400 not git, 404 refused, 500 failed. | |
| 232 | */ | |
| 233 | function countSession( | |
| 234 | forge: Forge, | |
| 235 | session: SshSession, | |
| 236 | user: User | undefined, | |
| 237 | status: number, | |
outdated
|
||
| 238 | ): void { | |
| 239 | const parsed = | |
| 240 | session.kind === "exec" && session.command !== undefined | |
| 241 | ? parseGitCommand(session.command) | |
| 242 | : null; | |
| 243 | counterFor(forge.db).note({ | |
| 244 | route: sshRoute(session.kind, parsed?.service), | |
| 245 | method: "SSH", | |
| 246 | status, | |
| 247 | role: viewerRole(forge.db, user, parsed === null ? {} : { owner: parsed.owner, name: parsed.name }), | |
| 248 | surface: "ssh", | |
| 249 | }); | |
| 250 | } | |
| 251 | ||
| 226 | 252 | /** |
| 227 | 253 | * Git over an exec channel. The access matrix is exactly the HTTP one: |
| 228 | 254 | * upload-pack → `canRead`; a guest may read a public repo. |
| @@ -238,6 +264,7 @@ async function serveGitCommand( | ||
| 238 | 264 | const parsed = |
| 239 | 265 | session.command === undefined ? null : parseGitCommand(session.command); |
| 240 | 266 | if (parsed === null) { |
| 267 | countSession(forge, session, user, 400); | |
| 241 | 268 | session.writeStderr( |
| 242 | 269 | `forge: only git is available over ssh; run 'ssh ${session.username}@host' for the terminal UI${CRLF}`, |
| 243 | 270 | ); |
| @@ -264,6 +291,7 @@ async function serveGitCommand( | ||
| 264 | 291 | ? user !== undefined && canWrite(forge.db, repo, user) |
| 265 | 292 | : canRead(forge.db, repo, user)); |
| 266 | 293 | if (!repo || !allowed) { |
| 294 | countSession(forge, session, user, 404); | |
| 267 | 295 | session.writeStderr( |
| 268 | 296 | `forge: repository not found: ${parsed.owner}/${parsed.name}${CRLF}`, |
| 269 | 297 | ); |
| @@ -286,7 +314,8 @@ async function serveGitCommand( | ||
| 286 | 314 | if (protocol !== undefined && /^[A-Za-z0-9=:._-]{1,200}$/.test(protocol)) |
| 287 | 315 | env.GIT_PROTOCOL = protocol; |
| 288 | 316 | |
| 289 | await runGitService(dir, parsed.service, session, { env }); | |
| 317 | const code = await runGitService(dir, parsed.service, session, { env }); | |
| 318 | countSession(forge, session, user, code === 0 ? 200 : 500); | |
| 290 | 319 | } |
| 291 | 320 | |
| 292 | 321 | export interface ForgeSshOptions { |
test/usage-count.test.ts added +231
| @@ -0,0 +1,231 @@ | ||
| 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, type User } from "../src/core/users.ts"; | |
| 11 | import { forgeSshSession } from "../src/tui/ssh.ts"; | |
| 12 | import { createOrg, createTeam, addTeamMember } from "../src/core/orgs.ts"; | |
| 13 | import { counterFor, listCounts, surfaceOf, RETAIN_DAYS, UsageCounter } from "../src/core/usage_count.ts"; | |
| 14 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 15 | ||
| 16 | describe("every answered request is counted by route pattern, surface and role", () => { | |
| 17 | let dataDir: string; | |
| 18 | let app: App; | |
| 19 | let servers: Servers; | |
| 20 | let agentToken = ""; | |
| 21 | const tokens: Record<string, string> = {}; | |
| 22 | ||
| 23 | beforeAll(async () => { | |
| 24 | dataDir = await mkdtemp(join(tmpdir(), "forge-usage-count-")); | |
| 25 | app = createApp({ dataDir, port: 0 }); | |
| 26 | servers = await serve(app); | |
| 27 | const alice = await createUser(app.db, { | |
| 28 | username: "alice", | |
| 29 | email: "[email protected]", | |
| 30 | password: "usage-count-pass", | |
| 31 | adminIfFirst: true, | |
| 32 | trusted: true, | |
| 33 | }); | |
| 34 | if (!alice.ok) throw new Error("user"); | |
| 35 | const made = await createRepo(app, alice.value, { name: "yard", visibility: "public" }); | |
| 36 | if (!made.ok) throw new Error("repo"); | |
| 37 | for (const title of ["one", "two", "three"]) | |
| 38 | createIssue(app.db, { repoId: made.value.id, authorId: alice.value.id, title }); | |
| 39 | const bot = await createAgent(app, alice.value, { username: "yardbot" }); | |
| 40 | if (!bot.ok) throw new Error("agent"); | |
| 41 | const user = getUserByName(app.db, "yardbot"); | |
| 42 | agentToken = createToken(app.db, user!.id, "run", "rw").token; | |
| 43 | tokens.alice = createToken(app.db, alice.value.id, "t", "rw").token; | |
| 44 | const people: Record<string, User> = {}; | |
| 45 | for (const name of ["bob", "carol", "dave", "erin"]) { | |
| 46 | const made = await createUser(app.db, { | |
| 47 | username: name, | |
| 48 | email: `${name}@forge.local`, | |
| 49 | password: "usage-count-pass", | |
| 50 | trusted: true, | |
| 51 | }); | |
| 52 | if (!made.ok) throw new Error(name); | |
| 53 | people[name] = made.value; | |
| 54 | tokens[name] = createToken(app.db, made.value.id, "t", "rw").token; | |
| 55 | } | |
| 56 | const org = createOrg(app.db, "barn", people.bob!.id); | |
| 57 | if (!org.ok) throw new Error("org"); | |
| 58 | for (const [name, permission] of [["carol", "write"], ["dave", "read"]] as const) { | |
| 59 | const team = createTeam(app.db, org.value.id, name, permission); | |
| 60 | if (!team.ok) throw new Error("team"); | |
| 61 | addTeamMember(app.db, team.value, people[name]!.id); | |
| 62 | } | |
| 63 | const hay = await createRepo(app, people.bob!, { owner: "barn", name: "hay", visibility: "public" }); | |
| 64 | if (!hay.ok) throw new Error("hay"); | |
| 65 | }, 30_000); | |
| 66 | ||
| 67 | afterAll(async () => { | |
| 68 | servers.stop(); | |
| 69 | app.close(); | |
| 70 | await rm(dataDir, { recursive: true, force: true }); | |
| 71 | }); | |
| 72 | ||
| 73 | test("three issues with different numbers land on one route pattern", async () => { | |
| 74 | for (const n of [1, 2, 3]) { | |
| 75 | const res = await fetch(`${servers.url}/alice/yard/issues/${n}`); | |
| 76 | expect(res.status).toBe(200); | |
| 77 | // the floor stays on the counted response | |
| 78 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 79 | await res.text(); | |
| 80 | } | |
| 81 | counterFor(app.db).flush(); | |
| 82 | const rows = listCounts(app.db).filter((r) => r.route.includes("issues/:number")); | |
| 83 | expect(rows).toHaveLength(1); | |
| 84 | expect(rows[0]).toMatchObject({ | |
| 85 | route: "/:owner/:name/issues/:number", | |
| 86 | method: "GET", | |
| 87 | statusClass: "2xx", | |
outdated
This passes on an empty table. Assert the row exists: one |
||
| 88 | role: "stranger", | |
| 89 | surface: "page", | |
| 90 | n: 3, | |
| 91 | }); | |
| 92 | expect(listCounts(app.db).some((r) => /\/alice\//.test(r.route))).toBe(false); | |
| 93 | }); | |
| 94 | ||
| 95 | test("an agent's API call is counted as agent/api", async () => { | |
| 96 | const res = await fetch(`${servers.url}/api/v1/repos/alice/yard`, { | |
| 97 | headers: { authorization: `Bearer ${agentToken}` }, | |
| 98 | }); | |
| 99 | expect(res.status).toBe(200); | |
| 100 | await res.text(); | |
| 101 | counterFor(app.db).flush(); | |
| 102 | const rows = listCounts(app.db).filter((r) => r.role === "agent"); | |
| 103 | expect(rows).toHaveLength(1); | |
| 104 | expect(rows[0]).toMatchObject({ surface: "api", statusClass: "2xx", n: 1 }); | |
| 105 | expect(rows[0]!.route.startsWith("/api/")).toBe(true); | |
| 106 | }); | |
| 107 | ||
| 108 | test("a path under no route is one row, never its raw path", async () => { | |
| 109 | for (const p of ["/nope/a/b/c/d", "/zzz/y/x/w/v"]) await (await fetch(`${servers.url}${p}`)).text(); | |
| 110 | counterFor(app.db).flush(); | |
| 111 | const rows = listCounts(app.db).filter((r) => r.statusClass === "4xx"); | |
| 112 | expect(rows).toHaveLength(1); | |
| 113 | expect(rows[0]).toMatchObject({ route: "(no route)", statusClass: "4xx", n: 2 }); | |
| 114 | }); | |
| 115 | ||
| 116 | /** An exec session whose peer sends a flush packet and half-closes. */ | |
| 117 | const sshExec = async (command: string) => { | |
| 118 | let eof = () => {}; | |
| 119 | let data: (d: Uint8Array) => void = () => {}; | |
| 120 | const session = { | |
| 121 | key: { fingerprint: "SHA256:nobody", line: "ssh-ed25519 AAAA" }, | |
| 122 | username: "git", | |
| 123 | remoteAddress: "203.0.113.9", | |
| 124 | kind: "exec" as const, | |
| 125 | command, | |
| 126 | env: {}, | |
| 127 | cols: 0, | |
| 128 | rows: 0, | |
| 129 | write() {}, | |
| 130 | writeStderr() {}, | |
| 131 | onData(f: (d: Uint8Array) => void) { data = f; }, | |
| 132 | onResize() {}, | |
| 133 | onEof(f: () => void) { eof = f; }, | |
| 134 | onClose() {}, | |
| 135 | exit() {}, | |
| 136 | drain: async () => {}, | |
| 137 | }; | |
| 138 | forgeSshSession(app)(session as never); | |
| 139 | // a client that asks for nothing: one flush packet, then done | |
| 140 | data(new TextEncoder().encode("0000")); | |
| 141 | eof(); | |
| 142 | await Bun.sleep(300); | |
| 143 | counterFor(app.db).flush(); | |
| 144 | }; | |
| 145 | ||
| 146 | test("an ssh exec is counted as ssh:exec:<service> under its real outcome", async () => { | |
| 147 | await sshExec("git-upload-pack '/alice/yard.git'"); | |
| 148 | const rows = listCounts(app.db).filter((r) => r.route === "ssh:exec:git-upload-pack"); | |
| 149 | expect(rows).toHaveLength(1); | |
| 150 | expect(rows[0]).toMatchObject({ surface: "ssh", role: "stranger", statusClass: "2xx", n: 1 }); | |
| 151 | }); | |
| 152 | ||
| 153 | test("each viewer role is told apart on a repository's routes", async () => { | |
| 154 | for (const who of ["alice", "bob", "carol", "dave", "erin"]) { | |
| 155 | const res = await fetch(`${servers.url}/api/v1/repos/barn/hay`, { | |
| 156 | headers: { authorization: `Bearer ${tokens[who]}` }, | |
| 157 | }); | |
| 158 | expect(res.status).toBe(200); | |
| 159 | await res.text(); | |
| 160 | } | |
| 161 | counterFor(app.db).flush(); | |
| 162 | const byRole = listCounts(app.db).filter( | |
| 163 | (r) => r.route === "/api/v1/repos/:owner/:name" && r.surface === "api" && r.role !== "agent", | |
| 164 | ); | |
| 165 | // alice: admin, bob: owner of barn, carol: writer, dave and erin: readers | |
| 166 | expect(byRole.map((r) => [r.role, r.n]).sort()).toEqual([ | |
| 167 | ["admin", 1], | |
| 168 | ["owner", 1], | |
| 169 | ["reader", 2], | |
| 170 | ["writer", 1], | |
| 171 | ]); | |
| 172 | }); | |
| 173 | ||
| 174 | test("an MCP call is counted as mcp", async () => { | |
| 175 | const res = await fetch(`${servers.url}/mcp`, { | |
| 176 | method: "POST", | |
| 177 | headers: { | |
| 178 | "content-type": "application/json", | |
| 179 | accept: "application/json, text/event-stream", | |
| 180 | authorization: `Bearer ${tokens.bob}`, | |
| 181 | }, | |
| 182 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), | |
| 183 | }); | |
| 184 | await res.text(); | |
| 185 | counterFor(app.db).flush(); | |
| 186 | const rows = listCounts(app.db).filter((r) => r.surface === "mcp"); | |
| 187 | expect(rows).toHaveLength(1); | |
| 188 | expect(rows[0]).toMatchObject({ method: "POST", role: "reader", n: 1 }); | |
| 189 | }); | |
| 190 | ||
| 191 | test("a fragment is told by ?fragment= or the x-forge-fragment header", async () => { | |
| 192 | await (await fetch(`${servers.url}/alice/yard?fragment=1`)).text(); | |
| 193 | await (await fetch(`${servers.url}/alice/yard`, { headers: { "x-forge-fragment": "1" } })).text(); | |
| 194 | counterFor(app.db).flush(); | |
| 195 | const rows = listCounts(app.db).filter((r) => r.surface === "fragment"); | |
| 196 | expect(rows.reduce((sum, r) => sum + r.n, 0)).toBe(2); | |
| 197 | expect(surfaceOf("/x", new URLSearchParams("fragment=1"))).toBe("fragment"); | |
| 198 | expect(surfaceOf("/x", new URLSearchParams(), new Headers({ "x-forge-fragment": "1" }))).toBe("fragment"); | |
| 199 | expect(surfaceOf("/x", new URLSearchParams(), new Headers({ "x-forge-fragment": "0" }))).toBe("page"); | |
| 200 | }); | |
| 201 | ||
| 202 | test("a refused push is not counted as a success", async () => { | |
| 203 | await sshExec("git-receive-pack '/alice/yard.git'"); | |
| 204 | const rows = listCounts(app.db).filter((r) => r.route === "ssh:exec:git-receive-pack"); | |
| 205 | expect(rows).toHaveLength(1); | |
| 206 | expect(rows[0]).toMatchObject({ statusClass: "4xx", role: "stranger", n: 1 }); | |
| 207 | }); | |
| 208 | ||
| 209 | test("hours older than the retention are dropped when counts are written", () => { | |
| 210 | const now = new Date("2026-10-15T12:30:00Z"); | |
| 211 | const old = new Date(now.getTime() - (RETAIN_DAYS + 1) * 86_400_000); | |
| 212 | const fresh = new Date(now.getTime() - (RETAIN_DAYS - 1) * 86_400_000); | |
| 213 | const seen = { route: "/x", method: "GET", status: 200, role: "stranger", surface: "page" } as const; | |
| 214 | let clock = old; | |
| 215 | const counter = new UsageCounter(app.db, () => clock); | |
| 216 | counter.note(seen); | |
| 217 | counter.flush(); | |
| 218 | clock = fresh; | |
| 219 | counter.note(seen); | |
| 220 | counter.flush(); | |
| 221 | expect(listCounts(app.db).filter((r) => r.route === "/x")).toHaveLength(2); | |
| 222 | clock = now; | |
| 223 | counter.note(seen); | |
| 224 | counter.flush(); | |
| 225 | const hours = listCounts(app.db) | |
| 226 | .filter((r) => r.route === "/x") | |
| 227 | .map((r) => r.hour); | |
| 228 | expect(hours).toHaveLength(2); | |
| 229 | expect(hours).not.toContain(old.toISOString().slice(0, 13) + ":00:00Z"); | |
| 230 | }); | |
| 231 | }); |
sshis declared here but nothing ever records it. The issue asks for the terminal door to be counted. Callnote({surface: "ssh", ...})wheresrc/ssh/channels.tshands off an accepted shell or exec, and add a test for it.