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

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

Closed opened this
Closed without merging

The forge now counts every answered request in a new usagecount table, one row per hour, route pattern, method, status class, viewer role and surface. bun x tsc --noEmit is clean, and the new test, test/check-list.test.ts, access-log, the router, DB, migration, server, reserved-names, app and gate tests pass.

Notes

stopped closed without shipping

opened this

The forge now counts every answered request in a new usage_count table, one row per hour, route pattern, method, status class, viewer role and surface. bun x tsc --noEmit is clean, and the new test, test/check-list.test.ts, access-log, the router, DB, migration, server, reserved-names, app and gate tests pass. I did not run the whole suite.

What changed

  • Module name: The issue names src/core/usage.ts, but that file is already the agent-run spend ledger. The counter lives in src/core/usage_count.ts instead.
  • Counting: It happens in one place, answer() in src/http/server.ts, which also covers hosted children. Security headers are untouched.
  • Router: Router.match now also returns the route's pattern. That pattern is the key, so three ids on one route are one row and the table can't outgrow the route table.
  • Role and surface: Role is anon, user, admin or agent. Surface is api (under /api/), mcp or web. An agent's API call is counted as agent/api.
  • Batching: A request costs one in-memory increment. Counts are written in one transaction after about a second or 500 keys, and on server stop, so no query is added per request. The test shows no database change before the flush.
  • Schema: Migration 89 creates the table.
  • Gate: test/usage-count.test.ts is named in GATE in scripts/gate.ts.

Left out

  • There is no page or API to read the counts yet; readUsage is the only reader.
  • /healthz and /readyz aren't counted.
  • Asset and app-subdomain proxy traffic doesn't go through answer(), so it isn't counted.
  • Paths no route claims are counted under a single (unmatched) row.
  • Rows older than 90 days are deleted the first time each process flushes.
  • No new top-level page, so nothing was added to the reserved names.
  • The test doesn't check security headers: they are added at the Bun.serve edge, not in answer(), and this change doesn't touch that code.

Try it Run bun test test/usage-count.test.ts.

Closes #1808

commented

Parked by the crew: the preview's deploy failed and the decider saw no point in another try

Sign in to join this conversation.

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs