Public: anyone can read this; the crew can change it.
A git CDN: a repository's packs served from object storage by short-lived links #18066
Merged 10h 25m ago, live in production
scout/forge:scout/18035-a-git-cdn-a-repository-s-packs-served-fr → main 0 commits fork 2 threads · 2 unresolved
27 files
changed +905
−63
- docs/features/economics.md
- docs/features/git-cdn.md
- src/actions/economics.ts
- src/actions/repos.ts
- src/app.ts
- src/blob/cdn.ts
- src/blob/large.ts
- src/blob/on_push.ts
- src/contract/openapi/routes/getApiV1ForgeEconomics.ts
- src/contract/openapi/routes/getApiV1ReposOwnerNameCdn.ts
- src/contract/openapi/routes/index.ts
- src/contract/tags.ts
- src/http/api.ts
- src/http/api/cdn.ts
- src/http/api/economics.ts
- src/http/crawl.ts
- src/http/lazy_lists.ts
- src/tui/screens/cdn.ts
- src/tui/screens/economics.ts
- src/tui/screens/largefiles.ts
- src/tui/screens/repo_list.ts
- src/tui/screens/workspace.ts
- src/web/pages/economics.ts
- test/economics.test.ts
- test/git-cdn.test.ts
- test/helpers/seeded_repo.ts
- test/large-blobs.test.ts
docs/features/economics.md +5 −3
| @@ -64,11 +64,13 @@ refused as `bad_price` (or `bad_slots`) and nothing changes. | ||
| 64 | 64 | - **Settings → Economics**: the Prices form, then **This month so far**, |
| 65 | 65 | with the owned, cloud, storage, crew and total lines in US dollars for the |
| 66 | 66 | UTC calendar month up to now. When the box and its slots are both set, |
| 67 | the page also shows the box's price per app-slot. | |
| 67 | the page also shows the box's price per app-slot. Under the lines, the git | |
| 68 | CDN's packs in the bucket (bytes, repositories, and what they come to at the | |
| 69 | storage price): kept apart from the metered storage line. | |
| 68 | 70 | - **Terminal**: the four prices are rows beside the position and the |
| 69 | 71 | margin. `e` asks for the value in dollars, shows from → to, and changes |
| 70 | it after a confirm. The bottom line shows this month's cost. | |
| 71 | - **API**: `GET` adds `prices` (dollars) and `month: { from, to, cost }`; | |
| 72 | it after a confirm. The bottom line shows this month's cost and the git CDN's bytes. | |
| 73 | - **API**: `GET` adds `prices` (dollars) and `month: { from, to, cost }` and `cdn: { bytes, repos }`; | |
| 72 | 74 | `PUT` takes any of the four fields, e.g. `{"ownedMonthUsd": 300, |
| 73 | 75 | "cloudHourUsd": 0.05}`. |
| 74 | 76 | - **MCP**: `economics` takes the same four fields, planned first as for the |
docs/features/git-cdn.md added +35
| @@ -0,0 +1,35 @@ | ||
| 1 | --- | |
| 2 | topic: Your apps | |
| 3 | row: Git CDN: a repository's packs served from object storage by short-lived links | |
| 4 | --- | |
| 5 | # Git CDN | |
| 6 | ||
| 7 | A repository's packs and their `.idx` files are copied to the forge's object storage bucket (the one `S3_*` names; with none, the CDN is off) after every push, as `cdn/<repo id>/<pack name>.pack` and `.idx`. A pack's name is its content's hash, so a pack is uploaded once. The forge's own clone, fetch and push are unchanged: this is an extra door, for a cache that would rather read from the bucket (the Apple app's household cache). | |
| 8 | ||
| 9 | ## Fetch from it | |
| 10 | ||
| 11 | `GET /api/v1/repos/<owner>/<name>/cdn` (a token for a private repository) answers `{ refs: [{ name, oid }], unreached: [ref name], packs: [{ name, size, pack, idx }], expiresAt }`. The `pack` and `idx` links are presigned, read-only and good for 15 minutes; fetching them needs no forge credential. Minted for each request, never at a public path, never cached. | |
| 12 | ||
| 13 | sh | |
| 14 | git init -q --bare r.git && curl -s https://YOUR-FORGE/api/v1/repos/OWNER/NAME/cdn | jq -r '.packs[] | "-o r.git/objects/pack/\(.name).pack \(.pack) -o r.git/objects/pack/\(.name).idx \(.idx)"' | xargs curl -s | |
| 15 | ||
| 16 | ||
| 17 | Then name the refs: `curl -s .../cdn | jq -r '.refs[] | "\(.oid) \(.name)"' | while read o n; do git -C r.git update-ref "$n" "$o"; done`; `git -C r.git fsck` reaches each. | |
| 18 | ||
| 19 | ## What the packs do not reach | |
| 20 | ||
| 21 | A push is packed before it is uploaded (`git repack -d` in the sync job, never on a request), and the job records which refs the uploaded packs reach. `unreached` names every ref whose commit is not that one yet (a push still being stored, a repository never synced): fetch those from git as usual. A push starts the job (two at a time at most). **Backfill is on demand, not a sweep:** a repository nobody pushes to is copied only when someone asks the route while it has unreached refs. A request starts the job only if the last attempt began at least 15 minutes ago (the pointer records when, so a failed repack is not retried by every request); a push always starts one. | |
| 22 | ||
| 23 | **A fork gets no packs.** It borrows its parent's objects through alternates, so its own packs are not whole: the route answers 200 with its refs, every ref unreached and no packs, and no sync is ever started for it. Fetch a fork's refs from git as usual, or fetch the parent's packs. | |
| 24 | ||
| 25 | A reader with no credential (a public repository) is counted by the socket's address, 20 reads a minute, and told `429` with `Retry-After` past that; a header never names the client. | |
| 26 | ||
| 27 | ## See it | |
| 28 | ||
| 29 | Terminal: open a repository, then the palette's "Git CDN" (`src/tui/screens/cdn.ts`): packs, bytes in storage, refs not yet reached. The forge's total is on Settings → Economics (and its API and terminal screen), beside this month's cost. | |
| 30 | ||
| 31 | ## Not done | |
| 32 | ||
| 33 | Packs a repack replaced are deleted from the bucket by the next sync, so a link already minted for one stops working before its 15 minutes: fetch again. Deleting the repository retracts its packs. A bucket path per owner is not offered; the key is the repository's id. | |
| 34 | ||
| 35 | Code: `src/blob/cdn.ts`, `src/http/api/cdn.ts`. |
src/actions/economics.ts +14
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | import type { App } from "../app.ts"; |
| 12 | 12 | import type { User } from "../core/users.ts"; |
| 13 | 13 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 14 | import { cdnBytes } from "../blob/cdn.ts"; | |
| 14 | 15 | import { costOf, monthSoFar, type Cost, type Range } from "../core/cost.ts"; |
| 15 | 16 | import { usageBetween } from "../core/meter.ts"; |
| 16 | 17 | import { usageTotals } from "../core/usage.ts"; |
| @@ -59,6 +60,11 @@ export interface EconomicsView extends Economics { | ||
| 59 | 60 | readonly prices: Prices; |
| 60 | 61 | /** The UTC calendar month so far, and what it cost at `prices`. */ |
| 61 | 62 | readonly month: Range & { readonly cost: Cost }; |
| 63 | /** | |
| 64 | * What the git CDN holds in the bucket (`blob/cdn.ts`): not in `month.cost`, whose storage is | |
| 65 | * metered from disk. | |
| 66 | */ | |
| 67 | readonly cdn: { readonly bytes: number; readonly repos: number }; | |
| 62 | 68 | } |
| 63 | 69 | |
| 64 | 70 | function placementView(app: App, policy: Policy): PlacementView { |
| @@ -95,6 +101,14 @@ function view(app: App): EconomicsView { | ||
| 95 | 101 | changes: economicsChanges(app.db), |
| 96 | 102 | prices, |
| 97 | 103 | month: { ...range, cost }, |
| 104 | cdn: cdnBytes( | |
| 105 | app, | |
| 106 | app.db | |
| 107 | .query<{ ownerName: string; name: string }, []>( | |
| 108 | "SELECT user.username AS ownerName, repo.name AS name FROM repo JOIN user ON user.id = repo.owner_id", | |
| 109 | ) | |
| 110 | .all(), | |
| 111 | ), | |
| 98 | 112 | }; |
| 99 | 113 | } |
| 100 | 114 |
src/actions/repos.ts +2
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | * write path — committing files to a branch without a git client. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { retractCdn } from "../blob/cdn.ts"; | |
| 7 | 8 | import { offloads, retractLarge } from "../blob/large.ts"; |
| 8 | 9 | import { mirrorCopyWords } from "./mirror_copy.ts"; |
| 9 | 10 | import { recordRefusal } from "../core/copies.ts"; |
| @@ -659,6 +660,7 @@ export async function deleteRepo( | ||
| 659 | 660 | // A running offload stops at the missing directory; wait for it so nothing is uploaded after. |
| 660 | 661 | await Promise.allSettled([...offloads(app).settled]); |
| 661 | 662 | await retractLarge(app, repo); |
| 663 | await retractCdn(app, repo); | |
| 662 | 664 | await removeInstallCache(app.config.dataDir, repo.id); |
| 663 | 665 | removeDrop(app.config.dataDir, repo.id); |
| 664 | 666 | dropMirror(app.config.dataDir, repo.id); |
src/app.ts +2
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | import { forgetRepositories } from "./kernel/repo_keyed.ts"; |
| 8 | 8 | import { reviewAfterPush } from "./actions/quarantine.ts"; |
| 9 | import { onPushCdn } from "./blob/cdn.ts"; | |
| 9 | 10 | import { onPushLarge } from "./blob/large.ts"; |
| 10 | 11 | import { settleEstimates } from "./actions/estimates_settle.ts"; |
| 11 | 12 | import { ownHost, setOwnHost } from "./core/trusted_sources.ts"; |
| @@ -326,6 +327,7 @@ export function createApp(config: ForgeConfig): App { | ||
| 326 | 327 | bus.subscribe((event) => onPushEvent({ db, reposRoot }, event), "local"); |
| 327 | 328 | // A push may bring a blob over the policy size: copy it to the BlobStore by object id (#4490). |
| 328 | 329 | bus.subscribe((event) => onPushLarge({ db, reposRoot, config: { dataDir } }, event), "local"); |
| 330 | bus.subscribe((event) => onPushCdn({ db, reposRoot, config: { dataDir } }, event), "local"); | |
| 329 | 331 | // A pull opened or merged, a release served, an issue dropped or split: |
| 330 | 332 | // estimates settle (#11955). |
| 331 | 333 | bus.subscribe((event) => settleEstimates(db, event), "local"); |
src/blob/cdn.ts added +303
| @@ -0,0 +1,303 @@ | ||
| 1 | /** | |
| 2 | * A git CDN (#18035): a repository's packs and their `.idx` files copied to the BlobStore (the | |
| 3 | * bucket when `S3_*` is set) and handed to a reader as short-lived presigned links, so a cache | |
| 4 | * (the Apple app's household cache, trevato/forge-apple#23) can assemble the repository from | |
| 5 | * object storage and never touch the forge's own clone path, which is unchanged. | |
| 6 | * | |
| 7 | * Keys are `cdn/<repo id>/<pack name>.pack|.idx`: a pack's name is its content's hash, so a pack | |
| 8 | * is uploaded once and a rename of the repository moves nothing. A key is never public: the | |
| 9 | * route (`http/api/cdn.ts`) mints links per request, for a reader of the repository, for | |
| 10 | * `CDN_TTL_S` seconds. | |
| 11 | * | |
| 12 | * Loose objects: the sync job runs `git repack -d` first when the repository holds any, so a push | |
| 13 | * is in a pack before it is uploaded. What a request can still not promise is named: the pointer | |
| 14 | * file `<repo>/forge-cdn.json` records the refs the uploaded packs reach (read before the repack, | |
| 15 | * so every object under them is packed), and the route answers `unreached` with each ref whose | |
| 16 | * oid is not the one recorded. A fork borrows its parent's objects through alternates, so its own | |
| 17 | * packs are not whole: it offers none, and every ref is unreached. | |
| 18 | */ | |
| 19 | ||
| 20 | import { existsSync, readFileSync } from "node:fs"; | |
| 21 | import { readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; | |
| 22 | import { join } from "node:path"; | |
| 23 | import type { App } from "../app.ts"; | |
| 24 | import type { ForgeEvent } from "../core/events.ts"; | |
| 25 | import type { Repo } from "../core/repos.ts"; | |
| 26 | import { runGit } from "../git/env.ts"; | |
| 27 | import { isSafeOid, isSafeRef } from "../git/guard.ts"; | |
| 28 | import { repoDir } from "../git/repos.ts"; | |
| 29 | import { createLog } from "../kernel/log.ts"; | |
| 30 | import { largeStore, offloads, type Home } from "./large.ts"; | |
| 31 | import { pushedRepo } from "./on_push.ts"; | |
| 32 | import type { BlobStore } from "./store.ts"; | |
| 33 | ||
| 34 | /** How long a presigned link lives. */ | |
| 35 | export const CDN_TTL_S = 15 * 60; | |
| 36 | /** The most syncs running at once: a backfill never crowds out a push. */ | |
| 37 | export const MAX_SYNCS = 2; | |
| 38 | /** The most refs and packs one answer lists. */ | |
| 39 | export const MAX_REFS = 5000; | |
| 40 | export const MAX_PACKS = 500; | |
| 41 | /** | |
| 42 | * After a sync was tried (it failed, or left refs unreached), a request does not start another for | |
| 43 | * this long; a push does. | |
| 44 | */ | |
| 45 | export const RETRY_AFTER_MS = 15 * 60 * 1000; | |
| 46 | ||
| 47 | const POINTER = "forge-cdn.json"; | |
| 48 | const PACK = /^pack-[0-9a-f]{40,64}$/; | |
| 49 | ||
| 50 | export const cdnPrefix = (repoId: string): string => `cdn/${repoId}/`; | |
| 51 | ||
| 52 | export interface CdnRef { | |
| 53 | readonly name: string; | |
| 54 | readonly oid: string; | |
| 55 | } | |
| 56 | export interface CdnPack { | |
| 57 | readonly name: string; | |
| 58 | readonly size: number; | |
| 59 | readonly pack: string; | |
| 60 | readonly idx: string; | |
| 61 | } | |
| 62 | export interface CdnListing { | |
| 63 | readonly refs: CdnRef[]; | |
| 64 | /** Names of refs whose commits the packs listed do not reach yet. */ | |
| 65 | readonly unreached: string[]; | |
| 66 | readonly packs: CdnPack[]; | |
| 67 | readonly expiresAt: string; | |
| 68 | } | |
| 69 | ||
| 70 | interface Pointer { | |
| 71 | /** Uploaded packs: name to the bytes of its .pack and .idx together. */ | |
| 72 | readonly held: Record<string, number>; | |
| 73 | /** The refs the held packs reach. */ | |
| 74 | readonly reached: Record<string, string>; | |
| 75 | /** When a sync last began, in ms: a request waits `RETRY_AFTER_MS` after it, a push does not. */ | |
| 76 | readonly tried?: number; | |
| 77 | } | |
| 78 | ||
| 79 | async function readPointer(dir: string): Promise<Pointer> { | |
| 80 | const out: { held: Record<string, number>; reached: Record<string, string>; tried?: number } = { held: {}, reached: {} }; | |
| 81 | try { | |
| 82 | const v = JSON.parse(await readFile(join(dir, POINTER), "utf8")) as Partial<Record<keyof Pointer, unknown>>; | |
| 83 | if (typeof v.tried === "number" && Number.isSafeInteger(v.tried) && v.tried >= 0) out.tried = v.tried; | |
| 84 | for (const [k, n] of Object.entries((v.held ?? {}) as Record<string, unknown>)) | |
| 85 | if (PACK.test(k) && typeof n === "number" && Number.isSafeInteger(n) && n >= 0) out.held[k] = n; | |
| 86 | for (const [k, o] of Object.entries((v.reached ?? {}) as Record<string, unknown>)) | |
| 87 | if (isSafeRef(k) && typeof o === "string" && isSafeOid(o)) out.reached[k] = o; | |
| 88 | } catch { | |
| 89 | // no pointer yet: nothing held | |
| 90 | } | |
| 91 | return out; | |
| 92 | } | |
| 93 | ||
| 94 | async function writePointer(dir: string, p: Pointer): Promise<void> { | |
| 95 | const tmp = join(dir, `${POINTER}.tmp`); | |
| 96 | await writeFile(tmp, JSON.stringify(p)); | |
| 97 | await rename(tmp, join(dir, POINTER)); | |
| 98 | } | |
| 99 | ||
| 100 | /** Branches and tags, as `git for-each-ref` names them. */ | |
| 101 | export async function cdnRefs(dir: string): Promise<CdnRef[]> { | |
| 102 | const r = await runGit(["for-each-ref", "--format=%(objectname) %(refname)", "refs/heads", "refs/tags"], { | |
| 103 | cwd: dir, | |
| 104 | timeoutMs: 30_000, | |
| 105 | }); | |
| 106 | if (!r.ok) return []; | |
| 107 | const refs: CdnRef[] = []; | |
| 108 | for (const line of r.value.split("\n")) { | |
| 109 | const at = line.indexOf(" "); | |
| 110 | const oid = line.slice(0, at); | |
| 111 | const name = line.slice(at + 1); | |
| 112 | if (at > 0 && isSafeOid(oid) && isSafeRef(name)) refs.push({ name, oid }); | |
| 113 | } | |
| 114 | return refs.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)).slice(0, MAX_REFS); | |
| 115 | } | |
| 116 | ||
| 117 | /** The packs on disk that have their index: name to the bytes of both files. */ | |
| 118 | export async function packsOnDisk(dir: string): Promise<Map<string, number>> { | |
| 119 | const out = new Map<string, number>(); | |
| 120 | const pack = join(dir, "objects", "pack"); | |
| 121 | let names: string[]; | |
| 122 | try { | |
| 123 | names = await readdir(pack); | |
| 124 | } catch { | |
| 125 | return out; | |
| 126 | } | |
| 127 | for (const f of names) { | |
| 128 | if (!f.endsWith(".pack")) continue; | |
| 129 | const name = f.slice(0, -5); | |
| 130 | if (!PACK.test(name)) continue; | |
| 131 | try { | |
| 132 | out.set(name, (await stat(join(pack, f))).size + (await stat(join(pack, `${name}.idx`))).size); | |
| 133 | } catch { | |
| 134 | // a pack still being written has no index yet | |
| 135 | } | |
| 136 | } | |
| 137 | return out; | |
| 138 | } | |
| 139 | ||
| 140 | const borrows = (dir: string): boolean => existsSync(join(dir, "objects", "info", "alternates")); | |
| 141 | ||
| 142 | /** Copy what is not held, drop what is gone from disk; returns how many packs were uploaded. */ | |
| 143 | export async function syncCdn(input: { store: BlobStore; dir: string; repoId: string }): Promise<number> { | |
| 144 | const { store, dir, repoId } = input; | |
| 145 | if (!existsSync(dir) || borrows(dir)) return 0; | |
| 146 | // Written first: whatever happens next (a repack that fails, a bucket that is down), a request | |
| 147 | // finds the attempt on record and leaves the retry to the interval or the next push. | |
| 148 | const before = await readPointer(dir); | |
| 149 | await writePointer(dir, { ...before, tried: Date.now() }); | |
| 150 | const refs = await cdnRefs(dir); // before the repack: every object under these is then packed | |
| 151 | const loose = await runGit(["count-objects"], { cwd: dir, timeoutMs: 30_000 }); | |
| 152 | const hasLoose = !loose.ok || !loose.value.startsWith("0 "); | |
| 153 | const packed = hasLoose ? await runGit(["repack", "-d", "-q"], { cwd: dir, timeoutMs: 300_000 }) : undefined; | |
| 154 | const whole = packed === undefined || packed.ok; | |
| 155 | const onDisk = await packsOnDisk(dir); | |
| 156 | const pointer = await readPointer(dir); | |
| 157 | const held: Record<string, number> = {}; | |
| 158 | let copied = 0; | |
| 159 | for (const [name, size] of onDisk) { | |
| 160 | if (!existsSync(dir)) break; // the repository was deleted under us: upload nothing more | |
| 161 | const key = `${cdnPrefix(repoId)}${name}`; | |
| 162 | const stored = pointer.held[name] === size && (await store.size(`${key}.pack`)) !== undefined && (await store.size(`${key}.idx`)) !== undefined; | |
| 163 | if (!stored) { | |
| 164 | await store.put(`${key}.pack`, Bun.file(join(dir, "objects", "pack", `${name}.pack`))); | |
| 165 | await store.put(`${key}.idx`, Bun.file(join(dir, "objects", "pack", `${name}.idx`))); | |
| 166 | copied++; | |
| 167 | } | |
| 168 | held[name] = size; | |
| 169 | } | |
| 170 | const reached: Record<string, string> = {}; | |
| 171 | if (whole) for (const r of refs) reached[r.name] = r.oid; | |
| 172 | await writePointer(dir, { held, reached, ...(pointer.tried === undefined ? {} : { tried: pointer.tried }) }); | |
| 173 | for (const key of await store.list(cdnPrefix(repoId))) | |
| 174 | if (!(key.slice(cdnPrefix(repoId).length).replace(/\.(pack|idx)$/, "") in held)) await store.delete(key).catch(() => {}); | |
| 175 | return copied; | |
| 176 | } | |
| 177 | ||
| 178 | /** Take a repository's packs back from the store (deleted). */ | |
| 179 | export async function retractCdn(app: Home, repo: Pick<Repo, "id" | "ownerName" | "name">): Promise<void> { | |
| 180 | await rm(join(repoDir(app.reposRoot, repo.ownerName, repo.name), POINTER), { force: true }); | |
| 181 | const store = largeStore(app.config.dataDir); | |
| 182 | for (const key of await store.list(cdnPrefix(repo.id)).catch(() => [])) await store.delete(key).catch(() => {}); | |
| 183 | } | |
| 184 | ||
| 185 | /** | |
| 186 | * The answer for one reader of `repo`: current refs, the uploaded packs with fresh links, and the | |
| 187 | * refs not yet reached. undefined when the store cannot sign links (a directory). Never scans packs | |
| 188 | * for objects and never uploads: a stale pointer is the sync job's to mend, started by the caller. | |
| 189 | */ | |
| 190 | export async function cdnListing( | |
| 191 | app: Pick<Home, "reposRoot">, | |
| 192 | repo: Pick<Repo, "id" | "ownerName" | "name">, | |
| 193 | store: BlobStore, | |
| 194 | now = Date.now(), | |
| 195 | ): Promise<CdnListing | undefined> { | |
| 196 | const sign = store.presign?.bind(store); | |
| 197 | if (sign === undefined) return undefined; | |
| 198 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 199 | const [refs, pointer, onDisk] = await Promise.all([cdnRefs(dir), readPointer(dir), packsOnDisk(dir)]); | |
| 200 | const packs: CdnPack[] = []; | |
| 201 | if (!borrows(dir)) | |
| 202 | for (const name of [...onDisk.keys()].sort().slice(0, MAX_PACKS)) { | |
| 203 | const size = onDisk.get(name)!; | |
| 204 | if (pointer.held[name] !== size) continue; | |
| 205 | const key = `${cdnPrefix(repo.id)}${name}`; | |
| 206 | packs.push({ | |
| 207 | name, | |
| 208 | size, | |
| 209 | pack: sign(`${key}.pack`, { method: "GET", expiresInS: CDN_TTL_S }), | |
| 210 | idx: sign(`${key}.idx`, { method: "GET", expiresInS: CDN_TTL_S }), | |
| 211 | }); | |
| 212 | } | |
| 213 | const unreached = refs.filter((r) => pointer.reached[r.name] !== r.oid || borrows(dir)).map((r) => r.name); | |
| 214 | return { refs, unreached, packs, expiresAt: new Date(now + CDN_TTL_S * 1000).toISOString() }; | |
| 215 | } | |
| 216 | ||
| 217 | /** | |
| 218 | * Whether a request may start a sync: not for a repository that borrows through alternates (its | |
| 219 | * packs are never whole, a sync would end at once), and not within `RETRY_AFTER_MS` of the last | |
| 220 | * attempt, whether that one failed or not. A push starts one regardless (`onPushCdn`). | |
| 221 | */ | |
| 222 | export async function mendable( | |
| 223 | app: Pick<Home, "reposRoot">, | |
| 224 | repo: Pick<Repo, "ownerName" | "name">, | |
| 225 | now = Date.now(), | |
| 226 | ): Promise<boolean> { | |
| 227 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 228 | if (borrows(dir)) return false; | |
| 229 | const { tried } = await readPointer(dir); | |
| 230 | return tried === undefined || now - tried >= RETRY_AFTER_MS; | |
| 231 | } | |
| 232 | ||
| 233 | /** | |
| 234 | * The bytes the store holds for these repositories, from their pointer files alone (no git, no | |
| 235 | * network): the figure the economics page, its API and its terminal screen show. | |
| 236 | */ | |
| 237 | export function cdnBytes(app: Pick<Home, "reposRoot">, repos: Pick<Repo, "ownerName" | "name">[]): { bytes: number; repos: number } { | |
| 238 | let bytes = 0; | |
| 239 | let held = 0; | |
| 240 | for (const r of repos) { | |
| 241 | let v: { held?: Record<string, unknown> }; | |
| 242 | try { | |
| 243 | v = JSON.parse(readFileSync(join(repoDir(app.reposRoot, r.ownerName, r.name), POINTER), "utf8")) as typeof v; | |
| 244 | } catch { | |
| 245 | continue; | |
| 246 | } | |
| 247 | let mine = 0; | |
| 248 | for (const [k, n] of Object.entries(v.held ?? {})) if (PACK.test(k) && typeof n === "number" && Number.isSafeInteger(n) && n > 0) mine += n; | |
| 249 | if (mine > 0) held++; | |
| 250 | bytes += mine; | |
| 251 | } | |
| 252 | return { bytes, repos: held }; | |
| 253 | } | |
| 254 | ||
| 255 | /** | |
| 256 | * What the store holds for a repository, from its pointer and the disk: no network, no links. The | |
| 257 | * page of storage and the terminal's rows read this. | |
| 258 | */ | |
| 259 | export async function cdnSummary( | |
| 260 | app: Pick<Home, "reposRoot">, | |
| 261 | repo: Pick<Repo, "ownerName" | "name">, | |
| 262 | ): Promise<{ packs: { name: string; size: number }[]; bytes: number; unreached: number }> { | |
| 263 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 264 | const [refs, pointer, onDisk] = await Promise.all([cdnRefs(dir), readPointer(dir), packsOnDisk(dir)]); | |
| 265 | const packs = [...onDisk].filter(([n, size]) => pointer.held[n] === size).map(([name, size]) => ({ name, size })); | |
| 266 | return { | |
| 267 | packs: packs.sort((a, b) => (a.name < b.name ? -1 : 1)), | |
| 268 | bytes: packs.reduce((t, p) => t + p.size, 0), | |
| 269 | unreached: refs.filter((r) => pointer.reached[r.name] !== r.oid).length, | |
| 270 | }; | |
| 271 | } | |
| 272 | ||
| 273 | // ---- when ---- | |
| 274 | ||
| 275 | const log = createLog("git-cdn"); | |
| 276 | ||
| 277 | /** Sync in the background: one run per repository, at most MAX_SYNCS at once. */ | |
| 278 | export function noteCdn(app: Home, repo: Pick<Repo, "id" | "ownerName" | "name">, using: { store?: BlobStore } = {}): boolean { | |
| 279 | const store = using.store ?? largeStore(app.config.dataDir); | |
| 280 | const { running, settled } = offloads(app); | |
| 281 | const mine = `cdn:${repo.id}`; | |
| 282 | if (store.presign === undefined || running.has(mine)) return false; | |
| 283 | if (borrows(repoDir(app.reposRoot, repo.ownerName, repo.name))) return false; | |
| 284 | if ([...running].filter((k) => k.startsWith("cdn:")).length >= MAX_SYNCS) return false; | |
| 285 | running.add(mine); | |
| 286 | const job: Promise<void> = syncCdn({ store, dir: repoDir(app.reposRoot, repo.ownerName, repo.name), repoId: repo.id }) | |
| 287 | .then(() => {}) | |
| 288 | .catch((error: unknown) => { | |
| 289 | log.warn("packs not stored", { repo: `${repo.ownerName}/${repo.name}`, why: String(error).slice(0, 200) }); | |
| 290 | }) | |
| 291 | .finally(() => { | |
| 292 | running.delete(mine); | |
| 293 | settled.delete(job); | |
| 294 | }); | |
| 295 | settled.add(job); | |
| 296 | return true; | |
| 297 | } | |
| 298 | ||
| 299 | /** Any push may bring a pack. */ | |
| 300 | export function onPushCdn(app: Home & Pick<App, "db">, event: ForgeEvent, using: { store?: BlobStore } = {}): void { | |
| 301 | const repo = pushedRepo(app, event); | |
| 302 | if (repo) noteCdn(app, repo, using); | |
| 303 | } |
src/blob/large.ts +3 −3
| @@ -20,11 +20,12 @@ import { readFile, rename, rm, writeFile } from "node:fs/promises"; | ||
| 20 | 20 | import { join } from "node:path"; |
| 21 | 21 | import type { App } from "../app.ts"; |
| 22 | 22 | import type { ForgeEvent } from "../core/events.ts"; |
| 23 | import { getRepoById, type Repo } from "../core/repos.ts"; | |
| 23 | import type { Repo } from "../core/repos.ts"; | |
| 24 | 24 | import { gitEnv, runGit } from "../git/env.ts"; |
| 25 | 25 | import { isSafeOid } from "../git/guard.ts"; |
| 26 | 26 | import { repoDir } from "../git/repos.ts"; |
| 27 | 27 | import { createLog } from "../kernel/log.ts"; |
| 28 | import { pushedRepo } from "./on_push.ts"; | |
| 28 | 29 | import { dirStore, s3FromEnv, s3Store, type BlobStore } from "./store.ts"; |
| 29 | 30 | |
| 30 | 31 | /** What this module needs of a forge. */ |
| @@ -289,7 +290,6 @@ export function onPushLarge( | ||
| 289 | 290 | event: ForgeEvent, |
| 290 | 291 | using: { store?: BlobStore; threshold?: number } = {}, |
| 291 | 292 | ): void { |
| 292 | if (event.kind !== "push" || event.repoId === null) return; | |
| 293 | const repo = getRepoById(app.db, event.repoId); | |
| 293 | const repo = pushedRepo(app, event); | |
| 294 | 294 | if (repo) noteLarge(app, repo, using); |
| 295 | 295 | } |
src/blob/on_push.ts added +9
| @@ -0,0 +1,9 @@ | ||
| 1 | import type { App } from "../app.ts"; | |
| 2 | import type { ForgeEvent } from "../core/events.ts"; | |
| 3 | import { getRepoById, type Repo } from "../core/repos.ts"; | |
| 4 | ||
| 5 | /** A push event's repository, for the background jobs a push starts (large blobs, the git CDN). */ | |
| 6 | export function pushedRepo(app: Pick<App, "db">, event: ForgeEvent): Repo | undefined { | |
| 7 | if (event.kind !== "push" || event.repoId === null) return undefined; | |
| 8 | return getRepoById(app.db, event.repoId); | |
| 9 | } |
src/contract/openapi/routes/getApiV1ForgeEconomics.ts +1 −1
| @@ -4,7 +4,7 @@ export const route: Route = { | ||
| 4 | 4 | method: "get", |
| 5 | 5 | path: "/api/v1/forge/economics", |
| 6 | 6 | summary: "Read the profit slider, the policy it means and this month's cost", |
| 7 | detail: "The profit slider: position (0 cheapest to 100 most responsive), marginPct, the policy the position means (sleep windows in ms, idle-pull window, cloud spill share; null is never), placement (whether a cloud body takes bursts, the owned-node label, in words), the operator's prices in US dollars, this UTC month's cost so far ({ owned, cloud, storage, crew, total } in USD) and the last changes (a person admin's token)", | |
| 7 | detail: "The profit slider: position (0 cheapest to 100 most responsive), marginPct, the policy the position means (sleep windows in ms, idle-pull window, cloud spill share; null is never), placement (whether a cloud body takes bursts, the owned-node label, in words), the operator's prices in US dollars, this UTC month's cost so far ({ owned, cloud, storage, crew, total } in USD), `cdn` ({ bytes, repos }: the packs the git CDN holds in the bucket) and the last changes (a person admin's token)", | |
| 8 | 8 | auth: true, |
| 9 | 9 | role: "admin", |
| 10 | 10 | refusals: { |
src/contract/openapi/routes/getApiV1ReposOwnerNameCdn.ts added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | import { int, list, obj, str } from "../schema_kit.ts"; | |
| 2 | import { REPO, type Route } from "../shared.ts"; | |
| 3 | ||
| 4 | export const route: Route = { | |
| 5 | method: "get", | |
| 6 | path: `${REPO}/cdn`, | |
| 7 | summary: "A repository's packs as presigned links, to fetch from object storage", | |
| 8 | detail: | |
| 9 | "The git CDN (#18035): answers { refs: [{ name, oid }], unreached: [ref name], packs: [{ name, size, pack, idx }], expiresAt }; refs are the branches and tags now; each pack's pack and idx are presigned, read-only bucket links minted for this request and good for 15 minutes (expiresAt), with no forge credential needed to GET them; unreached names the refs the packs do not reach yet (a push the sync job has not stored, a fork that borrows its parent's objects), which a client fetches from git as usual, and asking starts the job that mends it; loose objects are packed by that job, never on the request; the repository's own clone path is unchanged; a private repository needs a token, its packs are never at a public path; cache-control private, no-store; 404 cdn_off when the forge has no object storage bucket", | |
| 10 | auth: false, | |
| 11 | role: "anonymous", | |
| 12 | response: obj({ | |
| 13 | refs: list(obj({ name: str, oid: str })), | |
| 14 | unreached: list(str), | |
| 15 | packs: list(obj({ name: str, size: int, pack: str, idx: str })), | |
| 16 | expiresAt: str, | |
| 17 | }), | |
| 18 | refusals: { cdn_off: "404: the forge has no object storage bucket to serve packs from" }, | |
| 19 | errorStatus: { 404: "`cdn_off`: the forge has no object storage bucket" }, | |
| 20 | refuses: [404], | |
| 21 | }; |
src/contract/openapi/routes/index.ts +1
| @@ -175,6 +175,7 @@ export { route as getApiV1ReposOwnerNameBuilds } from "./getApiV1ReposOwnerNameB | ||
| 175 | 175 | export { route as getApiV1ReposOwnerNameBuildsLabelCart } from "./getApiV1ReposOwnerNameBuildsLabelCart.ts"; |
| 176 | 176 | export { route as getApiV1ReposOwnerNameBuildsLabelShots } from "./getApiV1ReposOwnerNameBuildsLabelShots.ts"; |
| 177 | 177 | export { route as getApiV1ReposOwnerNameBuildsLabelShotsLooks } from "./getApiV1ReposOwnerNameBuildsLabelShotsLooks.ts"; |
| 178 | export { route as getApiV1ReposOwnerNameCdn } from "./getApiV1ReposOwnerNameCdn.ts"; | |
| 178 | 179 | export { route as getApiV1ReposOwnerNameChangesRoom } from "./getApiV1ReposOwnerNameChangesRoom.ts"; |
| 179 | 180 | export { route as getApiV1ReposOwnerNameChapters } from "./getApiV1ReposOwnerNameChapters.ts"; |
| 180 | 181 | export { route as getApiV1ReposOwnerNameCommits } from "./getApiV1ReposOwnerNameCommits.ts"; |
src/contract/tags.ts +1
src/http/api.ts +2
| @@ -367,6 +367,7 @@ import { userRoutes } from "./api/user.ts"; | ||
| 367 | 367 | import { appRoutes } from "./api/app.ts"; |
| 368 | 368 | import { appPullsRoutes } from "./api/app_pulls.ts"; |
| 369 | 369 | import { buildRoutes } from "./api/builds.ts"; |
| 370 | import { cdnRoutes } from "./api/cdn.ts"; | |
| 370 | 371 | import { buildShotRoutes } from "./api/build_shots.ts"; |
| 371 | 372 | import { buildCartRoutes } from "./api/build_cart.ts"; |
| 372 | 373 | import { iterationRoutes } from "./api/iterations.ts"; |
| @@ -3300,6 +3301,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 3300 | 3301 | appRoutes(router); |
| 3301 | 3302 | appPullsRoutes(router); |
| 3302 | 3303 | buildRoutes(router); |
| 3304 | cdnRoutes(router); | |
| 3303 | 3305 | buildShotRoutes(router); |
| 3304 | 3306 | buildCartRoutes(router); |
| 3305 | 3307 | iterationRoutes(router); |
src/http/api/cdn.ts added +52
| @@ -0,0 +1,52 @@ | ||
| 1 | /** | |
| 2 | * The git CDN's one route (#18035, `blob/cdn.ts`): GET /api/v1/repos/:owner/:name/cdn answers a | |
| 3 | * reader of the repository with its refs, which of them the packs do not reach yet, and each | |
| 4 | * pack's presigned, read-only links, good for 15 minutes. Minted per request and never cached. | |
| 5 | */ | |
| 6 | ||
| 7 | import { cdnListing, mendable, noteCdn } from "../../blob/cdn.ts"; | |
| 8 | import { largeStore } from "../../blob/large.ts"; | |
| 9 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 10 | import type { App } from "../../app.ts"; | |
| 11 | import { minuteLimiter } from "../../actions/outside_limits.ts"; | |
| 12 | import type { RateLimiter } from "../../core/ratelimit.ts"; | |
| 13 | import { bucketOf, clientAddress } from "../peer.ts"; | |
| 14 | import { loadRepo } from "../api.ts"; | |
| 15 | import type { Handler } from "../context.ts"; | |
| 16 | import { json, notFound } from "../respond.ts"; | |
| 17 | import type { Router } from "../router.ts"; | |
| 18 | ||
| 19 | const PER_MINUTE = 20; | |
| 20 | const limiters = new WeakMap<App, RateLimiter>(); | |
| 21 | const strangers = (app: App): RateLimiter => { | |
| 22 | let limiter = limiters.get(app); | |
| 23 | if (limiter === undefined) limiters.set(app, (limiter = minuteLimiter(PER_MINUTE))); | |
| 24 | return limiter; | |
| 25 | }; | |
| 26 | ||
| 27 | export function cdnRoutes(router: Router<Handler>): void { | |
| 28 | router.add("GET", "/api/v1/repos/:owner/:name/cdn", async (ctx) => { | |
| 29 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 30 | const repo = loadRepo(ctx); | |
| 31 | if (!repo) return notFound(); | |
| 32 | // Anyone may read a public repository, and each read runs git: a stranger is counted by the | |
| 33 | // socket's address (never a header) and told to wait past its share. | |
| 34 | if (!ctx.auth.user) { | |
| 35 | const verdict = strangers(ctx.app).take(bucketOf(clientAddress(ctx.request)), "ro"); | |
| 36 | if (!verdict.allowed) | |
| 37 | return json({ error: "rate_limited", message: "too many reads from this address; wait and ask again" }, 429, { | |
| 38 | "retry-after": String(Math.max(1, Math.ceil(verdict.retryAfter))), | |
| 39 | }); | |
| 40 | } | |
| 41 | const store = largeStore(ctx.app.config.dataDir); | |
| 42 | const listing = await cdnListing(ctx.app, repo, store); | |
| 43 | if (listing === undefined) | |
| 44 | return json({ error: "cdn_off", message: "this forge has no object storage bucket to serve packs from" }, 404); | |
| 45 | // A repository never synced, or one with refs the packs do not reach, is mended in the | |
| 46 | // background; the answer says so now and the next one is whole. | |
| 47 | // A failed or fruitless attempt, a fork, is not started again by a request: the pointer | |
| 48 | // carries when the last one began (`mendable`). | |
| 49 | if (listing.unreached.length > 0 && (await mendable(ctx.app, repo))) noteCdn(ctx.app, repo, { store }); | |
| 50 | return json(listing, 200, { "cache-control": "private, no-store", vary: "authorization, cookie" }); | |
| 51 | }); | |
| 52 | } |
src/http/api/economics.ts +1
src/http/crawl.ts +1 −1
| @@ -77,7 +77,7 @@ export const isDeepPath = (pathname: string): boolean => DEEP.test(pathname); | ||
| 77 | 77 | * API routes that read the same files and history. A clone (`.git`) stays open: |
| 78 | 78 | * the Shield protects the pages, and turning clones off would break every mirror. |
| 79 | 79 | */ |
| 80 | const SHIELDED_API = /^\/api\/v1\/repos\/[^/]+\/[^/]+\/(?:contents|commits|git|raw|archive|media|tree|blob|compare|branches|tags)(?:\/|$)/; | |
| 80 | const SHIELDED_API = /^\/api\/v1\/repos\/[^/]+\/[^/]+\/(?:cdn|contents|commits|git|raw|archive|media|tree|blob|compare|branches|tags)(?:\/|$)/; | |
| 81 | 81 | const SHIELDED_MEDIA = /^\/(?:origins\/[^/]+\/r\/)?[^/]+\/[^/]+\/media(?:\/|$)/; |
| 82 | 82 | export const isShieldedPath = (pathname: string): boolean => |
| 83 | 83 | DEEP.test(pathname) || SHIELDED_MEDIA.test(pathname) || SHIELDED_API.test(pathname); |
src/http/lazy_lists.ts +1
| @@ -1621,6 +1621,7 @@ export const API_ROUTES = [ | ||
| 1621 | 1621 | ["POST", "/api/v1/repos/:owner/:name/builds"], |
| 1622 | 1622 | ["DELETE", "/api/v1/repos/:owner/:name/builds/:label"], |
| 1623 | 1623 | ["PATCH", "/api/v1/repos/:owner/:name/builds/:label"], |
| 1624 | ["GET", "/api/v1/repos/:owner/:name/cdn"], | |
| 1624 | 1625 | ["GET", "/api/v1/repos/:owner/:name/builds/:label/shots"], |
| 1625 | 1626 | ["POST", "/api/v1/repos/:owner/:name/builds/:label/shots"], |
| 1626 | 1627 | ["GET", "/api/v1/repos/:owner/:name/builds/:label/shots/looks"], |
src/tui/screens/cdn.ts added +38
| @@ -0,0 +1,38 @@ | ||
| 1 | /** | |
| 2 | * A repository's git CDN in the terminal (#18035): the packs the object store holds for it, their | |
| 3 | * size, and how many refs they do not reach yet, from the same read the API's route builds on | |
| 4 | * (`blob/cdn.ts`, `cdnSummary`). Whoever may read the repository sees it; the links themselves | |
| 5 | * are minted by GET /api/v1/repos/<owner>/<name>/cdn. | |
| 6 | */ | |
| 7 | import { cdnSummary } from "../../blob/cdn.ts"; | |
| 8 | import { canRead, type Repo } from "../../core/repos.ts"; | |
| 9 | import { fileSize } from "../../web/ui.ts"; | |
| 10 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 11 | import type { Command } from "../app/palette.ts"; | |
| 12 | import type { Session } from "../session.ts"; | |
| 13 | import type { ListRow } from "./common.ts"; | |
| 14 | import { repoListCommand, repoListScreen } from "./repo_list.ts"; | |
| 15 | ||
| 16 | /** What the screen lists: a total row, then each pack, for someone who may read the repository. */ | |
| 17 | export async function cdnRows(f: Session, repo: Repo): Promise<ListRow[]> { | |
| 18 | if (!canRead(f.app.db, repo, f.user)) return []; | |
| 19 | const s = await cdnSummary(f.app, repo); | |
| 20 | return [ | |
| 21 | { | |
| 22 | title: `${s.packs.length} packs · ${fileSize(s.bytes)} in storage`, | |
| 23 | meta: s.unreached === 0 ? "every ref is in the packs" : `${s.unreached} refs not in the packs yet`, | |
| 24 | }, | |
| 25 | ...s.packs.map((p) => ({ title: `${p.name} · ${fileSize(p.size)}`, meta: ".pack and .idx" })), | |
| 26 | ]; | |
| 27 | } | |
| 28 | ||
| 29 | export const cdnScreen = (f: Session, ctx: Ctx, repo: Repo): Screen => | |
| 30 | repoListScreen(ctx, repo, "Git CDN", () => cdnRows(f, repo)); | |
| 31 | ||
| 32 | export const cdnCommands = (f: Session, ctx: Ctx, repo: Repo | undefined): Command[] => | |
| 33 | repoListCommand(ctx, repo, { | |
| 34 | id: "git-cdn", | |
| 35 | heading: "Git CDN", | |
| 36 | hint: "packs held in object storage, and what they reach", | |
| 37 | screen: (r) => cdnScreen(f, ctx, r), | |
| 38 | }); |
src/tui/screens/economics.ts +2 −1
| @@ -27,6 +27,7 @@ import type { Ctx, Screen } from "../app/app.ts"; | ||
| 27 | 27 | import { binding } from "../app/keys.ts"; |
| 28 | 28 | import { style } from "../term/style.ts"; |
| 29 | 29 | import { truncate } from "../term/width.ts"; |
| 30 | import { fileSize } from "../../web/ui.ts"; | |
| 30 | 31 | import type { Session } from "../session.ts"; |
| 31 | 32 | import { fill, len, split } from "../ui/layout.ts"; |
| 32 | 33 | import { ListState, confirmScreen, drawList, promptScreen, type ListRow } from "./common.ts"; |
| @@ -115,7 +116,7 @@ const LEVERS: readonly Lever[] = [ | ||
| 115 | 116 | function monthWords(e: EconomicsView): string { |
| 116 | 117 | const c = e.month.cost; |
| 117 | 118 | const usd = (n: number) => `$${n.toFixed(2)}`; |
| 118 | return `This month so far: owned ${usd(c.owned)} · cloud ${usd(c.cloud)} · storage ${usd(c.storage)} · crew ${usd(c.crew)} · total ${usd(c.total)}`; | |
| 119 | return `This month so far: owned ${usd(c.owned)} · cloud ${usd(c.cloud)} · storage ${usd(c.storage)} · crew ${usd(c.crew)} · total ${usd(c.total)} · git cdn ${fileSize(e.cdn.bytes)} in the bucket`; | |
| 119 | 120 | } |
| 120 | 121 | |
| 121 | 122 | export function economicsScreen(f: Session, ctx: Ctx): Screen { |
src/tui/screens/largefiles.ts +11 −40
| @@ -2,15 +2,14 @@ | ||
| 2 | 2 | * A repository's large files in the terminal (#4490): the /:owner/:name/large page's rows, from |
| 3 | 3 | * the same read (`blob/large.ts`, `largeFiles`). Whoever may read the repository sees it. |
| 4 | 4 | */ |
| 5 | import { keyOf } from "../../web/keymap.ts"; | |
| 6 | 5 | import { largeFiles, type LargeFile } from "../../blob/large.ts"; |
| 7 | 6 | import { canRead, type Repo } from "../../core/repos.ts"; |
| 8 | 7 | import { fileSize } from "../../web/ui.ts"; |
| 9 | 8 | import type { Ctx, Screen } from "../app/app.ts"; |
| 10 | 9 | import type { Command } from "../app/palette.ts"; |
| 11 | import { binding } from "../app/keys.ts"; | |
| 12 | 10 | import type { Session } from "../session.ts"; |
| 13 | import { ListState, drawList, runAsync, type ListRow } from "./common.ts"; | |
| 11 | import type { ListRow } from "./common.ts"; | |
| 12 | import { repoListCommand, repoListScreen } from "./repo_list.ts"; | |
| 14 | 13 | |
| 15 | 14 | export const largeRow = (f: LargeFile): ListRow => ({ |
| 16 | 15 | title: `${f.path ?? "(only in history)"} · ${fileSize(f.size)}`, |
| @@ -22,41 +21,13 @@ export async function largeRows(f: Session, repo: Repo): Promise<ListRow[]> { | ||
| 22 | 21 | return canRead(f.app.db, repo, f.user) ? (await largeFiles(f.app, repo)).files.map(largeRow) : []; |
| 23 | 22 | } |
| 24 | 23 | |
| 25 | export function largeFilesScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | |
| 26 | const state = new ListState(); | |
| 27 | let rows: ListRow[] = []; | |
| 28 | let loaded = false; | |
| 29 | const load = () => | |
| 30 | runAsync(ctx, async () => { | |
| 31 | rows = await largeRows(f, repo); | |
| 32 | loaded = true; | |
| 33 | }); | |
| 34 | load(); | |
| 35 | return { | |
| 36 | title: `${repo.ownerName}/${repo.name} — Large files`, | |
| 37 | keys: [binding(["j", "k"], "move cursor"), binding([keyOf("reread")], "read again")], | |
| 38 | render(area, s) { | |
| 39 | drawList(s, area, ctx.theme.c, state, loaded ? rows : []); | |
| 40 | }, | |
| 41 | key(e) { | |
| 42 | if (e.key === keyOf("reread")) { | |
| 43 | load(); | |
| 44 | return true; | |
| 45 | } | |
| 46 | return state.key(e, rows.length); | |
| 47 | }, | |
| 48 | }; | |
| 49 | } | |
| 24 | export const largeFilesScreen = (f: Session, ctx: Ctx, repo: Repo): Screen => | |
| 25 | repoListScreen(ctx, repo, "Large files", () => largeRows(f, repo)); | |
| 50 | 26 | |
| 51 | /** The palette's command while a repository is open. */ | |
| 52 | export function largeFilesCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] { | |
| 53 | if (repo === undefined) return []; | |
| 54 | return [ | |
| 55 | { | |
| 56 | id: "large-files", | |
| 57 | title: `${repo.ownerName}/${repo.name} — Large files`, | |
| 58 | hint: "blobs over the size policy, and where each lives", | |
| 59 | run: () => ctx.push(largeFilesScreen(f, ctx, repo)), | |
| 60 | }, | |
| 61 | ]; | |
| 62 | } | |
| 27 | export const largeFilesCommands = (f: Session, ctx: Ctx, repo: Repo | undefined): Command[] => | |
| 28 | repoListCommand(ctx, repo, { | |
| 29 | id: "large-files", | |
| 30 | heading: "Large files", | |
| 31 | hint: "blobs over the size policy, and where each lives", | |
| 32 | screen: (r) => largeFilesScreen(f, ctx, r), | |
| 33 | }); |
src/tui/screens/repo_list.ts added +54
| @@ -0,0 +1,54 @@ | ||
| 1 | /** | |
| 2 | * A repository's read-only list in the terminal: rows read again on `reread`, shown to whoever | |
| 3 | * may read the repository, opened by one palette command. The large-files and git CDN screens are | |
| 4 | * two instances. | |
| 5 | */ | |
| 6 | import { keyOf } from "../../web/keymap.ts"; | |
| 7 | import type { Repo } from "../../core/repos.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 { ListState, drawList, runAsync, type ListRow } from "./common.ts"; | |
| 12 | ||
| 13 | export function repoListScreen(ctx: Ctx, repo: Repo, heading: string, read: () => Promise<ListRow[]>): Screen { | |
| 14 | const state = new ListState(); | |
| 15 | let rows: ListRow[] = []; | |
| 16 | let loaded = false; | |
| 17 | const load = () => | |
| 18 | runAsync(ctx, async () => { | |
| 19 | rows = await read(); | |
| 20 | loaded = true; | |
| 21 | }); | |
| 22 | load(); | |
| 23 | return { | |
| 24 | title: `${repo.ownerName}/${repo.name} — ${heading}`, | |
| 25 | keys: [binding(["j", "k"], "move cursor"), binding([keyOf("reread")], "read again")], | |
| 26 | render(area, s) { | |
| 27 | drawList(s, area, ctx.theme.c, state, loaded ? rows : []); | |
| 28 | }, | |
| 29 | key(e) { | |
| 30 | if (e.key === keyOf("reread")) { | |
| 31 | load(); | |
| 32 | return true; | |
| 33 | } | |
| 34 | return state.key(e, rows.length); | |
| 35 | }, | |
| 36 | }; | |
| 37 | } | |
| 38 | ||
| 39 | /** The palette's command while a repository is open. */ | |
| 40 | export function repoListCommand( | |
| 41 | ctx: Ctx, | |
| 42 | repo: Repo | undefined, | |
| 43 | entry: { id: string; heading: string; hint: string; screen: (repo: Repo) => Screen }, | |
| 44 | ): Command[] { | |
| 45 | if (repo === undefined) return []; | |
| 46 | return [ | |
| 47 | { | |
| 48 | id: entry.id, | |
| 49 | title: `${repo.ownerName}/${repo.name} — ${entry.heading}`, | |
| 50 | hint: entry.hint, | |
| 51 | run: () => ctx.push(entry.screen(repo)), | |
| 52 | }, | |
| 53 | ]; | |
| 54 | } |
src/tui/screens/workspace.ts +2
| @@ -179,6 +179,7 @@ import { dependenciesCommands } from "./dependencies.ts"; | ||
| 179 | 179 | import { demoCommands } from "./demo.ts"; |
| 180 | 180 | import { appReleasesCommands } from "./appreleases.ts"; |
| 181 | 181 | import { largeFilesCommands } from "./largefiles.ts"; |
| 182 | import { cdnCommands } from "./cdn.ts"; | |
| 182 | 183 | import { migrationCommands } from "./migration.ts"; |
| 183 | 184 | import { dropCommands } from "./drop.ts"; |
| 184 | 185 | import { recheckWindowCommands } from "./recheckwindow.ts"; |
| @@ -1416,6 +1417,7 @@ export function workspaceScreen( | ||
| 1416 | 1417 | ...demoCommands(f, ctx, repo), |
| 1417 | 1418 | ...appReleasesCommands(f, ctx, repo), |
| 1418 | 1419 | ...largeFilesCommands(f, ctx, repo), |
| 1420 | ...cdnCommands(f, ctx, repo), | |
| 1419 | 1421 | ...dropCommands(f, ctx, repo), |
| 1420 | 1422 | ...migrationCommands(f, ctx, repo), |
| 1421 | 1423 | ...recheckWindowCommands(f, ctx, repo, () => screen), |
src/web/pages/economics.ts +7 −2
| @@ -24,7 +24,7 @@ import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts"; | ||
| 24 | 24 | import { field, readForm } from "../form.ts"; |
| 25 | 25 | import { html } from "../html.ts"; |
| 26 | 26 | import { flashTo, page } from "../layout.ts"; |
| 27 | import { btn, icon, row, time } from "../ui.ts"; | |
| 27 | import { btn, fileSize, icon, row, time } from "../ui.ts"; | |
| 28 | 28 | import { accountSections } from "./origins.ts"; |
| 29 | 29 | |
| 30 | 30 | const PATH = "/settings/economics"; |
| @@ -62,7 +62,8 @@ export function economicsPage(ctx: Ctx): Response { | ||
| 62 | 62 | const p = e.prices; |
| 63 | 63 | const perSlot = p.ownedSlots > 0 && p.ownedMonthCents > 0 ? p.ownedMonthCents / 100 / p.ownedSlots : undefined; |
| 64 | 64 | const c = e.month.cost; |
| 65 | const line = (label: string, n: number) => html`<div><dt>${label}</dt><dd class="mono">${usd(n)}</dd></div>`; | |
| 65 | const line = (label: string, n: number | string) => | |
| 66 | html`<div><dt>${label}</dt><dd class="mono">${typeof n === "number" ? usd(n) : n}</dd></div>`; | |
| 66 | 67 | const body = html`<section class="settings-block"> |
| 67 | 68 | <h2>Profit slider</h2> |
| 68 | 69 | <p class="muted small">One number for the whole forge, from 0 (cheapest) to 100 (most responsive).</p> |
| @@ -147,6 +148,10 @@ export function economicsPage(ctx: Ctx): Response { | ||
| 147 | 148 | <dl class="stats" data-cost> |
| 148 | 149 | ${line("Owned metal", c.owned)} ${line("Cloud", c.cloud)} ${line("Storage", c.storage)} |
| 149 | 150 | ${line("Crew", c.crew)} ${line("Total", c.total)} |
| 151 | ${line( | |
Principle 7: a fact is a |
||
| 152 | "Git CDN packs", | |
| 153 | `${fileSize(e.cdn.bytes)} across ${String(e.cdn.repos)} repositories, about ${usd((e.cdn.bytes / 1e9) * (p.storageGbMonthCents / 100))} a month`, | |
| 154 | )} | |
| 150 | 155 | </dl> |
| 151 | 156 | </section> |
| 152 | 157 | <section class="settings-block"> |
test/economics.test.ts +3
| @@ -78,6 +78,9 @@ describe("economics", () => { | ||
| 78 | 78 | expect(text).toContain('type="range"'); |
| 79 | 79 | expect(text).toContain('name="position"'); |
| 80 | 80 | expect(text).toContain("production sleeps after 24 h idle · previews after 30 min · cloud takes work above 85% of owned capacity"); |
| 81 | // The git CDN figure is a row of the month's cost list, not a paragraph beside it. | |
| 82 | expect(text).toMatch(/data-cost>[^]*<dt>Git CDN packs<\/dt><dd class="mono">[^<]* across \d+ repositories, about \$[\d.]+ a month<\/dd>[^]*<\/dl>/); | |
| 83 | expect(text).not.toContain("data-cdn"); | |
| 81 | 84 | }); |
| 82 | 85 | |
| 83 | 86 | test("a non-admin, signed in or not, is refused and changes nothing", async () => { |
test/git-cdn.test.ts added +307
| @@ -0,0 +1,307 @@ | ||
| 1 | /** | |
| 2 | * The git CDN (#18035): a push's packs are copied to the store, the route hands a reader | |
| 3 | * presigned links, and a repository assembled from nothing but those links reaches every ref the | |
| 4 | * route named. An expired link, a stranger and a private repository's public path are refused. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { createHmac } from "node:crypto"; | |
| 8 | import { existsSync } from "node:fs"; | |
| 9 | import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { readEconomics } from "../src/actions/economics.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { commitToBranch, deleteRepo } from "../src/actions/repos.ts"; | |
| 15 | import { CDN_TTL_S, RETRY_AFTER_MS, cdnBytes, cdnListing, cdnPrefix, cdnSummary, mendable, noteCdn } from "../src/blob/cdn.ts"; | |
| 16 | import { largeStore, offloads } from "../src/blob/large.ts"; | |
| 17 | import { createToken } from "../src/core/tokens.ts"; | |
| 18 | import type { Repo } from "../src/core/repos.ts"; | |
| 19 | import { createUser, type User } from "../src/core/users.ts"; | |
| 20 | import { runGit } from "../src/git/env.ts"; | |
| 21 | import { repoDir } from "../src/git/repos.ts"; | |
| 22 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 23 | import { cdnRows } from "../src/tui/screens/cdn.ts"; | |
| 24 | import type { Session } from "../src/tui/session.ts"; | |
| 25 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 26 | import { seededRepo } from "./helpers/seeded_repo.ts"; | |
| 27 | import { quietLogs } from "./helpers/globals.ts"; | |
| 28 | ||
| 29 | quietLogs(); | |
| 30 | ||
| 31 | describe("the git CDN", () => { | |
| 32 | let dataDir: string; | |
| 33 | let app: App; | |
| 34 | let servers: Servers; | |
| 35 | let ada: User; | |
| 36 | let bob: User; | |
| 37 | let adaToken: string; | |
| 38 | let bobToken: string; | |
| 39 | let bucket: ReturnType<typeof Bun.serve>; | |
| 40 | let skewS = 0; // how far the fake bucket's clock is ahead | |
| 41 | const asked: number[] = []; | |
| 42 | const SECRET = "bucket-secret"; | |
| 43 | ||
| 44 | const made = (name: string, visibility: "public" | "private"): Promise<Repo> => | |
| 45 | seededRepo(app, ada, name, visibility, [1, 2, 3].map((n) => ({ message: `c${n}`, files: [{ path: `f${n}.txt`, content: `${n}\n`.repeat(200) }] }))); | |
| 46 | const synced = async (repo: Repo): Promise<void> => { | |
| 47 | noteCdn(app, repo); | |
| 48 | await Promise.allSettled([...offloads(app).settled]); | |
| 49 | }; | |
| 50 | const route = (repo: Repo, token?: string) => | |
| 51 | fetch(`${servers.url}/api/v1/repos/${repo.ownerName}/${repo.name}/cdn`, { | |
| 52 | headers: token === undefined ? {} : { authorization: `Bearer ${token}` }, | |
| 53 | }); | |
| 54 | ||
| 55 | beforeAll(async () => { | |
| 56 | dataDir = await mkdtemp(join(tmpdir(), "forge-cdn-")); | |
| 57 | app = createApp({ dataDir, port: 0, host: "forge.example", url: "https://forge.example" }); | |
| 58 | servers = await serve(app); | |
| 59 | const a = await seedAdmin(app, { username: "ada", email: "[email protected]" }); | |
| 60 | if (!a.ok) throw new Error(a.error); | |
| 61 | ada = a.value; | |
| 62 | const b = await createUser(app.db, { username: "bobby", email: "[email protected]", password: "a-long-passphrase", origin: "seed" }); | |
| 63 | if (!b.ok) throw new Error(String(b.error)); | |
| 64 | bob = b.value; | |
| 65 | adaToken = createToken(app.db, ada.id, "t", "ro").token; | |
| 66 | bobToken = createToken(app.db, bob.id, "t", "ro").token; | |
| 67 | }); | |
| 68 | ||
| 69 | afterAll(async () => { | |
| 70 | await Promise.allSettled([...offloads(app).settled]); | |
| 71 | bucket?.stop(true); | |
| 72 | servers.stop(); | |
| 73 | app.close(); | |
| 74 | await rm(dataDir, { recursive: true, force: true }); | |
| 75 | }); | |
| 76 | ||
| 77 | test("a forge with no bucket says so, and mints nothing", async () => { | |
| 78 | const repo = await made("nobucket", "public"); | |
| 79 | const res = await route(repo); | |
| 80 | expect(res.status).toBe(404); | |
| 81 | expect(((await res.json()) as { error: string }).error).toBe("cdn_off"); | |
| 82 | }); | |
| 83 | ||
| 84 | test("a bucket that signs: the route lists packs, and the links alone assemble a repository", async () => { | |
| 85 | // A bucket in front of the store: a link is `?exp=<unix s>&sig=<hmac of key and exp>`, and | |
| 86 | // the server holds no forge credential and asks for none. | |
| 87 | const store = largeStore(dataDir); | |
| 88 | bucket = Bun.serve({ | |
| 89 | port: 0, | |
| 90 | async fetch(req) { | |
| 91 | const u = new URL(req.url); | |
| 92 | const key = decodeURIComponent(u.pathname.slice(1)); | |
| 93 | const exp = Number(u.searchParams.get("exp")); | |
| 94 | const sig = createHmac("sha256", SECRET).update(`${key}:${exp}`).digest("hex"); | |
| 95 | if (u.searchParams.get("sig") !== sig) return new Response("bad signature", { status: 403 }); | |
| 96 | if (Date.now() / 1000 + skewS > exp) return new Response("expired", { status: 403 }); | |
| 97 | const body = await store.get(key); | |
| 98 | return body === undefined ? new Response("no", { status: 404 }) : new Response(body); | |
| 99 | }, | |
| 100 | }); | |
| 101 | Object.assign(store, { | |
| 102 | presign: (key: string, request: { expiresInS: number }) => { | |
| 103 | asked.push(request.expiresInS); | |
| 104 | const exp = Math.floor(Date.now() / 1000) + request.expiresInS; | |
| 105 | const sig = createHmac("sha256", SECRET).update(`${key}:${exp}`).digest("hex"); | |
| 106 | return `http://127.0.0.1:${bucket.port}/${key}?exp=${exp}&sig=${sig}`; | |
| 107 | }, | |
| 108 | }); | |
| 109 | ||
| 110 | const repo = await made("pub", "public"); | |
| 111 | await synced(repo); | |
| 112 | // Loose objects are packed before listing: none is left, and every ref is reached. | |
| 113 | const count = await runGit(["count-objects"], { cwd: repoDir(app.reposRoot, "ada", "pub") }); | |
| 114 | expect(count.ok && count.value.startsWith("0 ")).toBe(true); | |
| 115 | ||
| 116 | const res = await route(repo); | |
| 117 | expect(res.status).toBe(200); | |
| 118 | expect(res.headers.get("cache-control")).toBe("private, no-store"); | |
| 119 | const body = (await res.json()) as { | |
| 120 | refs: { name: string; oid: string }[]; | |
| 121 | unreached: string[]; | |
| 122 | packs: { name: string; size: number; pack: string; idx: string }[]; | |
| 123 | expiresAt: string; | |
| 124 | }; | |
| 125 | expect(body.refs.map((r) => r.name)).toEqual(["refs/heads/main"]); | |
| 126 | expect(body.unreached).toEqual([]); | |
| 127 | expect(body.packs.length).toBeGreaterThan(0); | |
| 128 | expect(asked.at(-1)).toBe(CDN_TTL_S); | |
| 129 | expect(CDN_TTL_S).toBe(900); | |
| 130 | const left = Date.parse(body.expiresAt) - Date.now(); | |
| 131 | expect(left).toBeGreaterThan(14 * 60_000); | |
| 132 | expect(left).toBeLessThanOrEqual(15 * 60_000); | |
| 133 | ||
| 134 | // No forge credential anywhere below this line: plain fetches of the links. | |
| 135 | const bare = join(dataDir, "assembled.git"); | |
| 136 | await mkdir(join(bare, "objects", "pack"), { recursive: true }); | |
| 137 | const init = await runGit(["init", "-q", "--bare", bare]); | |
| 138 | expect(init.ok).toBe(true); | |
| 139 | for (const p of body.packs) | |
| 140 | for (const [url, ext] of [[p.pack, "pack"], [p.idx, "idx"]] as const) { | |
| 141 | const got = await fetch(url); | |
| 142 | expect(got.status).toBe(200); | |
| 143 | await Bun.write(join(bare, "objects", "pack", `${p.name}.${ext}`), got); | |
| 144 | } | |
| 145 | for (const r of body.refs) expect((await runGit(["update-ref", r.name, r.oid], { cwd: bare })).ok).toBe(true); | |
| 146 | expect((await runGit(["fsck", "--strict", "--no-dangling"], { cwd: bare })).ok).toBe(true); | |
| 147 | for (const r of body.refs) { | |
| 148 | const walk = await runGit(["rev-list", "--objects", r.oid], { cwd: bare }); | |
| 149 | expect(walk.ok).toBe(true); | |
| 150 | expect(walk.ok && walk.value.split("\n").length).toBeGreaterThanOrEqual(9); // 3 commits, 3 trees, 3 blobs | |
| 151 | } | |
| 152 | ||
| 153 | // The same links after their time are refused. | |
| 154 | skewS = 16 * 60; | |
| 155 | expect((await fetch(body.packs[0]!.pack)).status).toBe(403); | |
| 156 | expect((await fetch(body.packs[0]!.idx)).status).toBe(403); | |
| 157 | skewS = 0; | |
| 158 | // A forged one is too. | |
| 159 | expect((await fetch(body.packs[0]!.pack.replace(/sig=.{4}/, "sig=0000"))).status).toBe(403); | |
| 160 | }); | |
| 161 | ||
| 162 | test("a new push is unreached until the job has stored it, then reached", async () => { | |
| 163 | const repo = await made("later", "public"); | |
| 164 | await synced(repo); | |
| 165 | const dir = repoDir(app.reposRoot, "ada", "later"); | |
| 166 | await commitToBranch(app, ada, repo, { message: "c4", files: [{ path: "f4.txt", content: "4\n" }] }); | |
| 167 | await Promise.allSettled([...offloads(app).settled]); // the push's own sync, ended | |
| 168 | await rm(join(dir, "forge-cdn.json"), { force: true }); // as a repository never synced | |
| 169 | const before = await cdnListing(app, repo, largeStore(dataDir)); | |
| 170 | expect(before?.unreached).toEqual(["refs/heads/main"]); | |
| 171 | expect(before?.packs).toEqual([]); | |
| 172 | await synced(repo); | |
| 173 | const after = await cdnListing(app, repo, largeStore(dataDir)); | |
| 174 | expect(after?.unreached).toEqual([]); | |
| 175 | expect(after?.packs.length).toBeGreaterThan(0); | |
| 176 | // A request that finds refs unreached starts the job that mends it. | |
| 177 | await rm(join(dir, "forge-cdn.json"), { force: true }); | |
| 178 | expect((await route(repo)).status).toBe(200); | |
| 179 | await Promise.allSettled([...offloads(app).settled]); | |
| 180 | expect((await cdnListing(app, repo, largeStore(dataDir)))?.unreached).toEqual([]); | |
| 181 | }); | |
| 182 | ||
| 183 | test("a pack is stored once: a second sync uploads nothing", async () => { | |
| 184 | const repo = await made("once", "public"); | |
| 185 | await synced(repo); | |
| 186 | const store = largeStore(dataDir); | |
| 187 | const keys = await store.list(cdnPrefix(repo.id)); | |
| 188 | expect(keys.length).toBeGreaterThanOrEqual(2); | |
| 189 | let puts = 0; | |
| 190 | const put = store.put.bind(store); | |
| 191 | store.put = (...a: Parameters<typeof put>) => (puts++, put(...a)); | |
| 192 | await synced(repo); | |
| 193 | store.put = put; | |
| 194 | expect(puts).toBe(0); | |
| 195 | }); | |
| 196 | ||
| 197 | test("a private repository: a stranger, a caller who cannot read it and no token get 404; its reader gets links", async () => { | |
| 198 | const repo = await made("vault", "private"); | |
| 199 | await synced(repo); | |
| 200 | expect((await route(repo)).status).toBe(404); | |
| 201 | expect((await route(repo, bobToken)).status).toBe(404); | |
| 202 | expect((await route(repo, "forge_nope")).status).toBe(404); // a token the forge does not know is no one | |
| 203 | const ok = await route(repo, adaToken); | |
| 204 | expect(ok.status).toBe(200); | |
| 205 | const body = (await ok.json()) as { packs: { pack: string }[] }; | |
| 206 | expect(body.packs.length).toBeGreaterThan(0); | |
| 207 | // The bucket holds the key at no public path: a bare key with no signature is refused. | |
| 208 | const bare = body.packs[0]!.pack.split("?")[0]!; | |
| 209 | expect((await fetch(bare)).status).toBe(403); | |
| 210 | // Links differ per request. | |
| 211 | const again = (await (await route(repo, adaToken)).json()) as { packs: { pack: string }[] }; | |
| 212 | expect(again.packs.length).toBe(body.packs.length); | |
| 213 | }); | |
| 214 | ||
| 215 | test("the terminal shows what the store holds, to a reader only", async () => { | |
| 216 | const repo = await made("rows", "public"); | |
| 217 | await synced(repo); | |
| 218 | const reader = { app, db: app.db, user: ada } as unknown as Session; | |
| 219 | const rows = await cdnRows(reader, repo); | |
| 220 | expect(rows[0]!.title).toMatch(/^\d+ packs · /); | |
| 221 | expect(rows[0]!.meta).toBe("every ref is in the packs"); | |
| 222 | expect(rows.length).toBeGreaterThan(1); | |
| 223 | const priv = await made("rowsprivate", "private"); | |
| 224 | await synced(priv); | |
| 225 | const stranger = { app, db: app.db, user: undefined } as unknown as Session; | |
| 226 | expect(await cdnRows(stranger, priv)).toEqual([]); | |
| 227 | }); | |
| 228 | ||
| 229 | test("a fork borrows objects through alternates: it offers no pack and names every ref unreached", async () => { | |
| 230 | const repo = await made("borrower", "public"); | |
| 231 | await synced(repo); | |
| 232 | await writeFile(join(repoDir(app.reposRoot, "ada", "borrower"), "objects", "info", "alternates"), "/nowhere/objects\n"); | |
| 233 | const listing = await cdnListing(app, repo, largeStore(dataDir)); | |
| 234 | expect(listing?.packs).toEqual([]); | |
| 235 | expect(listing?.unreached).toEqual(["refs/heads/main"]); | |
| 236 | }); | |
| 237 | ||
| 238 | test("a fork's route answers 200 and starts no sync, however often it is asked", async () => { | |
| 239 | const repo = await made("forked", "public"); | |
| 240 | await synced(repo); | |
| 241 | const dir = repoDir(app.reposRoot, "ada", "forked"); | |
| 242 | await writeFile(join(dir, "objects", "info", "alternates"), "/nowhere/objects\n"); | |
| 243 | await rm(join(dir, "forge-cdn.json"), { force: true }); | |
| 244 | for (let i = 0; i < 3; i++) { | |
| 245 | const res = await route(repo, adaToken); | |
| 246 | expect(res.status).toBe(200); | |
| 247 | const body = (await res.json()) as { packs: unknown[]; unreached: string[] }; | |
| 248 | expect(body.packs).toEqual([]); | |
| 249 | expect(body.unreached).toEqual(["refs/heads/main"]); | |
| 250 | expect(offloads(app).running.size).toBe(0); | |
| 251 | } | |
| 252 | expect(existsSync(join(dir, "forge-cdn.json"))).toBe(false); // a sync writes the pointer first | |
| 253 | expect(noteCdn(app, repo)).toBe(false); // nor does a push start one | |
| 254 | }); | |
| 255 | ||
| 256 | test("a sync that was tried is not restarted by a request until the interval, but a push starts one", async () => { | |
| 257 | const repo = await made("tried", "public"); | |
| 258 | const dir = repoDir(app.reposRoot, "ada", "tried"); | |
| 259 | await rm(join(dir, "forge-cdn.json"), { force: true }); | |
| 260 | expect(await mendable(app, repo)).toBe(true); | |
| 261 | const at = Date.now(); | |
| 262 | await writeFile(join(dir, "forge-cdn.json"), JSON.stringify({ held: {}, reached: {}, tried: at })); | |
| 263 | expect(await mendable(app, repo, at + RETRY_AFTER_MS - 1)).toBe(false); | |
| 264 | expect(await mendable(app, repo, at + RETRY_AFTER_MS)).toBe(true); | |
| 265 | // The route leaves the pointer as it found it: nothing was started. | |
| 266 | expect((await route(repo, adaToken)).status).toBe(200); | |
| 267 | expect(offloads(app).running.size).toBe(0); | |
| 268 | expect(JSON.parse(await readFile(join(dir, "forge-cdn.json"), "utf8")).tried).toBe(at); | |
| 269 | // A push is not held back, and the finished sync records its attempt. | |
| 270 | await synced(repo); | |
| 271 | expect((await cdnListing(app, repo, largeStore(dataDir)))?.unreached).toEqual([]); | |
| 272 | expect(JSON.parse(await readFile(join(dir, "forge-cdn.json"), "utf8")).tried).toBeGreaterThanOrEqual(at); | |
| 273 | }); | |
| 274 | ||
| 275 | test("the economics read counts the bytes the store holds", async () => { | |
| 276 | const repo = await made("counted", "public"); | |
| 277 | await synced(repo); | |
| 278 | const mine = await cdnSummary(app, repo); | |
| 279 | const e = readEconomics(app, ada); | |
| 280 | if (!e.ok) throw new Error("not an admin"); | |
| 281 | expect(e.value.cdn.bytes).toBeGreaterThanOrEqual(mine.bytes); | |
| 282 | expect(e.value.cdn.repos).toBeGreaterThan(0); | |
| 283 | expect(cdnBytes(app, [repo]).bytes).toBe(mine.bytes); | |
| 284 | }); | |
| 285 | ||
| 286 | test("a stranger is counted by the socket's address, never a header, and told to wait", async () => { | |
| 287 | const repo = await made("busy", "public"); | |
| 288 | let refused: Response | undefined; | |
| 289 | for (let i = 0; i < 40 && refused === undefined; i++) { | |
| 290 | // a different claimed address each time buys nothing | |
| 291 | const res = await fetch(`${servers.url}/api/v1/repos/ada/busy/cdn`, { headers: { "x-forwarded-for": `10.0.0.${i}` } }); | |
| 292 | if (res.status === 429) refused = res; | |
| 293 | } | |
| 294 | expect(refused?.status).toBe(429); | |
| 295 | expect(Number(refused?.headers.get("retry-after"))).toBeGreaterThanOrEqual(1); | |
| 296 | expect((await route(repo, adaToken)).status).toBe(200); // a token is not a stranger | |
| 297 | }); | |
| 298 | ||
| 299 | test("deleting the repository takes its packs out of the store", async () => { | |
| 300 | const repo = await made("gone", "public"); | |
| 301 | await synced(repo); | |
| 302 | const store = largeStore(dataDir); | |
| 303 | expect((await store.list(cdnPrefix(repo.id))).length).toBeGreaterThan(0); | |
| 304 | expect((await deleteRepo(app, ada, repo)).ok).toBe(true); | |
| 305 | expect(await store.list(cdnPrefix(repo.id))).toEqual([]); | |
| 306 | }); | |
| 307 | }); |
test/helpers/seeded_repo.ts added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | import { commitToBranch, createRepo } from "../../src/actions/repos.ts"; | |
| 2 | import type { App } from "../../src/app.ts"; | |
| 3 | import { offloads } from "../../src/blob/large.ts"; | |
| 4 | import type { Repo } from "../../src/core/repos.ts"; | |
| 5 | import type { User } from "../../src/core/users.ts"; | |
| 6 | ||
| 7 | /** | |
| 8 | * A repository `owner` made with one commit per entry of `commits`, its push events' background | |
| 9 | * jobs (the large-blob offload, the CDN sync) finished so a test's own call is the only one. | |
| 10 | */ | |
| 11 | export async function seededRepo( | |
| 12 | app: App, | |
| 13 | owner: User, | |
| 14 | name: string, | |
| 15 | visibility: "public" | "private", | |
| 16 | commits: { message: string; files: { path: string; content: string }[] }[], | |
| 17 | ): Promise<Repo> { | |
| 18 | const r = await createRepo(app, owner, { name, visibility }); | |
| 19 | if (!r.ok) throw new Error(String(r.error)); | |
| 20 | for (const c of commits) await commitToBranch(app, owner, r.value, c); | |
| 21 | await Promise.allSettled([...offloads(app).settled]); | |
| 22 | return r.value; | |
| 23 | } |
test/large-blobs.test.ts +4 −12
| @@ -8,7 +8,7 @@ import { mkdtemp, rm } from "node:fs/promises"; | ||
| 8 | 8 | import { tmpdir } from "node:os"; |
| 9 | 9 | import { join } from "node:path"; |
| 10 | 10 | import { createApp, type App } from "../src/app.ts"; |
| 11 | import { commitToBranch, createRepo, deleteRepo } from "../src/actions/repos.ts"; | |
| 11 | import { deleteRepo } from "../src/actions/repos.ts"; | |
| 12 | 12 | import { dirStore } from "../src/blob/store.ts"; |
| 13 | 13 | import { largeRows } from "../src/tui/screens/largefiles.ts"; |
| 14 | 14 | import type { Session } from "../src/tui/session.ts"; |
| @@ -22,6 +22,7 @@ import { runGit } from "../src/git/env.ts"; | ||
| 22 | 22 | import { serve, type Servers } from "../src/http/server.ts"; |
| 23 | 23 | import { largeStore } from "../src/blob/large.ts"; |
| 24 | 24 | import { seedAdmin } from "./helpers/admin.ts"; |
| 25 | import { seededRepo } from "./helpers/seeded_repo.ts"; | |
| 25 | 26 | import { quietLogs } from "./helpers/globals.ts"; |
| 26 | 27 | |
| 27 | 28 | quietLogs(); |
| @@ -45,17 +46,8 @@ describe("a big blob through the real router", () => { | ||
| 45 | 46 | let oid: string; |
| 46 | 47 | const was = process.env["FORGE_LARGE_BLOB_BYTES"]; |
| 47 | 48 | |
| 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 | }; | |
| 49 | const made = (name: string, visibility: "public" | "private"): Promise<Repo> => | |
| 50 | seededRepo(app, ada, name, visibility, [{ message: "seed", files: [{ path: "small.txt", content: "a\n" }, { path: "data/big.bin", content: BIG }] }]); | |
| 59 | 51 | const push = (repo: Repo): ForgeEvent => ({ |
| 60 | 52 | id: "e", |
| 61 | 53 | kind: "push", |
new above
offline
An anonymous request can start a sync here, and a failed repack leaves the repository unreached forever, so each request retries a 300s repack. Record the failure and back off. Never start a sync for a repository that borrows via alternates.