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

Big blobs from the bucket: blobs over a policy size (default 10 MB) written to the BlobStore by OID, served by presigned URL #16651

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/4490-big-blobs-from-the-bucket-blobs-over-a-p → main 0 commits fork 7 threads · 7 unresolved

  • Merged. scout/4490-big-blobs-from-the-bucket-blobs-over-a-p was merged into main as a26f6b8.

Review

Sign in to review this change.
16 files changed +669 −3
docs/BLOBS.md +5 −2
@@ -42,8 +42,11 @@ refused. So is a range that is not whole, non-negative bytes in order, and
4242 a presign that is not a GET or PUT valid for 1 s to 7 days. The bucket's
4343 secret never appears in a presigned URL; only its signature does.
4444
45 ## Big git blobs
46
47 Blobs over a size policy are copied here by object id after a push and served by presigned URL: `docs/features/large-files.md`.
48
4549 ## Not here yet
4650
47 Archiving finished run logs and attachments onto the store, big git blobs
48 by OID and the cold-tier lifecycle are later steps of #4481, each with
51 Archiving finished run logs and attachments onto the store and the cold-tier lifecycle are later steps of #4481, each with
4952 its own issue.
docs/features/large-files.md added +22
@@ -0,0 +1,22 @@
1 ---
2 topic: Your apps
3 row: Large files: blobs over a size policy, kept in the BlobStore by object id
4 ---
5 # Large files
6
7 A blob over the policy size (10 MB; set `FORGE_LARGE_BLOB_BYTES` to a whole number of bytes, 1024 or more; `off` stops the offload) is copied to the BlobStore after a push, under `large/<owner>/<name>/<oid>`. Git keeps its own copy, so a clone, a fetch and history are unchanged. The store is the bucket when `S3_*` is set, else a directory under the forge's data.
8
9 ## See them
10
11 - Page: `/<owner>/<name>/large` reads the list the offload job saved after the last push (no scan on a request) and lists each blob, largest first: its path on the default branch, its size, its object id, and where it lives (`git`, or `git and store`).
12 - Terminal: open a repository, then the palette's "Large files" (`src/tui/screens/largefiles.ts`); `g` reads again.
13
14 ## Download one
15
16 `/<owner>/<name>/large/<oid>` (saved as the file's own name, else the oid) redirects to a presigned bucket address valid for 5 minutes, or streams the bytes when the store is a directory. Only an oid the store holds is served, and only to someone who can read the repository; anything else is a 404.
17
18 ## Not done
19
20 Handing a clone the blob from the store (`packfile-uris` or an HTTPS promisor remote) is not here: git has no setting for it that fits a repository served by upload-pack as is. Deleting a repository retracts its blobs from the store (after any offload still running has stopped). Renaming a repository or making it private does not: the blobs stay under the old name, and the page and download still check who may read.
outdated

Stale: delete now retracts the blobs (deleteRepo calls retractLarge). Say that renames and making a repository private do not.

21
22 Code: `src/blob/large.ts`, `src/web/pages/large_files.ts`.
src/actions/repos.ts +4
@@ -4,6 +4,7 @@
44 * write path — committing files to a branch without a git client.
55 */
66
7 import { offloads, retractLarge } from "../blob/large.ts";
78 import { mirrorCopyWords } from "./mirror_copy.ts";
89 import { recordRefusal } from "../core/copies.ts";
910 import { retractBundles } from "../git/bundle_uri.ts";
@@ -629,6 +630,9 @@ export async function deleteRepo(
629630 await retractBundles(app, repo);
630631 const deleted = await destroyRepo(app.db, app.reposRoot, repo);
631632 if (!deleted.ok) return deleted;
633 // A running offload stops at the missing directory; wait for it so nothing is uploaded after.
outdated

An offload still running can re-upload after this. Cancel or await it, or check the row exists before uploading.

634 await Promise.allSettled([...offloads(app).settled]);
635 await retractLarge(app, repo);
632636 await removeInstallCache(app.config.dataDir, repo.id);
633637 removeDrop(app.config.dataDir, repo.id);
634638 dropMirror(app.config.dataDir, repo.id);
src/app.ts +3
@@ -4,6 +4,7 @@
44 * side-effect-contained, so tests boot real forges by the dozen.
55 */
66
7 import { onPushLarge } from "./blob/large.ts";
78 import { settleEstimates } from "./actions/estimates_settle.ts";
89 import { ownHost, setOwnHost } from "./core/trusted_sources.ts";
910 import { commitIdentity } from "./core/commit_identity.ts";
@@ -309,6 +310,8 @@ export function createApp(config: ForgeConfig): App {
309310 bus.subscribe((event) => enqueueForEvent(db, event), "local");
310311 // A push to a public repository's default branch makes its clone bundle again (#14409).
311312 bus.subscribe((event) => onPushEvent({ db, reposRoot }, event), "local");
313 // A push may bring a blob over the policy size: copy it to the BlobStore by object id (#4490).
314 bus.subscribe((event) => onPushLarge({ db, reposRoot, config: { dataDir } }, event), "local");
312315 // A pull opened or merged, a release served, an issue dropped or split:
313316 // estimates settle (#11955).
314317 bus.subscribe((event) => settleEstimates(db, event), "local");
src/blob/large.ts added +295
@@ -0,0 +1,295 @@
1 /**
2 * Big git blobs by object id, in the BlobStore (#4490, step 3 of #4481).
3 *
4 * A blob over the policy size (`FORGE_LARGE_BLOB_BYTES`, default 10 MB) is copied to the
5 * BlobStore under `large/<owner>/<name>/<oid>` after a push, and served from there by a presigned
6 * URL (or streamed, when the store is a directory). Git keeps its own copy: nothing here rewrites
7 * history or changes what a clone sends. Whether git can hand a client such a blob by
8 * `packfile-uris` or an HTTPS promisor remote is open; until it can, a clone still gets the bytes
9 * from git, and this is the cheap way to download one file and the place to see what is big.
10 *
11 * State: one small file per repository, `<repo>/forge-large.json`: `files` (oid, size, path of each
12 * blob over policy, found once per push by the offload job, never on a request) and `held`
13 * (`{ "<oid>": size }` for each blob the store is known to hold, written after the upload
14 * succeeded). Held in memory: the ids of repositories being offloaded, one each, gone on restart
15 * (the next push offloads again).
16 */
17
18 import { existsSync } from "node:fs";
19 import { readFile, rename, rm, writeFile } from "node:fs/promises";
20 import { join } from "node:path";
21 import type { App } from "../app.ts";
22 import type { ForgeEvent } from "../core/events.ts";
23 import { getRepoById, type Repo } from "../core/repos.ts";
24 import { gitEnv, runGit } from "../git/env.ts";
25 import { isSafeOid } from "../git/guard.ts";
26 import { repoDir } from "../git/repos.ts";
27 import { createLog } from "../kernel/log.ts";
28 import { dirStore, s3FromEnv, s3Store, type BlobStore } from "./store.ts";
29
30 /** What this module needs of a forge. */
31 export interface Home {
32 readonly reposRoot: string;
33 readonly db: object;
34 readonly config: { readonly dataDir: string };
35 }
36
37 export const DEFAULT_LARGE_BYTES = 10 * 1024 * 1024;
38 const POINTER = "forge-large.json";
39 /** The most blobs offloaded after one push, and the most the panel lists. */
40 export const MAX_PER_PUSH = 20;
41 export const MAX_LISTED = 200;
42 /** How long a presigned address lives. */
43 export const PRESIGN_S = 300;
44
45 /** The policy size: a whole number of bytes from 1 KiB up, else the default. */
46 export function largeThreshold(env: Record<string, string | undefined> = process.env): number {
47 const raw = env["FORGE_LARGE_BLOB_BYTES"]?.trim() ?? "";
48 if (!/^\d{1,15}$/.test(raw)) return DEFAULT_LARGE_BYTES;
49 const n = Number(raw);
50 return n >= 1024 ? n : DEFAULT_LARGE_BYTES;
51 }
52
53 /** `FORGE_LARGE_BLOB_BYTES=off` turns the offload off: a push then spawns nothing for it. */
54 const offByPolicy = (env: Record<string, string | undefined> = process.env): boolean =>
55 env["FORGE_LARGE_BLOB_BYTES"]?.trim().toLowerCase() === "off";
56
57 export const largeKey = (owner: string, name: string, oid: string): string =>
58 `large/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/${oid}`;
59
60 export interface LargeFile {
61 readonly oid: string;
62 readonly size: number;
63 /** A path on the default branch, or undefined when only history holds it. */
64 readonly path: string | undefined;
65 /** Where the bytes can be had besides git. */
66 readonly where: "git" | "git and store";
67 }
68
69 interface Pointer {
70 readonly held: Map<string, number>;
71 readonly files: { oid: string; size: number; path: string | undefined }[];
72 }
73
74 /** The pointer file: what the last offload found and what the store holds. Never scans git. */
75 async function readPointer(dir: string): Promise<Pointer> {
76 const out: Pointer = { held: new Map(), files: [] };
outdated

High: this full-object scan runs on every page view and terminal read (see largeFiles). Read a per-push cached list instead.

77 try {
78 const v: unknown = JSON.parse(await readFile(join(dir, POINTER), "utf8"));
79 if (typeof v !== "object" || v === null || Array.isArray(v)) return out;
80 const { held, files } = v as { held?: unknown; files?: unknown };
81 if (typeof held === "object" && held !== null && !Array.isArray(held))
82 for (const [oid, size] of Object.entries(held))
83 if (isSafeOid(oid) && typeof size === "number" && Number.isSafeInteger(size) && size >= 0) out.held.set(oid, size);
84 if (Array.isArray(files))
85 for (const f of files.slice(0, MAX_LISTED) as unknown[]) {
86 const { oid, size, path } = (f ?? {}) as { oid?: unknown; size?: unknown; path?: unknown };
87 if (typeof oid === "string" && isSafeOid(oid) && typeof size === "number" && Number.isSafeInteger(size) && size >= 0)
88 out.files.push({ oid, size, path: typeof path === "string" ? path.slice(0, 1024) : undefined });
89 }
90 } catch {
91 // no pointer yet: nothing listed
92 }
93 return out;
94 }
95
96 async function writePointer(dir: string, p: Pointer): Promise<void> {
97 const tmp = join(dir, `${POINTER}.tmp`);
98 await writeFile(tmp, JSON.stringify({ held: Object.fromEntries(p.held), files: p.files }));
99 await rename(tmp, join(dir, POINTER));
100 }
101
102 /** The name a download is saved as: the file's own, made safe for a header, else the oid. */
103 export function downloadName(path: string | undefined, oid: string): string {
104 const base = (path ?? "").split("/").pop() ?? "";
105 const safe = base.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^\.+/, "").slice(0, 100);
106 return safe === "" ? oid : safe;
107 }
108
109 /** Every blob in the repository of at least `threshold` bytes, largest first, at most `limit`. */
110 export async function scanLarge(
111 dir: string,
112 threshold: number,
113 defaultBranch: string,
114 limit = MAX_LISTED,
115 ): Promise<{ oid: string; size: number; path: string | undefined }[]> {
116 const all = await runGit(
117 ["cat-file", "--batch-all-objects", "--batch-check=%(objecttype) %(objectsize) %(objectname)"],
118 { cwd: dir, timeoutMs: 60_000 },
119 );
120 if (!all.ok) return [];
121 const found: { oid: string; size: number }[] = [];
122 for (const line of all.value.split("\n")) {
123 const [type, size, oid] = line.split(" ");
124 if (type !== "blob" || oid === undefined || !isSafeOid(oid)) continue;
125 const bytes = Number(size);
126 if (Number.isSafeInteger(bytes) && bytes >= threshold) found.push({ oid, size: bytes });
127 }
128 found.sort((a, b) => b.size - a.size || a.oid.localeCompare(b.oid));
129 const top = found.slice(0, limit);
130 const paths = new Map<string, string>();
131 if (top.length > 0) {
132 const tree = await runGit(["ls-tree", "-r", "-l", "-z", `refs/heads/${defaultBranch}`], { cwd: dir, timeoutMs: 60_000 });
133 if (tree.ok)
134 for (const entry of tree.value.split("\0")) {
135 const tab = entry.indexOf("\t");
136 const meta = entry.slice(0, tab).split(/\s+/);
137 const oid = meta[2];
138 if (tab > 0 && oid !== undefined && !paths.has(oid)) paths.set(oid, entry.slice(tab + 1));
139 }
140 }
141 return top.map((b) => ({ ...b, path: paths.get(b.oid) }));
142 }
143
144 /** The panel's rows, read from the pointer file the offload job wrote: no git on a request. */
145 export async function largeFiles(
146 app: Pick<Home, "reposRoot">,
147 repo: Pick<Repo, "ownerName" | "name">,
148 env: Record<string, string | undefined> = process.env,
149 ): Promise<{ threshold: number; files: LargeFile[] }> {
150 const { held, files } = await readPointer(repoDir(app.reposRoot, repo.ownerName, repo.name));
151 return {
152 threshold: largeThreshold(env),
153 files: files.map((f) => ({ ...f, where: held.get(f.oid) === f.size ? "git and store" : "git" })),
154 };
155 }
156
157 let shared: BlobStore | undefined;
158 /** The forge's blob store: the bucket when `S3_*` is set, else a directory under its data. */
159 export function largeStore(dataDir: string): BlobStore {
160 const target = s3FromEnv();
161 return (shared ??= target === undefined ? dirStore(join(dataDir, "large-blobs")) : s3Store(target, 2));
162 }
163
164 /** Copy one blob from git to the store, streamed, never whole in memory. */
165 async function copyBlob(store: BlobStore, dir: string, key: string, oid: string): Promise<void> {
166 const proc = Bun.spawn(["git", "cat-file", "blob", oid], { cwd: dir, env: gitEnv(), stdin: "ignore", stdout: "pipe", stderr: "ignore" });
167 try {
168 await store.putStream(key, proc.stdout);
169 if ((await proc.exited) !== 0) throw new Error(`git cat-file ${oid} failed`);
170 } catch (error) {
171 proc.kill();
172 await store.delete(key).catch(() => {});
173 throw error;
174 }
175 }
176
177 /** Offload what is over policy and not yet held; returns how many were copied. */
178 export async function offloadLarge(input: {
179 readonly store: BlobStore;
180 readonly dir: string;
181 readonly owner: string;
182 readonly name: string;
183 readonly defaultBranch: string;
184 readonly threshold: number;
185 }): Promise<number> {
186 const { store, dir, owner, name, threshold } = input;
187 const listed = await scanLarge(dir, threshold, input.defaultBranch);
188 if (!existsSync(dir)) return 0;
189 const pointer = await readPointer(dir);
190 const held = pointer.held;
191 await writePointer(dir, { held, files: listed });
192 let copied = 0;
193 for (const f of listed.slice(0, MAX_PER_PUSH)) {
194 if (!existsSync(dir)) break; // the repository was deleted under us: upload nothing more
195 const key = largeKey(owner, name, f.oid);
196 if (held.get(f.oid) === f.size && (await store.size(key)) === f.size) continue;
197 await copyBlob(store, dir, key, f.oid);
198 if ((await store.size(key)) !== f.size) {
199 await store.delete(key).catch(() => {});
200 throw new Error(`stored ${f.oid} has the wrong size`);
201 }
202 held.set(f.oid, f.size);
203 await writePointer(dir, { held, files: listed });
204 copied++;
205 }
206 return copied;
207 }
208
209 /** Take a repository's large blobs back from the store (deleted, renamed, moved). */
210 export async function retractLarge(
211 app: Home,
212 repo: Pick<Repo, "ownerName" | "name">,
213 ): Promise<void> {
214 await rm(join(repoDir(app.reposRoot, repo.ownerName, repo.name), POINTER), { force: true });
215 const store = largeStore(app.config.dataDir);
216 const prefix = `large/${encodeURIComponent(repo.ownerName)}/${encodeURIComponent(repo.name)}/`;
217 for (const key of await store.list(prefix).catch(() => [])) await store.delete(key).catch(() => {});
218 }
219
220 /**
221 * Where a held blob is read from: a presigned URL straight to the bucket, or its bytes when the
222 * store is a directory. undefined when the repository does not hold that oid there.
223 */
224 export async function serveLarge(
225 app: Home,
226 repo: Pick<Repo, "ownerName" | "name">,
227 oid: string,
228 store: BlobStore = largeStore(app.config.dataDir),
229 ): Promise<({ url: string } | { stream: ReadableStream<Uint8Array>; size: number }) & { name: string } | undefined> {
230 if (!isSafeOid(oid)) return undefined;
231 const { held, files } = await readPointer(repoDir(app.reposRoot, repo.ownerName, repo.name));
232 const size = held.get(oid);
233 if (size === undefined) return undefined;
234 const name = downloadName(files.find((f) => f.oid === oid)?.path, oid);
235 const key = largeKey(repo.ownerName, repo.name, oid);
236 if (store.presign !== undefined) return { name, url: store.presign(key, { method: "GET", expiresInS: PRESIGN_S }) };
237 const stream = await store.getStream(key);
238 return stream === undefined ? undefined : { name, stream, size };
239 }
240
241 // ---- when ----
242
243 const log = createLog("large-blob");
244 interface Jobs {
245 running: Set<string>;
246 settled: Set<Promise<void>>;
247 }
248 // By the forge's database handle, not the app object: the push listener hands in a fresh object
249 // each time.
250 const jobsOf = new WeakMap<object, Jobs>();
251 /** The offloads in flight under one app: a repository id each, and the promises to await. */
252 export function offloads(app: Home): Jobs {
253 let jobs = jobsOf.get(app.db);
254 if (!jobs) jobsOf.set(app.db, (jobs = { running: new Set(), settled: new Set() }));
255 return jobs;
256 }
257
258 /** Offload in the background; one run per repository at a time. */
259 export function noteLarge(
260 app: Home,
261 repo: Pick<Repo, "id" | "ownerName" | "name" | "defaultBranch">,
262 using: { store?: BlobStore; threshold?: number } = {},
263 ): void {
264 const { running, settled } = offloads(app);
265 if (offByPolicy() || running.has(repo.id)) return;
266 running.add(repo.id);
267 const job: Promise<void> = offloadLarge({
268 store: using.store ?? largeStore(app.config.dataDir),
269 dir: repoDir(app.reposRoot, repo.ownerName, repo.name),
270 owner: repo.ownerName,
271 name: repo.name,
272 defaultBranch: repo.defaultBranch,
273 threshold: using.threshold ?? largeThreshold(),
274 })
275 .then(() => {})
276 .catch((error: unknown) => {
277 log.warn("large blobs not stored", { repo: `${repo.ownerName}/${repo.name}`, why: String(error).slice(0, 200) });
278 })
279 .finally(() => {
280 running.delete(repo.id);
281 settled.delete(job);
282 });
283 settled.add(job);
284 }
285
286 /** Any push may bring a big blob. */
287 export function onPushLarge(
288 app: Home & Pick<App, "db">,
289 event: ForgeEvent,
290 using: { store?: BlobStore; threshold?: number } = {},
291 ): void {
292 if (event.kind !== "push" || event.repoId === null) return;
293 const repo = getRepoById(app.db, event.repoId);
294 if (repo) noteLarge(app, repo, using);
295 }
src/http/server.ts +4
@@ -269,6 +269,7 @@ import {
269269 previewSubmit,
270270 } from "../web/pages/edit.ts";
271271 import { configPage, configSubmit } from "../web/pages/config.ts";
272 import { largeFileDownload, largeFilesPage } from "../web/pages/large_files.ts";
272273 import { commitPage, commitsPage, comparePage } from "../web/pages/commits.ts";
273274 import { eventsList } from "../web/pages/events.ts";
274275 import {
@@ -1771,6 +1772,9 @@ export function buildRouter(): Router<Handler> {
17711772 // The repository's activity, for a feed reader.
17721773 router.add("GET", "/:owner/:name/activity.atom", activityAtom);
17731774 router.add("GET", "/:owner/:name/branches", branchesPage);
1775 // Blobs over the policy size, and the one a presigned address serves (#4490).
1776 router.add("GET", "/:owner/:name/large", largeFilesPage);
1777 router.add("GET", "/:owner/:name/large/:oid", largeFileDownload);
17741778 // Build pins (`git/builds.ts`): the list, the form, and the writes behind them.
17751779 router.add("GET", "/:owner/:name/builds", buildsPage);
17761780 router.add("GET", "/:owner/:name/builds/new", newBuildPage);
src/kernel/destroy_reach.ts +1
@@ -92,6 +92,7 @@ export const ALLOWED_REMOVALS: readonly { unit: string; why: string }[] = [
9292 { unit: "src/core/repos.ts:rowOrUndo", why: "removes the directory git has just made for the repository being created, when its row is refused" },
9393 { unit: "src/git/locks.ts:sweepRefLock", why: "removes the one lock file of the ref a merge moves, when older than any live update (issue 12143): a name checked to be under refs/heads, never another file" },
9494 { unit: "src/git/write.ts:commitFiles", why: "removes its own temporary index file" },
95 { unit: "src/blob/store.ts:dirStore", why: "reached only because `largeStore` (a push offloads big blobs, #4490) may build it: it removes a half-written upload's temporary part and the key a caller deletes, and the offload deletes only the key of a copy that failed, never a forge, app or repository directory" },
9596 { unit: "src/kernel/file_modes.ts:writePrivate", why: "removes the temporary file it has just made itself, under a name nobody else chose, when the write or the rename failed" },
9697 { unit: "src/git/repos.ts:detachFork", why: "removes the alternates file of the fork just made" },
9798 { unit: "src/git/env.ts:trustedCaBundle", why: "removes the process's own temporary CA bundle at exit" },
src/tui/screens/largefiles.ts added +61
@@ -0,0 +1,61 @@
1 /**
2 * A repository's large files in the terminal (#4490): the /:owner/:name/large page's rows, from
3 * the same read (`blob/large.ts`, `largeFiles`). Whoever may read the repository sees it.
4 */
5 import { largeFiles, type LargeFile } from "../../blob/large.ts";
6 import { canRead, type Repo } from "../../core/repos.ts";
7 import { fileSize } from "../../web/ui.ts";
8 import type { Ctx, Screen } from "../app/app.ts";
9 import type { Command } from "../app/palette.ts";
10 import { binding } from "../app/keys.ts";
11 import type { Session } from "../session.ts";
12 import { ListState, drawList, runAsync, type ListRow } from "./common.ts";
13
14 export const largeRow = (f: LargeFile): ListRow => ({
15 title: `${f.path ?? "(only in history)"} · ${fileSize(f.size)}`,
16 meta: `${f.where} · ${f.oid}`,
17 });
18
19 /** What the screen lists: the saved rows for someone who may read the repository, else none. */
20 export async function largeRows(f: Session, repo: Repo): Promise<ListRow[]> {
21 return canRead(f.app.db, repo, f.user) ? (await largeFiles(f.app, repo)).files.map(largeRow) : [];
22 }
23
outdated

The screen has no test. Add one covering a reader's rows and a stranger on a private repository.

24 export function largeFilesScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
25 const state = new ListState();
26 let rows: ListRow[] = [];
27 let loaded = false;
28 const load = () =>
29 runAsync(ctx, async () => {
30 rows = await largeRows(f, repo);
31 loaded = true;
32 });
33 load();
34 return {
35 title: `${repo.ownerName}/${repo.name} — Large files`,
36 keys: [binding(["j", "k"], "move cursor"), binding(["g"], "read again")],
37 render(area, s) {
38 drawList(s, area, ctx.theme.c, state, loaded ? rows : []);
39 },
40 key(e) {
41 if (e.key === "g") {
42 load();
43 return true;
44 }
45 return state.key(e, rows.length);
46 },
47 };
48 }
49
50 /** The palette's command while a repository is open. */
51 export function largeFilesCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
52 if (repo === undefined) return [];
53 return [
54 {
55 id: "large-files",
56 title: `${repo.ownerName}/${repo.name} — Large files`,
57 hint: "blobs over the size policy, and where each lives",
58 run: () => ctx.push(largeFilesScreen(f, ctx, repo)),
59 },
60 ];
61 }
src/tui/screens/workspace.ts +2
@@ -222,6 +222,7 @@ import { templateCommands } from "./template.ts";
222222 import { buildCacheCommands } from "./buildcache.ts";
223223 import { schedulesCommands } from "./schedules.ts";
224224 import { appReleasesCommands } from "./appreleases.ts";
225 import { largeFilesCommands } from "./largefiles.ts";
225226 import { migrationCommands } from "./migration.ts";
226227 import { dropCommands } from "./drop.ts";
227228 import { recheckWindowCommands } from "./recheckwindow.ts";
@@ -2442,6 +2443,7 @@ export function workspaceScreen(
24422443 ...trafficCommands(f, ctx, repo),
24432444 ...schedulesCommands(f, ctx, repo),
24442445 ...appReleasesCommands(f, ctx, repo),
2446 ...largeFilesCommands(f, ctx, repo),
24452447 ...dropCommands(f, ctx, repo),
24462448 ...migrationCommands(f, ctx, repo),
24472449 ...recheckWindowCommands(f, ctx, repo, () => screen),
src/web/pages/large_files.ts added +63
@@ -0,0 +1,63 @@
1 /**
2 * Large files: the blobs over the policy size in one repository, how big each is and where it
3 * lives (#4490). Git always holds it; "git and store" means the BlobStore holds it too, by object
4 * id, and `/:owner/:name/large/:oid` hands out a short-lived presigned address (or the bytes,
5 * when the store is a directory). Readable by whoever can read the repository.
6 */
7
8 import { largeFiles, serveLarge } from "../../blob/large.ts";
9 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
10 import type { Ctx } from "../../http/context.ts";
11 import { loadRepo, notFoundPage, scopeHeader } from "../chrome.ts";
12 import { html, type Html } from "../html.ts";
13 import { page } from "../layout.ts";
14 import { localScope } from "../scope.ts";
15 import { empty, fileSize, row, rowList } from "../ui.ts";
16
17 // GET /:owner/:name/large
18 export async function largeFilesPage(ctx: Ctx): Promise<Response> {
19 const repo = loadRepo(ctx);
20 if (!repo) return notFoundPage(ctx);
21 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
22 const scope = localScope(ctx, repo);
23 const { threshold, files } = await timePhaseAsync(ctx.request, "large", () => largeFiles(ctx.app, repo));
24 const rows: Html = rowList(files.map((f) =>
25 row({
26 title: f.path ?? "(only in history)",
27 meta: html`<span class="mono">${f.oid}</span>`,
28 trail: html`<span class="num">${fileSize(f.size)}</span>

High: an unauthenticated request triggers a full repository scan here. Read the list the offload job saved.

29 <span class="muted small">${f.where}</span>
30 ${f.where === "git and store" ? html`<a class="small" href="${scope.base}/large/${f.oid}">Download</a>` : null}`,
31 }),
32 ));
33 return timePhase(ctx.request, "render", () => page({
34 ctx,
35 title: `Large files · ${scope.facts.name}`,
36 crumbs: scope.crumbs,
37 palette: scope.palette,
38 body: html`${scopeHeader(ctx, scope, "code", { compact: true })}
39 <div class="mt">
40 ${files.length === 0
41 ? empty({ icon: "file", title: `Nothing is ${fileSize(threshold)} or more` })
42 : rows}
43 </div>`,
44 }));
45 }
46
47 // GET /:owner/:name/large/:oid
48 export async function largeFileDownload(ctx: Ctx): Promise<Response> {
outdated

Principle 1: say it once. Drop the empty-state note or the muted line.

49 const repo = loadRepo(ctx);
50 if (!repo) return notFoundPage(ctx);
51 const served = await serveLarge(ctx.app, repo, ctx.params.oid ?? "");
52 if (served === undefined) return notFoundPage(ctx);
53 const headers = { "cache-control": "private, no-store" };
54 if ("url" in served) return new Response(null, { status: 302, headers: { ...headers, location: served.url } });
55 return new Response(served.stream, {
56 headers: {
57 ...headers,
58 "content-type": "application/octet-stream",
59 "content-length": String(served.size),
60 "content-disposition": `attachment; filename="${served.name}"`,
61 },
outdated

A fixed filename blob is useless to the person downloading. Use the file's basename or the oid.

62 });
63 }
test/fork-drift-cache.test.ts +6
@@ -14,6 +14,7 @@ import { createUser, type User } from "../src/core/users.ts";
1414 import { promote } from "./helpers/members.ts";
1515 import { gitSpawns } from "./helpers/work.ts";
1616
17 const was = process.env["FORGE_LARGE_BLOB_BYTES"]; // env-restored: afterAll
1718 let dir: string;
1819 let app: App;
1920 let amy: User;
@@ -30,6 +31,9 @@ const read = () =>
3031 forkDrift(app, getRepo(app.db, "bob", "lib")!, getRepo(app.db, "amy", "lib")!);
3132
3233 beforeAll(async () => {
34 // A fork follows its parent in the background, and a push would scan it for big blobs (#4490): a
35 // spawn this test would count.
36 process.env["FORGE_LARGE_BLOB_BYTES"] = "off"; // env-restored: afterAll
3337 dir = await mkdtemp(join(tmpdir(), "forge-drift-cache-"));
3438 app = createApp({ dataDir: dir, port: 0 });
3539 const users: User[] = [];
@@ -51,6 +55,8 @@ beforeAll(async () => {
5155 await land(bob, "bob", "mine");
5256 });
5357 afterAll(async () => {
58 if (was === undefined) delete process.env["FORGE_LARGE_BLOB_BYTES"]; // env-restored: afterAll
59 else process.env["FORGE_LARGE_BLOB_BYTES"] = was; // env-restored: afterAll
5460 await rm(dir, { recursive: true, force: true });
5561 });
5662
test/large-blobs.test.ts added +198
@@ -0,0 +1,198 @@
1 /**
2 * Big blobs by object id (#4490): a blob over the policy size is copied to the BlobStore after a
3 * push, listed on the large-files page with where it lives, and served by the oid; one under the
4 * policy, an oid never stored and a repository the caller cannot read are not.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { commitToBranch, createRepo, deleteRepo } from "../src/actions/repos.ts";
12 import { dirStore } from "../src/blob/store.ts";
13 import { largeRows } from "../src/tui/screens/largefiles.ts";
14 import type { Session } from "../src/tui/session.ts";
15 import { gitSpawns } from "./helpers/work.ts";
16 import { DEFAULT_LARGE_BYTES, downloadName, largeFiles, largeKey, largeThreshold, noteLarge, onPushLarge, offloads, serveLarge } from "../src/blob/large.ts";
17 import type { ForgeEvent } from "../src/core/events.ts";
18 import type { Repo } from "../src/core/repos.ts";
19 import type { User } from "../src/core/users.ts";
20 import { repoDir } from "../src/git/repos.ts";
21 import { runGit } from "../src/git/env.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23 import { largeStore } from "../src/blob/large.ts";
24 import { seedAdmin } from "./helpers/admin.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26
27 quietLogs();
28
29 const BIG = "x".repeat(5000);
30
31 describe("the policy", () => {
32 test("a whole number of bytes from 1 KiB, else 10 MB", () => {
33 expect(largeThreshold({})).toBe(DEFAULT_LARGE_BYTES);
34 expect(largeThreshold({ FORGE_LARGE_BLOB_BYTES: "4096" })).toBe(4096);
35 for (const bad of ["12", "-5", "1e9", "abc", "0x10", "", "99999999999999999"])
36 expect(largeThreshold({ FORGE_LARGE_BLOB_BYTES: bad })).toBe(DEFAULT_LARGE_BYTES);
37 });
38 });
39
40 describe("a big blob through the real router", () => {
41 let dataDir: string;
42 let app: App;
43 let servers: Servers;
44 let ada: User;
45 let oid: string;
46 const was = process.env["FORGE_LARGE_BLOB_BYTES"];
47
48 const made = async (name: string, visibility: "public" | "private"): Promise<Repo> => {
49 const r = await createRepo(app, ada, { name, visibility });
50 if (!r.ok) throw new Error(String(r.error));
51 await commitToBranch(app, ada, r.value, {
52 message: "seed",
53 files: [{ path: "small.txt", content: "a\n" }, { path: "data/big.bin", content: BIG }],
54 });
55 // The commit's own push event starts an offload; let it end so the test's call is the only one.
56 await Promise.allSettled([...offloads(app).settled]);
57 return r.value;
58 };
59 const push = (repo: Repo): ForgeEvent => ({
60 id: "e",
61 kind: "push",
62 repoId: repo.id,
63 actorId: null,
64 payload: { updates: [] },
65 createdAt: new Date().toISOString(),
66 });
67
68 beforeAll(async () => {
69 process.env["FORGE_LARGE_BLOB_BYTES"] = "2048";
70 dataDir = await mkdtemp(join(tmpdir(), "forge-large-"));
71 app = createApp({ dataDir, port: 0, host: "forge.example", url: "https://forge.example" });
72 servers = await serve(app);
73 const seeded = await seedAdmin(app, { username: "ada", email: "[email protected]" });
74 if (!seeded.ok) throw new Error(seeded.error);
75 ada = seeded.value;
76 });
77
78 afterAll(async () => {
79 if (was === undefined) delete process.env["FORGE_LARGE_BLOB_BYTES"];
80 else process.env["FORGE_LARGE_BLOB_BYTES"] = was;
81 await Promise.allSettled([...offloads(app).settled]);
82 servers.stop();
83 app.close();
84 await rm(dataDir, { recursive: true, force: true });
85 });
86
87 test("a read scans nothing; the panel says git and store once offloaded", async () => {
88 const repo = await made("pub", "public");
89 expect((await largeFiles(app, repo)).threshold).toBe(2048);
90 expect(await gitSpawns(async () => void (await largeFiles(app, repo)))).toBe(0); // a read scans nothing
91
92 onPushLarge(app, push(repo));
93 await Promise.all([...offloads(app).settled]);
94 const after = await largeFiles(app, repo);
95 expect(after.files.map((f) => [f.path, f.size])).toEqual([["data/big.bin", 5000]]);
96 oid = after.files[0]!.oid;
97 expect(after.files.map((f) => f.where)).toEqual(["git and store"]);
98 expect(await largeStore(dataDir).size(largeKey("ada", "pub", oid))).toBe(5000);
99 });
100
101 test("the page lists it, and the oid serves its bytes", async () => {
102 const list = await fetch(`${servers.url}/ada/pub/large`);
103 expect(list.status).toBe(200);
104 const text = await list.text();
105 expect(text).toContain("data/big.bin");
106 expect(text).toContain(oid);
107 expect(text).toContain("git and store");
108 expect(text).not.toContain("small.txt");
109
110 const got = await fetch(`${servers.url}/ada/pub/large/${oid}`);
111 expect(got.status).toBe(200);
112 expect(got.headers.get("content-disposition")).toBe('attachment; filename="big.bin"');
113 expect(await got.text()).toBe(BIG);
114 });
115
116 test("an oid never stored, a malformed one and the small blob are 404", async () => {
117 const small = await runGit(["rev-parse", "HEAD:small.txt"], { cwd: repoDir(app.reposRoot, "ada", "pub") });
118 expect(small.ok).toBe(true);
119 for (const bad of [small.ok ? small.value : "", "f".repeat(40), "nothex", "../x"])
120 expect((await fetch(`${servers.url}/ada/pub/large/${bad}`)).status).toBe(404);
121 });
122
123 test("a private repository answers a stranger as it answers a missing one", async () => {
124 const repo = await made("vault", "private");
125 onPushLarge(app, push(repo));
126 await Promise.all([...offloads(app).settled]);
127 const id = (await largeFiles(app, repo)).files[0]!.oid;
128 const reader = { app, db: app.db, user: ada } as unknown as Session;
129 const stranger = { app, db: app.db, user: undefined } as unknown as Session;
130 expect((await largeRows(reader, repo)).map((r) => r.title)).toEqual(["data/big.bin · 4.9 KB"]);
131 expect(await largeRows(stranger, repo)).toEqual([]);
132 expect((await fetch(`${servers.url}/ada/vault/large`)).status).toBe(404);
133 expect((await fetch(`${servers.url}/ada/vault/large/${id}`)).status).toBe(404);
134 });
135
136 test("a store with presigning gets a redirect, not the bytes", async () => {
137 const repo = await made("signed", "public");
138 const store = dirStore(join(dataDir, "elsewhere"));
139 const signing = Object.assign(Object.create(store), {
140 presign: (key: string) => `https://bucket.example/${key}?sig=1`,
141 });
142 onPushLarge(app, push(repo), { store: signing });
143 await Promise.all([...offloads(app).settled]);
144 const id = (await largeFiles(app, repo)).files[0]!.oid;
145 const served = await serveLarge(app, repo, id, signing);
146 expect(served).toEqual({ name: "big.bin", url: `https://bucket.example/large/ada/signed/${id}?sig=1` });
147 });
148
149 test("deleting the repository takes its large blobs out of the store", async () => {
150 const repo = await made("gone", "public");
151 onPushLarge(app, push(repo));
152 await Promise.all([...offloads(app).settled]);
153 const key = largeKey("ada", "gone", (await largeFiles(app, repo)).files[0]!.oid);
154 expect(await largeStore(dataDir).size(key)).toBe(5000);
155 expect((await deleteRepo(app, ada, repo)).ok).toBe(true);
156 expect(await largeStore(dataDir).size(key)).toBeUndefined();
157 });
158
159 test("a delete while an offload runs leaves nothing in the store", async () => {
160 const repo = await made("racing", "public");
161 onPushLarge(app, push(repo)); // in flight: not awaited
162 expect((await deleteRepo(app, ada, repo)).ok).toBe(true);
163 await Promise.all([...offloads(app).settled]);
164 expect(await largeStore(dataDir).list("large/ada/racing/")).toEqual([]);
165 });
166
167 test("a download is named for the file, else the oid, and never carries path characters", () => {
168 expect(downloadName("data/big.bin", "a".repeat(40))).toBe("big.bin");
169 expect(downloadName('x/"; rm.txt', "b".repeat(40))).toBe("_rm.txt");
170 expect(downloadName("dir/..", "c".repeat(40))).toBe("c".repeat(40));
171 expect(downloadName(undefined, "d".repeat(40))).toBe("d".repeat(40));
172 });
173 });
174
175 const dbs = new Map<string, object>();
176 const home = (root: string) => {
177 if (!dbs.has(root)) dbs.set(root, {});
178 return { reposRoot: root, db: dbs.get(root)!, config: { dataDir: root } } as unknown as Parameters<typeof offloads>[0];
179 };
180
181 test("the push listener's fresh app object shares one job set per forge", () => {
182 const a = home("/same");
183 expect(offloads(a)).toBe(offloads(home("/same")));
184 expect(offloads(a)).not.toBe(offloads(home("/other")));
185 });
186
187 test("FORGE_LARGE_BLOB_BYTES=off starts no offload on a push", () => {
188 const was = process.env["FORGE_LARGE_BLOB_BYTES"];
189 process.env["FORGE_LARGE_BLOB_BYTES"] = "off";
190 try {
191 const app = home("/nonexistent");
192 noteLarge(app, { id: "r1", ownerName: "a", name: "b", defaultBranch: "main" });
193 expect(offloads(app).running.size).toBe(0);
194 } finally {
195 if (was === undefined) delete process.env["FORGE_LARGE_BLOB_BYTES"];
196 else process.env["FORGE_LARGE_BLOB_BYTES"] = was;
197 }
198 });
test/no-polling.test.ts +1
@@ -304,6 +304,7 @@ const NOT_WALKED: Record<string, string> = {
304304 "/:owner/-/teams/:team": "needs an organization and a team",
305305 "/:owner/:name/app/:env/open": "needs a running app environment to open",
306306 "/:owner/:name/archive/:file": "a tarball download, not a page; the file name is one the seed cannot guess",
307 "/:owner/:name/large/:oid": "a download redirect or stream for a blob held in the store, not a page; the seed holds none",
307308 "/:owner/:name/bets/:id": "needs a proposed bet",
308309 "/:owner/:name/bets/:id/walk/:walk": "needs a proposed bet with a journey walk",
309310 "/:owner/:name/builds/:label/cart": "needs a pinned build with a cart",
test/pages-budget.test.ts +1 −1
@@ -69,7 +69,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = {
6969 };
7070
7171 /** Patterns with no fixture today: lower this as fixtures are added, never raise it silently. */
72 const MAX_UNFIXTURED = 156; // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856)
72 const MAX_UNFIXTURED = 157; // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856)
7373
7474 /** Streams and live fragments: no page. */
7575 const NOT_PAGES = new Set([
test/spawn-pipes.test.ts +1
@@ -22,6 +22,7 @@ const PIPING: Record<string, { sites: string[]; reason: string }> = {
2222 "src/snapshot/drill_job.ts": { sites: ["stdout+stderr"], reason: "the drill child's stdout is read line by line for progress and its result, stderr to its end for the failure text, alongside the exit" },
2323 "src/spawn/archive.ts": { sites: ["stdout+stderr"], reason: "tar() reads the listing from stdout and the failure text from stderr, then waits for exit" },
2424 "src/spawn/cell.ts": { sites: ["stdout+stderr"], reason: "drain() reads the child forge's stdout and stderr to its log until exit" },
25 "src/blob/large.ts": { sites: ["stdout"], reason: "cat-file stdout is the blob, read to the end into the store; stderr is ignored" },
2526 "src/chaos/faults.ts": { sites: ["stdout"], reason: "stdout is read until the kill closes it, then cancelled; stderr is ignored" },
2627 "src/crew/claude.ts": { sites: ["stdout+stderr", "stdout"], reason: "session pumps stdout and stderr; --version awaits stdout, stderr ignored" },
2728 "src/crew/claude_usage.ts": { sites: ["stdout"], reason: "/usage stdout awaited with the exit, under a kill timer; stderr ignored" },
test/spawn-sites.test.ts +2
@@ -19,6 +19,8 @@ const SITES: Record<string, string> = {
1919 "runs an app's `run`/`check` command from its forge.json, which a repository writer pushed; the command is the app's own, run as argv inside its cell (or /bin/sh -c on a host with no cell), never text from a request",
2020 "src/apps/tty.ts":
2121 "runs the app's own `tty` command from forge.json, a writer's text, in the app's cell; the person at the terminal reaches only the pty's stdin, never argv",
22 "src/blob/large.ts":
23 "`git cat-file blob <oid>` in a repository the forge made, the oid checked as a safe hex id first; nothing else from a request",
2224 "src/chaos/faults.ts":
2325 "chaos harness: runs bun on its own worker.ts with a database path and repo id the harness made",
2426 "src/chaos/invariants.ts":

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs