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

Per-account quotas: repositories, apps, previews, storage, concurrent runs and checks #961

Closed opened this in answer to
Closed without merging

scout/forge:scout/657-per-account-quotas-repositories-apps-pre → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +383 −6
src/actions/apps.ts +10 −1
@@ -6,6 +6,7 @@
66 * the repository may look at it and open its environments.
77 */
88
9 import { checkCount, appsOwned, type QuotaError } from "../core/quotas.ts";
910 import { requireVerified } from "./verify.ts";
1011 import type { App } from "../app.ts";
1112 import { appsRuntime, envsFor, type EnvStatus } from "../apps/runtime.ts";
@@ -76,11 +77,18 @@ export function enableApp(
7677 actor: User | undefined,
7778 repo: Repo,
7879 input: AppSettingsInput = {},
79 ): Result<AppRecord, "not_found" | CreateAppError | "unverified"> {
80 ): Result<AppRecord, "not_found" | CreateAppError | "unverified" | QuotaError> {
8081 const admin = requireRepoAdmin(app, actor, repo);
8182 if (!admin.ok) return admin;
8283 const proven = requireVerified(app, admin.value);
8384 if (!proven.ok) return proven;
85 const roomed = checkCount(
86 app.db,
87 repo.ownerId,
88 "quota.apps",
89 appsOwned(app.db, repo.ownerId),
90 );
91 if (!roomed.ok) return roomed;
8492 const created = insertApp(app.db, {
8593 repoId: repo.id,
8694 slug: input.slug ?? slugFor(repo.name),
@@ -267,6 +275,7 @@ export interface NewAppResult {
267275 export type NewAppError =
268276 | CreateRepoActionError
269277 | CreateAppError
278 | QuotaError
270279 | "scaffold_failed"
271280 | "no_such_agent";
272281
src/actions/repos.ts +38 −2
@@ -23,6 +23,12 @@ import {
2323 type Repo,
2424 type RepoSettings,
2525 } from "../core/repos.ts";
26 import {
27 checkCount,
28 checkStorage,
29 reposOwned,
30 type QuotaError,
31 } from "../core/quotas.ts";
2632 import { commitIdentity } from "../core/commit_identity.ts";
2733 import type { User } from "../core/users.ts";
2834 import {
@@ -63,7 +69,8 @@ export interface CreateRepoInput {
6369 export type CreateRepoActionError =
6470 | CreateRepoError
6571 | "unauthorized"
66 | "forbidden_owner";
72 | "forbidden_owner"
73 | QuotaError;
6774
6875 /** Resolve the owner id for a new repo: the actor, or an org they can write to. */
6976 function resolveOwner(
@@ -79,6 +86,26 @@ function resolveOwner(
7986 return undefined;
8087 }
8188
89 /** Whether `ownerId` may hold one more repository: its count, then its bytes. */
90 async function roomFor(
91 app: App,
92 ownerId: string,
93 ): Promise<Result<true, QuotaError>> {
94 const counted = checkCount(
95 app.db,
96 ownerId,
97 "quota.repos",
98 reposOwned(app.db, ownerId),
99 );
100 if (!counted.ok) return counted;
101 return checkStorage(
102 app.db,
103 app.reposRoot,
104 app.config.dataDir,
105 ownerId,
106 );
107 }
108
82109 export async function createRepo(
83110 app: App,
84111 actor: User | undefined,
@@ -93,6 +120,8 @@ export async function createRepo(
93120 if (user.value.kind === "agent") return err("forbidden_owner");
94121 const ownerId = resolveOwner(app, user.value, input.owner ?? "");
95122 if (ownerId === undefined) return err("forbidden_owner");
123 const roomed = await roomFor(app, ownerId);
124 if (!roomed.ok) return roomed;
96125 const created = await initRepo(app.db, app.reposRoot, {
97126 ownerId,
98127 name: input.name,
@@ -113,11 +142,18 @@ export async function forkRepo(
113142 actor: User | undefined,
114143 parent: Repo,
115144 name?: string,
116 ): Promise<Result<Repo, ForkRepoError | "not_found" | "unauthorized" | "unverified">> {
145 ): Promise<
146 Result<
147 Repo,
148 ForkRepoError | "not_found" | "unauthorized" | "unverified" | QuotaError
149 >
150 > {
117151 const user = requireParticipant(app, actor, parent);
118152 if (!user.ok) return user;
119153 const proven = requireVerified(app, user.value);
120154 if (!proven.ok) return proven;
155 const roomed = await roomFor(app, user.value.id);
156 if (!roomed.ok) return roomed;
121157 const forked = await cloneRepo(
122158 app.db,
123159 app.reposRoot,
src/apps/runtime.ts +47
@@ -61,6 +61,7 @@ import {
6161 SAMPLE_SPAN_MS,
6262 type Placement,
6363 } from "../core/meter.ts";
64 import { checkCount, quotaMessage } from "../core/quotas.ts";
6465 import { dirBytes } from "./bytes.ts";
6566 import { BUSY_WORDS, busyReason, type BusyReason } from "./busy.ts";
6667 import { exportTree, readFileAt } from "./checkout.ts";
@@ -880,6 +881,32 @@ export class AppsRuntime {
880881
881882 // ---- deploying ----
882883
884 /**
885 * Why a preview of this app may not start now: the owner already has as
886 * many previews held (live, asleep, deploying or waiting) as its limit
887 * allows. An environment already held is never refused, and production
888 * is not a preview.
889 */
890 private previewRefusal(
891 record: AppRecord,
892 repo: Repo,
893 env: EnvName,
894 ): string | undefined {
895 if (env === "production") return undefined;
896 let held = 0;
897 for (const state of this.envs.values()) {
898 if (state.env === "production") continue;
899 const owner = getRepoById(this.app.db, state.app.repoId)?.ownerId;
900 if (owner !== repo.ownerId) continue;
901 const here = state.live ?? state.asleep ?? state.deploying ?? state.queued;
902 if (here === undefined) continue;
903 if (state.app.id === record.id && state.env === env) return undefined;
904 held++;
905 }
906 const verdict = checkCount(this.app.db, repo.ownerId, "quota.previews", held);
907 return verdict.ok ? undefined : quotaMessage(verdict.error);
908 }
909
883910 /**
884911 * Ask for `env` to run `commitOid`. Returns the run that will do it — or
885912 * the one already serving that commit, when nothing needs to happen.
@@ -913,6 +940,26 @@ export class AppsRuntime {
913940 }
914941 const issue =
915942 env === "production" ? undefined : this.pullIssueId(repo, env);
943 // A preview past the owner's limit is refused where it would start, and
944 // the refusal is the run's own line on the pull (#657).
945 const refused = this.previewRefusal(record, repo, env);
946 if (refused !== undefined) {
947 const run = createRun(this.app.db, {
948 repoId: repo.id,
949 kind: "deploy",
950 env,
951 commitOid,
952 reason,
953 ...(issue === undefined ? {} : { issueId: issue }),
954 ...(actorId === undefined ? {} : { actorId }),
955 });
956 const done = finishRun(this.app.db, run.id, {
957 state: "failed",
958 summary: refused,
959 });
960 announceRun(this.app, done ?? run, actorId);
961 return done ?? run;
962 }
916963 const run = createRun(this.app.db, {
917964 repoId: repo.id,
918965 kind: "deploy",
src/checks/service.ts +24 −1
@@ -11,6 +11,7 @@
1111 * is that command's business.
1212 */
1313
14 import { mayStart, ownedRuns, quotaMessage } from "../core/quotas.ts";
1415 import { existsSync, mkdirSync, rmSync } from "node:fs";
1516 import { tmpdir } from "node:os";
1617 import { join } from "node:path";
@@ -244,13 +245,35 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
244245 * opens up. Claiming is what decides between two forges, so calling this
245246 * from both never runs the same check twice.
246247 */
248 /**
249 * Whether the owner of this check's repository has a slot: past
250 * `quota.checks` it waits, and its card says why (#657).
251 */
252 function withinQuota(run: Run): boolean {
253 const owner = getRepoById(app.db, run.repoId)?.ownerId;
254 if (owner === undefined) return true;
255 const verdict = mayStart(
256 app.db,
257 owner,
258 "check",
259 ownedRuns(app.db, owner, inFlight.keys()),
260 );
261 if (verdict.ok) return true;
262 const words = `waiting: ${quotaMessage(verdict.error)}`;
263 if (run.summary !== words) noteRunProgress(app.db, run.id, { summary: words });
264 return false;
265 }
266
247267 function schedule(): void {
248268 if (stopped) return;
249269 const limit = capacity();
250270 gate.resize(limit);
251271 while (inFlight.size < limit) {
252272 const queued = listActive(app.db, "check").filter(
253 (run) => run.state === "queued" && !inFlight.has(run.id),
273 (run) =>
274 run.state === "queued" &&
275 !inFlight.has(run.id) &&
276 withinQuota(run),
254277 );
255278 const next = pickNext(queued);
256279 if (!next) return;
src/core/capacity.ts +31 −1
@@ -17,7 +17,17 @@ export type CapacityKey =
1717 | "crew.concurrency"
1818 | "checks.concurrency"
1919 | "checks.shards"
20 | "cells.egress";
20 | "cells.egress"
21 | QuotaKey;
22
23 /** Per-account limits (#657), set here like the rest; see `core/quotas.ts`. */
24 export type QuotaKey =
25 | "quota.repos"
26 | "quota.apps"
27 | "quota.previews"
28 | "quota.storage"
29 | "quota.runs"
30 | "quota.checks";
2131
2232 interface Definition {
2333 /** What the settings page and the API call it. */
@@ -33,6 +43,19 @@ interface Definition {
3343 readonly help: string;
3444 }
3545
46 const quota = (
47 label: string,
48 env: string,
49 fallback: string,
50 help: string,
51 ): Definition => ({
52 label,
53 env,
54 kind: { type: "count", min: 1, max: 1_000_000 },
55 fallback,
56 help: `${help} Per account; a forge admin's own account is not limited.`,
57 });
58
3659 export const CAPACITY: Record<CapacityKey, Definition> = {
3760 "crew.concurrency": {
3861 label: "Crew runs at once",
@@ -62,6 +85,13 @@ export const CAPACITY: Record<CapacityKey, Definition> = {
6285 fallback: "enforce",
6386 help: "enforce refuses a host an app or check did not declare; report lets it through on 80 and 443 and lists it on the app's page. Takes effect on the next cell started.",
6487 },
88
89 "quota.repos": quota("Repositories per account", "FORGE_QUOTA_REPOS", "20", "How many repositories one account may own."),
90 "quota.apps": quota("Apps per account", "FORGE_QUOTA_APPS", "10", "How many apps one account may own."),
91 "quota.previews": quota("Live previews per account", "FORGE_QUOTA_PREVIEWS", "5", "How many pull previews of one account's apps may be deployed at once."),
92 "quota.storage": quota("Storage per account (MB)", "FORGE_QUOTA_STORAGE_MB", "2048", "Repository bytes plus app-data bytes, in megabytes; a create or push past it is refused."),
93 "quota.runs": quota("Concurrent crew runs per account", "FORGE_QUOTA_RUNS", "2", "How many agent runs on one account's repositories go at once; the rest wait."),
94 "quota.checks": quota("Concurrent checks per account", "FORGE_QUOTA_CHECKS", "1", "How many checks on one account's repositories run at once; the rest wait."),
6595 };
6696
6797 export const CAPACITY_KEYS = Object.keys(CAPACITY) as CapacityKey[];
src/core/quotas.ts added +186
@@ -0,0 +1,186 @@
1 /**
2 * Per-account quotas (#657): how much of the forge one account may hold.
3 * The limits are capacity settings (`core/capacity.ts`, `quota.*`) a forge
4 * admin changes live; this module counts what an account has and says no
5 * past the limit, naming the limit and the count — the same words on every
6 * surface. A forge admin's own account is never limited. Pure reads; the
7 * callers are the boundaries that create or start something.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { dirBytes } from "../apps/bytes.ts";
12 import { appsRoot, envDataDir, isEnvName } from "../apps/data.ts";
13 import { repoDir } from "../git/repos.ts";
14 import { err, ok, type Result } from "../kernel/result.ts";
15 import { capacityCount, type QuotaKey } from "./capacity.ts";
16 import { readdirSync } from "node:fs";
17 import { join } from "node:path";
18
19 /** A refusal, as the one line every surface shows. */
20 export type QuotaError = `quota_exceeded: ${string}`;
21
22 export const isQuotaError = (error: unknown): error is QuotaError =>
23 typeof error === "string" && error.startsWith("quota_exceeded: ");
24
25 /** The words after `quota_exceeded: `, for a page or a message. */
26 export const quotaMessage = (error: QuotaError): string =>
27 error.slice("quota_exceeded: ".length);
28
29 const NOUN: Record<QuotaKey, string> = {
30 "quota.repos": "repositories",
31 "quota.apps": "apps",
32 "quota.previews": "live previews",
33 "quota.storage": "MB of storage",
34 "quota.runs": "concurrent runs",
35 "quota.checks": "concurrent checks",
36 };
37
38 /** The limit on `key` now; 0 means unlimited (an admin's account). */
39 export function limitFor(db: Database, accountId: string, key: QuotaKey): number {
40 const row = db
41 .query<{ is_admin: number }, [string]>(
42 "SELECT is_admin FROM user WHERE id = ?1",
43 )
44 .get(accountId);
45 if (row?.is_admin === 1) return 0;
46 return capacityCount(db, key, 1);
47 }
48
49 /** Refuse when `used` has reached the limit: one more would pass it. */
50 export function checkCount(
51 db: Database,
52 accountId: string,
53 key: QuotaKey,
54 used: number,
55 ): Result<true, QuotaError> {
56 const limit = limitFor(db, accountId, key);
57 if (limit === 0 || used < limit) return ok(true);
58 return err(
59 `quota_exceeded: this account has ${used} of ${limit} ${NOUN[key]} (${key})`,
60 );
61 }
62
63 /** How many of `runIds` belong to a repository `accountId` owns. */
64 export function ownedRuns(
65 db: Database,
66 accountId: string,
67 runIds: Iterable<string>,
68 ): number {
69 let n = 0;
70 for (const runId of runIds)
71 if (
72 db
73 .query<{ x: number }, [string, string]>(
74 `SELECT 1 AS x FROM run JOIN repo ON repo.id = run.repo_id
75 WHERE run.id = ?1 AND repo.owner_id = ?2`,
76 )
77 .get(runId, accountId) !== null
78 )
79 n++;
80 return n;
81 }
82
83 const count = (db: Database, sql: string, id: string): number =>
84 db.query<{ n: number }, [string]>(sql).get(id)?.n ?? 0;
85
86 export const reposOwned = (db: Database, id: string): number =>
87 count(db, "SELECT COUNT(*) AS n FROM repo WHERE owner_id = ?1", id);
88
89 export const appsOwned = (db: Database, id: string): number =>
90 count(
91 db,
92 "SELECT COUNT(*) AS n FROM app JOIN repo ON repo.id = app.repo_id WHERE repo.owner_id = ?1",
93 id,
94 );
95
96 /** Agent or check runs of the account's repositories that are running now. */
97 export function runningFor(
98 db: Database,
99 accountId: string,
100 kind: "agent" | "check",
101 ): number {
102 return (
103 db
104 .query<{ n: number }, [string, string]>(
105 `SELECT COUNT(*) AS n FROM run JOIN repo ON repo.id = run.repo_id
106 WHERE run.state = 'running' AND run.kind = ?1 AND repo.owner_id = ?2`,
107 )
108 .get(kind, accountId)?.n ?? 0
109 );
110 }
111
112 /**
113 * Whether another run of `kind` for this account may start now. `flying` is
114 * how many of its runs this process has taken but not yet marked running —
115 * a claim is not instant, so the table alone would let two slip through.
116 */
117 export function mayStart(
118 db: Database,
119 accountId: string,
120 kind: "agent" | "check",
121 flying = 0,
122 ): Result<true, QuotaError> {
123 return checkCount(
124 db,
125 accountId,
126 kind === "agent" ? "quota.runs" : "quota.checks",
127 Math.max(runningFor(db, accountId, kind), flying),
128 );
129 }
130
131 /** Bytes the account holds: its repositories plus every environment's data. */
132 export async function storageBytes(
133 db: Database,
134 reposRoot: string,
135 dataDir: string,
136 accountId: string,
137 ): Promise<number> {
138 const repos = db
139 .query<{ id: string; name: string; owner_name: string }, [string]>(
140 `SELECT repo.id, repo.name, user.username AS owner_name
141 FROM repo JOIN user ON user.id = repo.owner_id WHERE repo.owner_id = ?1`,
142 )
143 .all(accountId);
144 let total = 0;
145 for (const repo of repos) {
146 total += await dirBytes(repoDir(reposRoot, repo.owner_name, repo.name));
147 const app = db
148 .query<{ id: string }, [string]>("SELECT id FROM app WHERE repo_id = ?1")
149 .get(repo.id);
150 if (!app) continue;
151 let names: string[] = [];
152 try {
153 names = readdirSync(join(appsRoot(dataDir), app.id));
154 } catch {
155 // never deployed
156 }
157 for (const name of names)
158 if (isEnvName(name))
159 total += await dirBytes(envDataDir(dataDir, app.id, name));
160 }
161 return total;
162 }
163
164 /**
165 * Refuse a create or push that would take the account past its storage
166 * limit: what it holds now plus `incoming` bytes (a push's declared size).
167 */
168 export async function checkStorage(
169 db: Database,
170 reposRoot: string,
171 dataDir: string,
172 accountId: string,
173 incoming = 0,
174 ): Promise<Result<true, QuotaError>> {
175 const limit = limitFor(db, accountId, "quota.storage");
176 if (limit === 0) return ok(true);
177 const used = await storageBytes(db, reposRoot, dataDir, accountId);
178 const max = limit * 1024 * 1024;
179 if (used + incoming <= max && used < max) return ok(true);
180 const mb = (n: number): string => (n / 1024 / 1024).toFixed(1);
181 return err(
182 `quota_exceeded: this account holds ${mb(used)} of ${limit} MB of storage${
183 incoming > 0 ? `, and this adds ${mb(incoming)} MB` : ""
184 } (quota.storage)`,
185 );
186 }
src/core/runs.ts +4 −1
@@ -306,10 +306,12 @@ export function noteRunProgress(
306306 subscriptionId?: string | undefined;
307307 /** Whether the shell is held to the sandbox, and why not when it is not. */
308308 sandbox?: { enforced: boolean; note: string } | undefined;
309 /** What the card says, for a run that has not started. */
310 summary?: string | undefined;
309311 },
310312 ): void {
311313 db.query(
312 `UPDATE run SET session_id = COALESCE(?2, session_id), cost_usd = COALESCE(?3, cost_usd),
314 `UPDATE run SET summary = COALESCE(?8, summary), session_id = COALESCE(?2, session_id), cost_usd = COALESCE(?3, cost_usd),
313315 branch = COALESCE(?4, branch), subscription_id = COALESCE(?5, subscription_id),
314316 sandbox_enforced = COALESCE(?6, sandbox_enforced),
315317 sandbox_note = COALESCE(?7, sandbox_note)
@@ -322,6 +324,7 @@ export function noteRunProgress(
322324 progress.subscriptionId ?? null,
323325 progress.sandbox === undefined ? null : progress.sandbox.enforced ? 1 : 0,
324326 progress.sandbox?.note.slice(0, 300) ?? null,
327 progress.summary?.slice(0, 300) ?? null,
325328 );
326329 }
327330
src/crew/dispatch.ts +16
@@ -8,6 +8,7 @@
88 * time. A missed wake-up costs a tick, never a run.
99 */
1010
11 import { mayStart, ownedRuns, quotaMessage } from "../core/quotas.ts";
1112 import { capacityCount } from "../core/capacity.ts";
1213 import { tmpdir } from "node:os";
1314 import { emailVerified } from "../core/verify.ts";
@@ -956,6 +957,21 @@ function pump(
956957 if (queued.issueId !== null && runningIssues.has(queued.issueId)) continue;
957958 const fresh = getRun(app.db, queued.id);
958959 if (!fresh || fresh.state !== "queued") continue;
960 // The account's own limit on runs at once (#657): past it the run
961 // waits, with the reason on its card, and the next one is looked at.
962 const owner = getRepoById(app.db, fresh.repoId)?.ownerId;
963 const room =
964 owner === undefined ? undefined : mayStart(
965 app.db,
966 owner,
967 "agent",
968 ownedRuns(app.db, owner, inFlight.keys()),
969 );
970 if (room !== undefined && !room.ok) {
971 const words = `waiting: ${quotaMessage(room.error)}`;
972 if (fresh.summary !== words) noteRunProgress(app.db, fresh.id, { summary: words });
973 continue;
974 }
959975 slots--;
960976 if (queued.issueId !== null) runningIssues.add(queued.issueId);
961977 const running = executeAgentRun(app, fresh, options)
src/http/respond.ts +3
@@ -4,6 +4,7 @@
44 * before it reaches an action.
55 */
66
7 import { isQuotaError, quotaMessage } from "../core/quotas.ts";
78 import { bodyCapFor, readBounded } from "./limits.ts";
89 import { scopeAllows, type TokenScope } from "../core/tokens.ts";
910 import type { User } from "../core/users.ts";
@@ -148,6 +149,8 @@ export function respondAccess(error: string, status: number): Response {
148149 // same words on every surface (\`actions/verify.ts\`).
149150 if (error === "unverified")
150151 return json({ error, message: "verify your email first" }, 403);
152 if (isQuotaError(error))
153 return json({ error: "quota_exceeded", message: quotaMessage(error) }, 403);
151154 if (error === "unauthorized") return unauthorized();
152155 if (error === "forbidden") return forbidden();
153156 return json({ error }, status);
src/http/server.ts +24
@@ -30,6 +30,7 @@ import {
3030 } from "./limits.ts";
3131 import { canRead, canWrite, getRepo, getRepoById } from "../core/repos.ts";
3232 import { trackPullHead } from "../core/pulls.ts";
33 import { checkStorage, isQuotaError, quotaMessage } from "../core/quotas.ts";
3334 import { createRepo } from "../actions/repos.ts";
3435 import { sessionOf } from "../core/sessions.ts";
3536 import { scopeAllows, verifyToken } from "../core/tokens.ts";
@@ -1098,6 +1099,11 @@ async function withGitAccess(
10981099 visibility: "private",
10991100 });
11001101 if (created.ok) repo = created.value;
1102 else if (isQuotaError(created.error))
1103 return new Response(quotaMessage(created.error) + "\n", {
1104 status: 403,
1105 headers: { "content-type": "text/plain; charset=utf-8" },
1106 });
11011107 }
11021108
11031109 // Anonymous callers get a challenge wherever credentials could help;
@@ -1111,6 +1117,24 @@ async function withGitAccess(
11111117 ) {
11121118 return notFound();
11131119 }
1120 // The push itself, not the ref advertisement before it: what the owner
1121 // holds now plus what the body declares must fit (#657). A chunked body
1122 // declares nothing, so it is held to what the owner already holds.
1123 if (ctx.request.method === "POST") {
1124 const declared = Number(ctx.request.headers.get("content-length"));
1125 const room = await checkStorage(
1126 ctx.app.db,
1127 ctx.app.reposRoot,
1128 ctx.app.config.dataDir,
1129 repo.ownerId,
1130 Number.isFinite(declared) && declared > 0 ? declared : 0,
1131 );
1132 if (!room.ok)
1133 return new Response(quotaMessage(room.error) + "\n", {
1134 status: 403,
1135 headers: { "content-type": "text/plain; charset=utf-8" },
1136 });
1137 }
11141138 } else {
11151139 if (!canRead(ctx.app.db, repo, ctx.auth.user))
11161140 return ctx.auth.user ? notFound() : gitChallenge();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs