Diffinery

homeflare/diffinerypublic

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

277 lines · 15.2 KBRaw History
1import type { Env } from "../env.js";
2import type { Account } from "../lib/directory.js";
3import { Directory } from "../lib/directory.js";
4import { tarEnd, tarFileHeader, tarPadding } from "../lib/archive.js";
5import { R2Sink } from "../lib/r2-sink.js";
6import { deletePrefixes } from "../lib/storage-keys.js";
7import { HttpError, newId, now } from "../lib/util.js";
8import { MailStore } from "../mail/prefs.js";
9import { enqueueMail } from "../mail/send.js";
10
11/**
12 * Exports of an account's data (Settings → Account → Export your data), like GitHub's account archive.
13 *
14 * The person asks; AccountWorkflow builds the archive in the background, one piece per step, under
15 * exports/<account id>/<export id>/parts/, then puts the pieces together into one uncompressed tar archive
16 * (the Git bundles inside are already compressed) and emails the person a link. They download it from
17 * Settings → Account for {@link EXPORT_DAYS} days; then the cron deletes it (and an R2 age rule on exports/ is
18 * the backstop). One export at a time per account.
19 *
20 * Inside the archive, under `diffinery-export-<login>/`:
21 *
22 * | Path | What |
23 * |------|------|
24 * | `manifest.json` | format version, account, when it was made, and every file with its size |
25 * | `account.json` | profile, settings (appearance, notification settings, watched repositories), organizations, agents, access tokens and passkeys (names and dates only, never secrets), linked accounts |
26 * | `repositories/<name>.json` | each repository the account owns: description, visibility, default branch, topics, clone URL |
27 * | `repositories/<name>.bundle` | its branches and tags as a Git bundle: `git clone <name>.bundle` |
28 * | `issues/<owner>/<repo>.json` | issues and pull requests the account opened, comments and reviews it wrote, per repository it can see |
29 *
30 * A repository too large to bundle ({@link MAX_BUNDLE_BYTES}) has no bundle; its JSON says so and gives the clone URL.
31 */
32
33export const EXPORT_DAYS = 7;
34/** Archive format version, in manifest.json. */
35export const EXPORT_FORMAT = 1;
36/** Largest repository bundle in an export; tar's plain header holds sizes up to 8 GiB. */
37export const MAX_BUNDLE_BYTES = 4 * 1024 ** 3;
38/** Largest whole archive (R2 multipart: 10,000 parts of 8 MiB). */
39const MAX_ARCHIVE_BYTES = 75 * 1024 ** 3;
40/** How many repositories one step looks through for what the account wrote. */
41export const AUTHORED_PAGE = 20;
42
43export interface ExportRow {
44 id: string;
45 account_id: string;
46 status: "queued" | "running" | "ready" | "failed";
47 r2_key: string | null;
48 size: number | null;
49 error: string | null;
50 created_at: string;
51 finished_at: string | null;
52 expires_at: string | null;
53}
54
55export interface ExportJob {
56 kind: "export";
57 exportId: string;
58}
59
60const prefix = (row: Pick<ExportRow, "account_id" | "id">) => `exports/${row.account_id}/${row.id}/`;
61const partsPrefix = (row: Pick<ExportRow, "account_id" | "id">) => `${prefix(row)}parts/`;
62const json = (v: unknown) => new TextEncoder().encode(`${JSON.stringify(v, null, 2)}\n`);
63
64async function row(env: Env, id: string): Promise<ExportRow> {
65 const r = await env.DB.prepare("SELECT * FROM account_exports WHERE id = ?").bind(id).first<ExportRow>();
66 if (!r) throw new HttpError(404, "no such export");
67 return r;
68}
69
70async function owner(env: Env, r: ExportRow): Promise<Account> {
71 const a = await new Directory(env).account(r.account_id);
72 if (!a || a.deleted_at) throw new HttpError(404, "the account was deleted");
73 return a;
74}
75
76/** The account's exports, newest first (Settings → Account). Expired ones are left out. */
77export async function exportsFor(env: Env, accountId: string): Promise<ExportRow[]> {
78 const r = await env.DB.prepare("SELECT * FROM account_exports WHERE account_id = ? AND (expires_at IS NULL OR expires_at > ?) ORDER BY created_at DESC LIMIT 5").bind(accountId, now()).all<ExportRow>();
79 return r.results;
80}
81
82/** Ask for an export. Refused while another one is being built. Earlier archives are replaced. */
83export async function requestExport(env: Env, account: Account): Promise<ExportRow> {
84 const busy = await env.DB.prepare("SELECT 1 FROM account_exports WHERE account_id = ? AND status IN ('queued', 'running') AND created_at > ?").bind(account.id, new Date(Date.now() - 86400_000).toISOString()).first();
85 if (busy) throw new HttpError(409, "An export is already being prepared. We'll email you when it's ready.");
86 const old = await env.DB.prepare("SELECT * FROM account_exports WHERE account_id = ?").bind(account.id).all<ExportRow>();
87 await deletePrefixes(env.BUCKET, old.results.map(prefix));
88 const id = newId();
89 await env.DB.batch([
90 env.DB.prepare("DELETE FROM account_exports WHERE account_id = ?").bind(account.id),
91 env.DB.prepare("INSERT INTO account_exports (id, account_id, status, created_at) VALUES (?, ?, 'queued', ?)").bind(id, account.id, now()),
92 ]);
93 const job: ExportJob = { kind: "export", exportId: id };
94 if (env.ACCOUNT_WORKFLOW) await env.ACCOUNT_WORKFLOW.create({ id: `export-${id}`, params: job });
95 else await buildExport(env, id);
96 return row(env, id);
97}
98
99/** The whole export in one go: what AccountWorkflow does step by step (used when there is no workflow binding). */
100async function buildExport(env: Env, id: string): Promise<void> {
101 try {
102 const plan = await startExport(env, id);
103 await exportAccount(env, id);
104 for (const r of plan.owned) await exportRepository(env, id, r);
105 for (let i = 0; i < plan.visible.length; i += AUTHORED_PAGE) await exportAuthored(env, id, plan.visible.slice(i, i + AUTHORED_PAGE));
106 await assembleExport(env, id);
107 } catch (e) {
108 await failExport(env, id, e instanceof Error ? e.message : String(e));
109 }
110}
111
112/** Public repositories of other people an export looks through for what the account wrote. */
113const EXPORT_PUBLIC_REPOS = 1000;
114
115/** First step: mark the export running and list the repositories it covers. */
116export async function startExport(env: Env, id: string): Promise<{ owned: string[]; visible: string[] }> {
117 const r = await row(env, id);
118 const account = await owner(env, r);
119 await env.DB.prepare("UPDATE account_exports SET status = 'running' WHERE id = ?").bind(id).run();
120 const dir = new Directory(env);
121 const owned = (await env.DB.prepare("SELECT id FROM repos WHERE owner_id = ? ORDER BY name").bind(account.id).all<{ id: string }>()).results.map((x) => x.id);
122 // Issues and pull requests the account wrote: in the repositories it works with, and in public
123 // ones (reposVisibleTo leaves those out), the most recently pushed first.
124 const [visible, open] = await Promise.all([dir.reposVisibleTo(account), dir.publicRepos(EXPORT_PUBLIC_REPOS)]);
125 return { owned, visible: [...new Set([...owned, ...visible.map((x) => x.id), ...open.map((x) => x.id)])] };
126}
127
128/** account.json: the profile and settings. Tokens and passkeys by name only: nothing in the archive signs anyone in. */
129export async function exportAccount(env: Env, id: string): Promise<void> {
130 const r = await row(env, id);
131 const a = await owner(env, r);
132 const db = env.DB;
133 const all = async <T>(q: string) => (await db.prepare(q).bind(a.id).all<T>()).results;
134 const data = {
135 login: a.login,
136 name: a.name,
137 email: a.email,
138 created_at: a.created_at,
139 site_admin: !!a.site_admin,
140 avatar_url: `${env.PUBLIC_URL}/api/avatars/${encodeURIComponent(a.login)}`,
141 settings: {
142 appearance: a.appearance ?? "auto",
143 notifications: await new MailStore(db).prefs(a.id),
144 watching: await all("SELECT a.login || '/' || r.name AS repository, w.level FROM repo_watches w JOIN repos r ON r.id = w.repo_id JOIN accounts a ON a.id = r.owner_id WHERE w.account_id = ? ORDER BY 1"),
145 },
146 organizations: await all("SELECT o.login, m.role, m.created_at AS joined_at FROM org_members m JOIN accounts o ON o.id = m.org_id WHERE m.user_id = ? ORDER BY o.login"),
147 agents: await all("SELECT login, name, status, created_at FROM accounts WHERE kind = 'agent' AND owner_id = ? AND deleted_at IS NULL ORDER BY login"),
148 tokens: (await all<{ name: string; prefix: string; scopes: string; expires_at: string; last_used_at: string | null; created_at: string }>("SELECT name, prefix, scopes, expires_at, last_used_at, created_at FROM tokens WHERE account_id = ? AND revoked_at IS NULL AND import_id IS NULL ORDER BY created_at")).map((t) => ({ ...t, scopes: JSON.parse(t.scopes) as string[] })),
149 passkeys: await all("SELECT name, created_at, last_used_at, backed_up AS synced FROM passkeys WHERE account_id = ? ORDER BY created_at"),
150 linked_accounts: await all("SELECT provider, api_base, external_login AS login, created_at FROM account_links WHERE account_id = ? ORDER BY created_at"),
151 model_keys: await all("SELECT provider, hint, created_at FROM model_keys WHERE account_id = ? ORDER BY provider"),
152 };
153 await env.BUCKET.put(`${partsPrefix(r)}account.json`, json(data));
154}
155
156/** repositories/<name>.json, and its Git bundle when the repository has commits and isn't too large. */
157export async function exportRepository(env: Env, id: string, repoId: string): Promise<void> {
158 const r = await row(env, id);
159 const repo = await new Directory(env).repoById(repoId);
160 if (!repo) return;
161 const at = `${partsPrefix(r)}repositories/${repo.name}`;
162 let bundle: string | null = null;
163 let note: string | undefined;
164 try {
165 const b = await env.REPO.get(env.REPO.idFromName(repo.id)).writeBundle(`${at}.bundle`, MAX_BUNDLE_BYTES);
166 if (b) bundle = `${repo.name}.bundle`;
167 else note = "The repository has no branches or tags yet.";
168 } catch (e) {
169 if (!(e instanceof Error) || !/too large/.test(e.message)) throw e;
170 note = `The repository is larger than ${MAX_BUNDLE_BYTES / 1024 ** 3} GiB, too large to bundle: clone it from clone_url.`;
171 }
172 const meta = {
173 name: repo.name,
174 full_name: `${repo.owner_login}/${repo.name}`,
175 description: repo.description,
176 visibility: repo.visibility,
177 default_branch: repo.default_branch,
178 archived: !!repo.archived,
179 topics: JSON.parse(repo.topics ?? "[]") as string[],
180 homepage: repo.homepage ?? "",
181 created_at: repo.created_at,
182 pushed_at: repo.pushed_at,
183 clone_url: `${env.PUBLIC_URL}/${repo.owner_login}/${repo.name}.git`,
184 bundle,
185 ...(note ? { note } : {}),
186 };
187 await env.BUCKET.put(`${at}.json`, json(meta));
188}
189
190/** issues/<owner>/<repo>.json for each of these repositories where the account wrote something. */
191export async function exportAuthored(env: Env, id: string, repoIds: string[]): Promise<void> {
192 const r = await row(env, id);
193 const dir = new Directory(env);
194 await Promise.all(
195 repoIds.map(async (repoId) => {
196 const repo = await dir.repoById(repoId);
197 if (!repo) return;
198 const mine = await env.REPO.get(env.REPO.idFromName(repo.id)).authoredBy([r.account_id]);
199 if (!mine.issues.length && !mine.comments.length && !mine.reviews.length) return;
200 await env.BUCKET.put(`${partsPrefix(r)}issues/${repo.owner_login}/${repo.name}.json`, json({ repository: `${repo.owner_login}/${repo.name}`, ...mine }));
201 }),
202 );
203}
204
205/** Last step: the pieces become one tar archive, the pieces go, and the person hears that it's ready. */
206export async function assembleExport(env: Env, id: string): Promise<void> {
207 const r = await row(env, id);
208 const a = await owner(env, r);
209 const parts: Array<{ key: string; path: string; size: number }> = [];
210 let cursor: string | undefined;
211 do {
212 const page = await env.BUCKET.list({ prefix: partsPrefix(r), cursor });
213 for (const o of page.objects) parts.push({ key: o.key, path: o.key.slice(partsPrefix(r).length), size: o.size });
214 cursor = page.truncated ? page.cursor : undefined;
215 } while (cursor);
216 parts.sort((x, y) => (x.path === "account.json" ? -1 : y.path === "account.json" ? 1 : x.path.localeCompare(y.path)));
217 const day = now().slice(0, 10);
218 const top = `diffinery-export-${a.login}`;
219 const key = `${prefix(r)}${top}-${day}.tar`;
220 const mtime = Math.floor(Date.now() / 1000);
221 const manifest = json({ format: EXPORT_FORMAT, instance: env.PUBLIC_URL, account: a.login, created_at: now(), files: parts.map((p) => ({ path: p.path, size: p.size })) });
222 const sink = new R2Sink(env.BUCKET, key, "application/x-tar", MAX_ARCHIVE_BYTES, "the export is too large");
223 try {
224 for (const b of tarFileHeader(`${top}/manifest.json`, manifest.length, mtime)) await sink.write(b);
225 await sink.write(manifest);
226 await sink.write(tarPadding(manifest.length));
227 for (const p of parts) {
228 const obj = await env.BUCKET.get(p.key);
229 if (!obj) throw new Error(`a piece of the export is missing: ${p.path}`);
230 for (const b of tarFileHeader(`${top}/${p.path}`, obj.size, mtime)) await sink.write(b);
231 const reader = obj.body.getReader();
232 for (;;) {
233 const { done, value } = await reader.read();
234 if (done) break;
235 await sink.write(value);
236 }
237 await sink.write(tarPadding(obj.size));
238 }
239 await sink.write(tarEnd());
240 } catch (e) {
241 await sink.abort();
242 throw e;
243 }
244 const size = await sink.close();
245 await deletePrefixes(env.BUCKET, [partsPrefix(r)]);
246 const expires = new Date(Date.now() + EXPORT_DAYS * 86400_000).toISOString();
247 await env.DB.prepare("UPDATE account_exports SET status = 'ready', r2_key = ?, size = ?, finished_at = ?, expires_at = ? WHERE id = ?").bind(key, size, now(), expires, id).run();
248 await enqueueMail(env, [{ kind: "export_ready", data: { url: `${env.PUBLIC_URL}/settings/account`, size, expiresAt: expires }, to: { accountId: a.id }, reason: "account", at: now() }]);
249}
250
251/** The export failed for good: say why on Settings → Account, and drop its pieces. */
252export async function failExport(env: Env, id: string, message: string): Promise<void> {
253 const r = await env.DB.prepare("SELECT * FROM account_exports WHERE id = ?").bind(id).first<ExportRow>();
254 if (!r) return;
255 await deletePrefixes(env.BUCKET, [prefix(r)]).catch(() => false);
256 await env.DB.prepare("UPDATE account_exports SET status = 'failed', error = ?, finished_at = ? WHERE id = ?").bind(message.slice(0, 500), now(), id).run();
257}
258
259/** The archive of a ready, unexpired export of this account, for downloading. */
260export async function exportArchive(env: Env, accountId: string, id: string): Promise<{ body: ReadableStream; size: number; name: string }> {
261 const r = await env.DB.prepare("SELECT * FROM account_exports WHERE id = ? AND account_id = ?").bind(id, accountId).first<ExportRow>();
262 if (!r || r.status !== "ready" || !r.r2_key) throw new HttpError(404, "no such export");
263 if (!r.expires_at || r.expires_at < now()) throw new HttpError(410, "this export has expired; ask for a new one");
264 const obj = await env.BUCKET.get(r.r2_key);
265 if (!obj) throw new HttpError(410, "this export has expired; ask for a new one");
266 return { body: obj.body, size: obj.size, name: r.r2_key.split("/").at(-1)! };
267}
268
269/** Cron: delete exports past their 7 days, and ones stuck building for more than a day. */
270export async function expireExports(env: Env): Promise<void> {
271 const old = await env.DB.prepare("SELECT * FROM account_exports WHERE expires_at < ? OR (status IN ('queued', 'running', 'failed') AND created_at < ?) LIMIT 50")
272 .bind(now(), new Date(Date.now() - 86400_000).toISOString())
273 .all<ExportRow>();
274 for (const r of old.results) {
275 if (await deletePrefixes(env.BUCKET, [prefix(r)], 50)) await env.DB.prepare("DELETE FROM account_exports WHERE id = ?").bind(r.id).run();
276 }
277}