Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

184 lines · 12.7 KBRaw History
1import { describe, expect, it } from "vitest";
2import { checkRepositoryQuota, checkStorageQuota, DEFAULT_QUOTAS, endCompute, fleetLimits, HOSTED_JOBS_LIMIT, mayStart, monthStart, quotasFor, setQuotas, startCompute, storageRefusal, storedBytes, usageOf } from "../../src/lib/quotas.js";
3import type { Env } from "../../src/env.js";
4import { testD1 } from "./stubs/d1.js";
5
6const at = "2026-10-01T00:00:00.000Z";
7
8function setup(vars: Record<string, string> = {}) {
9 const DB = testD1();
10 const add = (id: string, kind: string, siteAdmin = 0) => DB.sqlite.prepare("INSERT INTO accounts (id, login, kind, status, site_admin, created_at) VALUES (?, ?, ?, 'active', ?, ?)").run(id, id, kind, siteAdmin, at);
11 add("ann", "user");
12 add("root", "user", 1);
13 add("acme", "org");
14 add("ops", "org");
15 DB.sqlite.prepare("INSERT INTO org_members (org_id, user_id, role, created_at) VALUES ('acme', 'ann', 'owner', ?), ('ops', 'root', 'owner', ?)").run(at, at);
16 const usage = (id: string, account: string, kind: "job" | "sandbox", start: string, end: string | null) =>
17 DB.sqlite.prepare("INSERT INTO compute_usage (id, account_id, repo_id, kind, started_at, ended_at) VALUES (?, ?, 'r', ?, ?, ?)").run(id, account, kind, start, end);
18 return { env: { DB, ...vars } as unknown as Env, DB, usage };
19}
20
21describe("quotas", () => {
22 it("uses the defaults, the environment's, then a site administrator's override", async () => {
23 const { env } = setup();
24 expect(await quotasFor(env, "ann")).toEqual({ ...DEFAULT_QUOTAS, exempt: false });
25 const fromEnv = setup({ QUOTA_HOSTED_MINUTES: "120", QUOTA_SANDBOXES: "junk" }).env;
26 expect((await quotasFor(fromEnv, "ann")).hosted_minutes).toBe(120);
27 expect((await quotasFor(fromEnv, "ann")).sandboxes).toBe(DEFAULT_QUOTAS.sandboxes);
28 await setQuotas(env, "ann", { hosted_jobs: 1, repositories: -1 }, "root");
29 await setQuotas(env, "ann", { hosted_minutes: 10 }, "root");
30 expect(await quotasFor(env, "ann")).toEqual({ ...DEFAULT_QUOTAS, hosted_jobs: 1, repositories: -1, hosted_minutes: 10, exempt: false });
31 await setQuotas(env, "ann", { hosted_jobs: null }, "root");
32 expect((await quotasFor(env, "ann")).hosted_jobs).toBe(DEFAULT_QUOTAS.hosted_jobs);
33 await expect(setQuotas(env, "ann", { storage: 1 } as never, "root")).rejects.toThrow(/unknown quota storage/);
34 await expect(setQuotas(env, "ann", { hosted_jobs: -5 }, "root")).rejects.toThrow(/whole number/);
35 });
36
37 it("doesn't limit accounts run by a site administrator", async () => {
38 const { env } = setup();
39 expect((await quotasFor(env, "root")).exempt).toBe(true);
40 expect((await quotasFor(env, "ops")).exempt).toBe(true);
41 expect((await quotasFor(env, "acme")).exempt).toBe(false);
42 });
43
44 it("counts this month's minutes and what is running now", async () => {
45 const { env, usage } = setup();
46 const now = new Date("2026-10-13T12:00:00.000Z");
47 usage("j1", "acme", "job", "2026-10-13T10:00:00.000Z", "2026-10-13T10:10:30.000Z"); // 11 minutes (rounded up)
48 usage("j2", "acme", "job", "2026-10-13T11:30:00.000Z", null); // running: 30 minutes so far
49 usage("s1", "acme", "sandbox", "2026-10-13T11:00:00.000Z", null); // open: 60 minutes
50 usage("j3", "acme", "job", "2026-09-30T23:50:00.000Z", "2026-10-01T00:20:00.000Z"); // 20 of its minutes are this month's
51 usage("j4", "acme", "job", "2026-09-10T10:00:00.000Z", "2026-09-10T11:00:00.000Z"); // last month
52 usage("j5", "acme", "job", "2026-10-12T00:00:00.000Z", null); // lost its end: counted as ended after 7 hours
53 usage("j6", "ann", "job", "2026-10-13T11:00:00.000Z", null); // someone else's
54 expect(await usageOf(env, "acme", now)).toEqual({ hosted_minutes: 11 + 30 + 60 + 20 + 420, hosted_jobs: 1, sandboxes: 1, repositories: 0, storage_bytes: 0 });
55 expect(monthStart(now)).toBe("2026-10-01T00:00:00.000Z");
56 });
57
58 it("refuses work past the minutes, holds jobs past the running jobs, and refuses sandboxes past theirs", async () => {
59 const { env } = setup();
60 await setQuotas(env, "acme", { hosted_jobs: 1, sandboxes: 1 }, "root");
61 expect(await mayStart(env, "acme", "job")).toEqual({ ok: true });
62 await startCompute(env, { id: "job-a", accountId: "acme", repoId: "r", kind: "job" });
63 expect(await mayStart(env, "acme", "job")).toMatchObject({ ok: false, wait: true });
64 await endCompute(env, "job-a");
65 await endCompute(env, "job-a");
66 expect(await mayStart(env, "acme", "job")).toEqual({ ok: true });
67 await startCompute(env, { id: "sb", accountId: "acme", repoId: "r", kind: "sandbox" });
68 expect(await mayStart(env, "acme", "sandbox")).toMatchObject({ ok: false, wait: false, message: expect.stringMatching(/already has 1 agent sandboxes open/) });
69 // A job still starts: sandboxes and jobs have their own counts.
70 expect(await mayStart(env, "acme", "job")).toEqual({ ok: true });
71 await setQuotas(env, "acme", { hosted_minutes: 0 }, "root");
72 for (const kind of ["job", "sandbox"] as const) expect(await mayStart(env, "acme", kind)).toMatchObject({ ok: false, wait: false, message: expect.stringMatching(/used its 0 hosted minutes for this month/) });
73 // The administrator's own organization is never held up.
74 await setQuotas(env, "ops", { hosted_minutes: 0 }, "root");
75 expect(await mayStart(env, "ops", "job")).toEqual({ ok: true });
76 });
77
78 it("holds every account, exempt ones too, to half the fleet, and the fleet to its limit", async () => {
79 expect(fleetLimits({} as Env)).toEqual({ total: HOSTED_JOBS_LIMIT, share: HOSTED_JOBS_LIMIT / 2 });
80 expect(fleetLimits({ HOSTED_JOBS_LIMIT: "9" } as Env)).toEqual({ total: 9, share: 4 });
81 for (const junk of ["", "1", "-1", "lots"]) expect(fleetLimits({ HOSTED_JOBS_LIMIT: junk } as Env).total).toBe(HOSTED_JOBS_LIMIT);
82 const { env, usage } = setup({ HOSTED_JOBS_LIMIT: "6" });
83 const recent = new Date(Date.now() - 60_000).toISOString();
84 await setQuotas(env, "acme", { hosted_jobs: -1 }, "root");
85 // ops is run by a site administrator: no quota of its own, but still half the fleet (3 of 6).
86 for (const id of ["o1", "o2"]) usage(id, "ops", "job", recent, null);
87 expect(await mayStart(env, "ops", "job")).toEqual({ ok: true });
88 usage("o3", "ops", "job", recent, null);
89 expect(await mayStart(env, "ops", "job")).toMatchObject({ ok: false, wait: true, message: expect.stringMatching(/one account runs at most 3 at once, half of this Diffinery's hosted runners/) });
90 // A sandbox isn't a job: the fleet's limits don't apply to it.
91 expect(await mayStart(env, "ops", "sandbox")).toEqual({ ok: true });
92 // acme, with no limit of its own, gets the other half; then the fleet is full for anyone.
93 for (const id of ["a1", "a2"]) usage(id, "acme", "job", recent, null);
94 expect(await mayStart(env, "acme", "job")).toEqual({ ok: true });
95 usage("a3", "acme", "job", recent, null);
96 expect(await mayStart(env, "ann", "job")).toMatchObject({ ok: false, wait: true, message: expect.stringMatching(/all 6 of this Diffinery's hosted runners are busy/) });
97 // A job that ends frees its place, and a row left open past a job's longest run no longer counts.
98 await endCompute(env, "o3");
99 expect(await mayStart(env, "ann", "job")).toEqual({ ok: true });
100 expect(await mayStart(env, "ops", "job")).toEqual({ ok: true });
101 usage("stale", "ann", "job", new Date(Date.now() - 8 * 3600_000).toISOString(), null);
102 expect(await mayStart(env, "ann", "job")).toEqual({ ok: true });
103 });
104
105 it("caps the repositories an account owns", async () => {
106 const { env, DB } = setup();
107 await setQuotas(env, "ann", { repositories: 1 }, "root");
108 await checkRepositoryQuota(env, "ann", "ann");
109 DB.sqlite.prepare("INSERT INTO repos (id, owner_id, name, description, visibility, default_branch, created_at, updated_at) VALUES ('r1', 'ann', 'one', '', 'private', 'main', ?, ?)").run(at, at);
110 await expect(checkRepositoryQuota(env, "ann", "ann")).rejects.toThrow(/ann has reached its limit of 1 repositories/);
111 await setQuotas(env, "ann", { repositories: -1 }, "root");
112 await checkRepositoryQuota(env, "ann", "ann");
113 });
114});
115
116describe("storage quota", () => {
117 /** acme's repositories r1 (reported 1000 bytes) and r2 (never measured), ann's r3; `measured` lists the repositories asked to report. */
118 function storage(vars: Record<string, string> = {}) {
119 const s = setup(vars);
120 const repo = (id: string, owner: string) => s.DB.sqlite.prepare("INSERT INTO repos (id, owner_id, name, description, visibility, default_branch, created_at, updated_at) VALUES (?, ?, ?, '', 'private', 'main', ?, ?)").run(id, owner, id, at, at);
121 const report = (id: string, bytes: number) => s.DB.sqlite.prepare("INSERT INTO repo_storage (repo_id, bytes, updated_at) VALUES (?, ?, ?) ON CONFLICT(repo_id) DO UPDATE SET bytes = excluded.bytes").run(id, bytes, at);
122 repo("r1", "acme");
123 repo("r2", "acme");
124 repo("r3", "ann");
125 report("r1", 1000);
126 report("r3", 5000);
127 const measured: string[] = [];
128 // A repository asked to report writes its row, as RepoDO.reportStorage does.
129 const REPO = { idFromName: (id: string) => id, get: (id: string) => ({ reportStorage: async () => (measured.push(id), report(id, 200)) }) };
130 const env = { ...s.env, REPO } as unknown as Env;
131 return { ...s, env, repo, report, measured };
132 }
133
134 it("is 10 GB by default, from QUOTA_STORAGE_BYTES, or a site administrator's override up to 1 PiB", async () => {
135 expect(DEFAULT_QUOTAS.storage_bytes).toBe(10 * 1024 ** 3);
136 const { env } = storage();
137 expect((await quotasFor(env, "acme")).storage_bytes).toBe(10 * 1024 ** 3);
138 expect((await quotasFor(storage({ QUOTA_STORAGE_BYTES: "2048" }).env, "acme")).storage_bytes).toBe(2048);
139 await setQuotas(env, "acme", { storage_bytes: 100 * 1024 ** 4 }, "root");
140 expect((await quotasFor(env, "acme")).storage_bytes).toBe(100 * 1024 ** 4);
141 await expect(setQuotas(env, "acme", { storage_bytes: 2 ** 51 }, "root")).rejects.toThrow(/whole number/);
142 expect((await quotasFor(env, "root")).storage_bytes).toBe(-1);
143 });
144
145 it("adds up the account's repositories, measuring those that never reported, and its packages", async () => {
146 const { env, DB, measured } = storage();
147 // r2 never reported: it is asked once, then its report counts.
148 expect(await storedBytes(env, "acme")).toBe(1000 + 200);
149 expect(measured).toEqual(["r2"]);
150 expect(await storedBytes(env, "acme")).toBe(1200);
151 expect(measured).toEqual(["r2"]);
152 // A repository counting its own bytes replaces its report.
153 expect(await storedBytes(env, "acme", { repoId: "r1", bytes: 1500 })).toBe(1500 + 200);
154 // Packages: each blob once however many of the account's packages use it, plus the manifests.
155 const p = (id: string, owner: string) => DB.sqlite.prepare("INSERT INTO packages (id, owner_id, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)").run(id, owner, id, at, at);
156 p("p1", "acme");
157 p("p2", "acme");
158 p("p3", "ann");
159 DB.sqlite.prepare("INSERT INTO registry_blobs (digest, size, r2_key, created_at) VALUES ('sha256:a', 300, 'k1', ?), ('sha256:b', 40, 'k2', ?)").run(at, at);
160 DB.sqlite.prepare("INSERT INTO package_blobs (package_id, digest, created_at) VALUES ('p1', 'sha256:a', ?), ('p2', 'sha256:a', ?), ('p3', 'sha256:b', ?)").run(at, at, at);
161 DB.sqlite.prepare("INSERT INTO package_manifests (package_id, digest, media_type, size, created_at) VALUES ('p1', 'sha256:m', 'x', 7, ?)").run(at);
162 expect(await storedBytes(env, "acme")).toBe(1200 + 300 + 7);
163 expect(await storedBytes(env, "ann")).toBe(5000 + 40);
164 expect((await usageOf(env, "acme")).storage_bytes).toBe(1507);
165 // A deleted repository's report goes with it.
166 DB.sqlite.prepare("DELETE FROM repos WHERE id = 'r1'").run();
167 expect(await storedBytes(env, "acme")).toBe(507);
168 });
169
170 it("refuses a write that would take the account past its quota, naming the account and the limit", async () => {
171 const { env } = storage();
172 await setQuotas(env, "acme", { storage_bytes: 1300 }, "root");
173 expect(await storageRefusal(env, "acme", "acme", 100)).toBeNull();
174 expect(await storageRefusal(env, "acme", "acme", 101)).toMatch(/^acme has reached its storage limit of 1300 bytes/);
175 await expect(checkStorageQuota(env, "acme", "acme", 101)).rejects.toThrow(/403: acme has reached its storage limit of 1300 bytes/);
176 // The repository's own count, fresher than its report, decides.
177 expect(await storageRefusal(env, "acme", "acme", 0, { repoId: "r1", bytes: 1200 })).toMatch(/storage limit/);
178 await setQuotas(env, "acme", { storage_bytes: -1 }, "root");
179 expect(await storageRefusal(env, "acme", "acme", 1e12)).toBeNull();
180 // Accounts run by a site administrator have no limit.
181 await setQuotas(env, "ops", { storage_bytes: 0 }, "root");
182 expect(await storageRefusal(env, "ops", "ops", 1e12)).toBeNull();
183 });
184});