Branchwell / source / src / repo.ts
| 1 | // One Durable Object per repository. It holds every Git object, the branches, the commit records |
| 2 | // and the votes in its own SQLite database, so a push, a vote and a removal never race each other. |
| 3 | import { DurableObject } from 'cloudflare:workers'; |
| 4 | import { |
| 5 | ZERO, FLUSH, te, td, pkt, concat, readPkts, sideband, objectId, parseTree, writeTree, parseCommit, personName, |
| 6 | readPack, packHeader, packObjHeader, deflate, inflate, TYPE_NUM, NUM_TYPE, type ObjType, type RawObj, type TreeEntry, |
| 7 | } from './git/core'; |
| 8 | import { Sha1 } from './git/sha1'; |
| 9 | import { checkBlob } from './checks'; |
| 10 | |
| 11 | const PART = 1_000_000; // bytes per stored row (SQLite rows cap at 2 MB) |
| 12 | export const VOTES_TO_DECIDE = 3; |
| 13 | const BRANCH_RE = /^(?!\/|.*\/\/|.*\.\.|.*\.lock$|.*[\s~^:?*[\\\x00-\x1f\x7f]|.*@\{|\.|.*\/\.)[A-Za-z0-9._\/-]{1,100}(?<!\/|\.)$/; |
| 14 | |
| 15 | export interface Voter { id: string; handle: string; canVote: boolean } |
| 16 | export interface Pusher { id: string; handle: string } |
| 17 | |
| 18 | export class RepoDO extends DurableObject { |
| 19 | sql: SqlStorage; |
| 20 | constructor(ctx: DurableObjectState, env: unknown) { |
| 21 | super(ctx, env as never); |
| 22 | this.sql = ctx.storage.sql; |
| 23 | this.sql.exec(` |
| 24 | CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT); |
| 25 | CREATE TABLE IF NOT EXISTS objects (sha TEXT PRIMARY KEY, type INTEGER NOT NULL, size INTEGER NOT NULL, parts INTEGER NOT NULL, z BLOB); |
| 26 | CREATE TABLE IF NOT EXISTS object_parts (sha TEXT NOT NULL, idx INTEGER NOT NULL, z BLOB NOT NULL, PRIMARY KEY (sha, idx)); |
| 27 | CREATE TABLE IF NOT EXISTS refs (name TEXT PRIMARY KEY, sha TEXT NOT NULL); |
| 28 | CREATE TABLE IF NOT EXISTS branches (name TEXT PRIMARY KEY, status TEXT NOT NULL, up INTEGER NOT NULL DEFAULT 0, down INTEGER NOT NULL DEFAULT 0, |
| 29 | created_by TEXT, created_at INTEGER NOT NULL, removed_at INTEGER, last_sha TEXT); |
| 30 | CREATE TABLE IF NOT EXISTS commits (sha TEXT PRIMARY KEY, branch TEXT NOT NULL, status TEXT NOT NULL, up INTEGER NOT NULL DEFAULT 0, down INTEGER NOT NULL DEFAULT 0, |
| 31 | pusher TEXT, pushed_at INTEGER NOT NULL, subject TEXT, author TEXT, note TEXT); |
| 32 | CREATE INDEX IF NOT EXISTS commits_branch ON commits (branch, pushed_at); |
| 33 | CREATE TABLE IF NOT EXISTS votes (kind TEXT NOT NULL, target TEXT NOT NULL, account TEXT NOT NULL, handle TEXT, value INTEGER NOT NULL, at INTEGER NOT NULL, |
| 34 | PRIMARY KEY (kind, target, account)); |
| 35 | `); |
| 36 | } |
| 37 | |
| 38 | // ---------------- storage ---------------- |
| 39 | meta(k: string): string | null { const r = this.sql.exec('SELECT v FROM meta WHERE k = ?', k).toArray()[0]; return r ? (r.v as string) : null; } |
| 40 | setMeta(k: string, v: string) { this.sql.exec('INSERT INTO meta (k, v) VALUES (?, ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v', k, v); } |
| 41 | defaultBranch() { return this.meta('default_branch') || 'main'; } |
| 42 | |
| 43 | has(sha: string) { return this.sql.exec('SELECT 1 FROM objects WHERE sha = ?', sha).toArray().length > 0; } |
| 44 | zOf(sha: string): { type: number; size: number; z: Uint8Array } | null { |
| 45 | const r = this.sql.exec('SELECT type, size, parts, z FROM objects WHERE sha = ?', sha).toArray()[0]; |
| 46 | if (!r) return null; |
| 47 | let z: Uint8Array; |
| 48 | if ((r.parts as number) === 0) z = new Uint8Array(r.z as ArrayBuffer); |
| 49 | else z = concat(this.sql.exec('SELECT z FROM object_parts WHERE sha = ? ORDER BY idx', sha).toArray().map((p) => new Uint8Array(p.z as ArrayBuffer))); |
| 50 | return { type: r.type as number, size: r.size as number, z }; |
| 51 | } |
| 52 | get(sha: string, overlay?: Map<string, RawObj>): RawObj | null { |
| 53 | const o = overlay?.get(sha); if (o) return o; |
| 54 | const z = this.zOf(sha); if (!z) return null; |
| 55 | return { type: NUM_TYPE[z.type], data: inflate(z.z), sha }; |
| 56 | } |
| 57 | put(o: RawObj) { |
| 58 | if (this.has(o.sha)) return; |
| 59 | const z = deflate(o.data); |
| 60 | if (z.length <= PART) { this.sql.exec('INSERT INTO objects (sha, type, size, parts, z) VALUES (?, ?, ?, 0, ?)', o.sha, TYPE_NUM[o.type], o.data.length, z); return; } |
| 61 | const n = Math.ceil(z.length / PART); |
| 62 | for (let i = 0; i < n; i++) this.sql.exec('INSERT INTO object_parts (sha, idx, z) VALUES (?, ?, ?)', o.sha, i, z.subarray(i * PART, (i + 1) * PART)); |
| 63 | this.sql.exec('INSERT INTO objects (sha, type, size, parts, z) VALUES (?, ?, ?, ?, NULL)', o.sha, TYPE_NUM[o.type], o.data.length, n); |
| 64 | } |
| 65 | make(type: ObjType, data: Uint8Array): string { const sha = objectId(type, data); this.put({ type, data, sha }); return sha; } |
| 66 | |
| 67 | refs(): Map<string, string> { return new Map(this.sql.exec('SELECT name, sha FROM refs ORDER BY name').toArray().map((r) => [r.name as string, r.sha as string])); } |
| 68 | setRef(branch: string, sha: string) { this.sql.exec('INSERT INTO refs (name, sha) VALUES (?, ?) ON CONFLICT (name) DO UPDATE SET sha = excluded.sha', 'refs/heads/' + branch, sha); this.sql.exec('UPDATE branches SET last_sha = ? WHERE name = ?', sha, branch); } |
| 69 | |
| 70 | commit(sha: string, overlay?: Map<string, RawObj>) { const o = this.get(sha, overlay); if (!o || o.type !== 'commit') throw new Error('missing commit ' + sha); return parseCommit(o.data); } |
| 71 | tree(sha: string, overlay?: Map<string, RawObj>): TreeEntry[] { const o = this.get(sha, overlay); if (!o || o.type !== 'tree') throw new Error('missing tree ' + sha); return parseTree(o.data); } |
| 72 | |
| 73 | /** Every commit reachable from the given tips. */ |
| 74 | reachable(tips: string[], overlay?: Map<string, RawObj>, stop?: Set<string>, limit = 100000): Set<string> { |
| 75 | const seen = new Set<string>(); const q = tips.filter((t) => t && t !== ZERO); |
| 76 | while (q.length && seen.size < limit) { |
| 77 | const s = q.pop()!; if (seen.has(s) || stop?.has(s)) continue; seen.add(s); |
| 78 | for (const p of this.commit(s, overlay).parents) if (!seen.has(p)) q.push(p); |
| 79 | } |
| 80 | return seen; |
| 81 | } |
| 82 | |
| 83 | /** path -> {mode, sha} for every file under a tree (submodules kept as entries). */ |
| 84 | flatten(treeSha: string | null, overlay?: Map<string, RawObj>, prefix = '', out = new Map<string, { mode: string; sha: string }>()) { |
| 85 | if (!treeSha) return out; |
| 86 | for (const e of this.tree(treeSha, overlay)) { |
| 87 | if (e.mode === '40000') this.flatten(e.sha, overlay, prefix + e.name + '/', out); |
| 88 | else out.set(prefix + e.name, { mode: e.mode, sha: e.sha }); |
| 89 | } |
| 90 | return out; |
| 91 | } |
| 92 | buildTree(flat: Map<string, { mode: string; sha: string }>): string { |
| 93 | type Dir = { files: TreeEntry[]; dirs: Map<string, Dir> }; |
| 94 | const root: Dir = { files: [], dirs: new Map() }; |
| 95 | for (const [path, v] of flat) { |
| 96 | const parts = path.split('/'); let d = root; |
| 97 | for (const p of parts.slice(0, -1)) { if (!d.dirs.has(p)) d.dirs.set(p, { files: [], dirs: new Map() }); d = d.dirs.get(p)!; } |
| 98 | d.files.push({ mode: v.mode, name: parts[parts.length - 1], sha: v.sha }); |
| 99 | } |
| 100 | const write = (d: Dir): string => this.make('tree', writeTree([...d.files, ...[...d.dirs].map(([name, sub]) => ({ mode: '40000', name, sha: write(sub) }))])); |
| 101 | return write(root); |
| 102 | } |
| 103 | changes(sha: string, overlay?: Map<string, RawObj>) { |
| 104 | const c = this.commit(sha, overlay); |
| 105 | const after = this.flatten(c.tree, overlay); |
| 106 | const before = c.parents[0] ? this.flatten(this.commit(c.parents[0], overlay).tree, overlay) : new Map(); |
| 107 | const out: { path: string; status: 'added' | 'changed' | 'deleted'; before?: { mode: string; sha: string }; after?: { mode: string; sha: string } }[] = []; |
| 108 | for (const [p, v] of after) { const b = before.get(p); if (!b) out.push({ path: p, status: 'added', after: v }); else if (b.sha !== v.sha || b.mode !== v.mode) out.push({ path: p, status: 'changed', before: b, after: v }); } |
| 109 | for (const [p, v] of before) if (!after.has(p)) out.push({ path: p, status: 'deleted', before: v }); |
| 110 | return { commit: c, files: out.sort((a, b) => (a.path < b.path ? -1 : 1)) }; |
| 111 | } |
| 112 | |
| 113 | // ---------------- Git smart HTTP ---------------- |
| 114 | async fetch(req: Request): Promise<Response> { |
| 115 | const url = new URL(req.url); |
| 116 | const rn = req.headers.get('x-repo'); if (rn && !this.meta('name')) this.setMeta('name', rn); |
| 117 | try { |
| 118 | if (url.pathname === '/info/refs') return this.advertise(url.searchParams.get('service') || ''); |
| 119 | if (url.pathname === '/git-upload-pack') return this.uploadPack(new Uint8Array(await req.arrayBuffer())); |
| 120 | if (url.pathname === '/git-receive-pack') { |
| 121 | const pusher = JSON.parse(req.headers.get('x-pusher') || 'null') as Pusher | null; |
| 122 | if (!pusher) return new Response('sign in to push', { status: 401 }); |
| 123 | return this.receivePack(new Uint8Array(await req.arrayBuffer()), pusher); |
| 124 | } |
| 125 | } catch (e) { |
| 126 | return new Response('error: ' + (e as Error).message, { status: 500 }); |
| 127 | } |
| 128 | return new Response('not found', { status: 404 }); |
| 129 | } |
| 130 | |
| 131 | advertise(service: string): Response { |
| 132 | if (service !== 'git-upload-pack' && service !== 'git-receive-pack') return new Response('dumb HTTP is not supported; use git 1.7 or newer', { status: 403 }); |
| 133 | const refs = this.refs(); |
| 134 | const def = this.defaultBranch(); |
| 135 | const caps = service === 'git-upload-pack' |
| 136 | ? `side-band-64k no-progress symref=HEAD:refs/heads/${def} agent=branchwell/1` |
| 137 | : 'report-status side-band-64k quiet ofs-delta agent=branchwell/1'; |
| 138 | const lines: Uint8Array[] = [pkt(`# service=${service}\n`), FLUSH]; |
| 139 | const list: [string, string][] = []; |
| 140 | const head = refs.get('refs/heads/' + def); |
| 141 | if (head && service === 'git-upload-pack') list.push(['HEAD', head]); |
| 142 | for (const [n, s] of refs) list.push([n, s]); |
| 143 | if (!list.length) lines.push(pkt(`${ZERO} capabilities^{}\0${caps}\n`)); |
| 144 | list.forEach(([n, s], i) => lines.push(pkt(i === 0 ? `${s} ${n}\0${caps}\n` : `${s} ${n}\n`))); |
| 145 | lines.push(FLUSH); |
| 146 | return new Response(concat(lines), { headers: { 'content-type': `application/x-${service}-advertisement`, 'cache-control': 'no-cache' } }); |
| 147 | } |
| 148 | |
| 149 | uploadPack(body: Uint8Array): Response { |
| 150 | const { lines } = readPkts(body); |
| 151 | const wants: string[] = []; const haves: string[] = []; let done = false; let caps = ''; |
| 152 | for (const l of lines) { |
| 153 | if (!l) continue; |
| 154 | const s = td.decode(l).replace(/\n$/, ''); |
| 155 | if (s.startsWith('want ')) { wants.push(s.slice(5, 45)); if (!caps) caps = s.slice(46); } |
| 156 | else if (s.startsWith('have ')) haves.push(s.slice(5, 45)); |
| 157 | else if (s === 'done') done = true; |
| 158 | } |
| 159 | const common = haves.filter((h) => this.has(h)); |
| 160 | const ack = pkt(common.length ? `ACK ${common[0]}\n` : 'NAK\n'); |
| 161 | const type = 'application/x-git-upload-pack-result'; |
| 162 | if (!done && !wants.length) return new Response(ack, { headers: { 'content-type': type } }); |
| 163 | if (!done) return new Response(ack, { headers: { 'content-type': type } }); |
| 164 | for (const w of wants) if (!this.has(w)) return new Response(concat([pkt(`ERR upload-pack: not our ref ${w}\n`)]), { headers: { 'content-type': type } }); |
| 165 | |
| 166 | // Objects the client already has. |
| 167 | const have = new Set<string>(); |
| 168 | const commitsHave = this.reachable(common); |
| 169 | const addTree = (t: string, set: Set<string>) => { if (set.has(t)) return; set.add(t); for (const e of this.tree(t)) { if (e.mode === '40000') addTree(e.sha, set); else if (e.mode !== '160000') set.add(e.sha); } }; |
| 170 | for (const c of commitsHave) { have.add(c); addTree(this.commit(c).tree, have); } |
| 171 | // Objects to send, in commit, tree, blob order. |
| 172 | const send: string[] = []; const seen = new Set<string>(); |
| 173 | const q = [...wants]; |
| 174 | while (q.length) { |
| 175 | const s = q.pop()!; if (seen.has(s) || have.has(s)) continue; seen.add(s); |
| 176 | const z = this.sql.exec('SELECT type FROM objects WHERE sha = ?', s).toArray()[0]; |
| 177 | if (!z) continue; |
| 178 | send.push(s); |
| 179 | if (z.type === 1) { const c = this.commit(s); q.push(...c.parents); this.collectTree(c.tree, have, seen, send); } |
| 180 | else if (z.type === 4) { const t = td.decode(this.get(s)!.data).match(/^object ([0-9a-f]{40})/m); if (t) q.push(t[1]); } |
| 181 | } |
| 182 | const band = /\bside-band-64k\b/.test(caps); |
| 183 | const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>(); |
| 184 | const w = writable.getWriter(); |
| 185 | const self = this; |
| 186 | (async () => { |
| 187 | const out = async (d: Uint8Array) => { if (band) { for (const p of sideband(1, d)) await w.write(p); } else await w.write(d); }; |
| 188 | try { |
| 189 | await w.write(ack); |
| 190 | const sha = new Sha1(); |
| 191 | const emit = async (d: Uint8Array) => { sha.update(d); await out(d); }; |
| 192 | await emit(packHeader(send.length)); |
| 193 | let batch: Uint8Array[] = []; let n = 0; |
| 194 | for (const s of send) { |
| 195 | const z = self.zOf(s)!; |
| 196 | batch.push(packObjHeader(z.type, z.size), z.z); n += z.z.length; |
| 197 | if (n > 256 * 1024) { await emit(concat(batch)); batch = []; n = 0; } |
| 198 | } |
| 199 | if (batch.length) await emit(concat(batch)); |
| 200 | await out(sha.digest()); |
| 201 | if (band) await w.write(FLUSH); |
| 202 | await w.close(); |
| 203 | } catch (e) { await w.abort(e); } |
| 204 | })(); |
| 205 | return new Response(readable, { headers: { 'content-type': type, 'cache-control': 'no-cache' } }); |
| 206 | } |
| 207 | collectTree(t: string, have: Set<string>, seen: Set<string>, send: string[]) { |
| 208 | if (seen.has(t) || have.has(t)) return; seen.add(t); send.push(t); |
| 209 | for (const e of this.tree(t)) { |
| 210 | if (e.mode === '40000') this.collectTree(e.sha, have, seen, send); |
| 211 | else if (e.mode !== '160000' && !seen.has(e.sha) && !have.has(e.sha)) { seen.add(e.sha); send.push(e.sha); } |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | async receivePack(body: Uint8Array, pusher: Pusher): Promise<Response> { |
| 216 | const { lines, end } = readPkts(body, 0, true); |
| 217 | const cmds: { old: string; neu: string; ref: string }[] = []; let caps = ''; |
| 218 | for (const l of lines) { |
| 219 | if (!l) break; |
| 220 | let s = td.decode(l).replace(/\n$/, ''); |
| 221 | const nul = s.indexOf('\0'); if (nul >= 0) { caps = s.slice(nul + 1); s = s.slice(0, nul); } |
| 222 | const [old, neu, ref] = s.split(' '); |
| 223 | cmds.push({ old, neu, ref }); |
| 224 | } |
| 225 | const band = /\bside-band-64k\b/.test(caps); |
| 226 | const progress: string[] = []; |
| 227 | const results = new Map<string, string>(); // ref -> '' (ok) or reason |
| 228 | let unpack = 'ok'; |
| 229 | const overlay = new Map<string, RawObj>(); |
| 230 | try { |
| 231 | if (end < body.length && cmds.some((c) => c.neu !== ZERO)) { |
| 232 | const objs = await readPack(body.subarray(end), async (sha) => this.get(sha)); |
| 233 | for (const o of objs) overlay.set(o.sha, o); |
| 234 | } |
| 235 | } catch (e) { unpack = (e as Error).message; } |
| 236 | |
| 237 | const refsNow = this.refs(); |
| 238 | const known = unpack === 'ok' ? this.reachable([...refsNow.values()]) : new Set<string>(); |
| 239 | const newCommits = new Map<string, string[]>(); // ref -> new commit shas (oldest first) |
| 240 | if (unpack === 'ok') for (const c of cmds) { |
| 241 | const branch = c.ref.replace(/^refs\/heads\//, ''); |
| 242 | if (!c.ref.startsWith('refs/heads/') || !BRANCH_RE.test(branch)) { results.set(c.ref, 'only branches (refs/heads/...) with plain names can be pushed'); continue; } |
| 243 | if (c.neu === ZERO) { results.set(c.ref, 'branches are removed by votes, not by push'); continue; } |
| 244 | const cur = refsNow.get(c.ref) || ZERO; |
| 245 | if (cur !== c.old) { results.set(c.ref, 'fetch first: the branch moved. Run git pull, then push again'); continue; } |
| 246 | const removed = this.sql.exec("SELECT 1 FROM branches WHERE name = ? AND status = 'removed'", branch).toArray().length; |
| 247 | if (removed && cur === ZERO) { results.set(c.ref, 'this branch name was voted out. Push under a new name'); continue; } |
| 248 | let mine: Set<string>; |
| 249 | try { mine = this.reachable([c.neu], overlay, known); } catch (e) { results.set(c.ref, 'missing objects: ' + (e as Error).message); continue; } |
| 250 | if (cur !== ZERO && !mine.has(cur) && !this.reachable([c.neu], overlay).has(cur)) { results.set(c.ref, 'not a fast-forward. Run git pull, then push again (history is never rewritten here)'); continue; } |
| 251 | if (mine.size > 2000) { results.set(c.ref, 'too many new commits in one push (limit 2000)'); continue; } |
| 252 | // Checks ("tests"): every changed file in every new commit. |
| 253 | const problems: string[] = []; |
| 254 | const checked = new Set<string>(); |
| 255 | for (const sha of mine) { |
| 256 | for (const f of this.changes(sha, overlay).files) { |
| 257 | if (!f.after || f.after.mode === '160000' || checked.has(f.after.sha + f.path)) continue; |
| 258 | checked.add(f.after.sha + f.path); |
| 259 | const blob = this.get(f.after.sha, overlay); |
| 260 | const why = blob ? checkBlob(f.path, blob.data) : 'missing file data'; |
| 261 | if (why) problems.push(`${f.path}: ${why}`); |
| 262 | if (problems.length >= 5) break; |
| 263 | } |
| 264 | if (problems.length >= 5) break; |
| 265 | } |
| 266 | if (problems.length) { results.set(c.ref, 'checks failed: ' + problems.join('; ')); continue; } |
| 267 | const order = [...mine].map((s) => ({ s, t: this.commit(s, overlay).time })).sort((a, b) => a.t - b.t).map((x) => x.s); |
| 268 | newCommits.set(c.ref, order); |
| 269 | results.set(c.ref, ''); |
| 270 | } |
| 271 | |
| 272 | const okRefs = cmds.filter((c) => results.get(c.ref) === ''); |
| 273 | if (okRefs.length) { |
| 274 | for (const o of overlay.values()) this.put(o); |
| 275 | const now = Date.now(); |
| 276 | for (const c of okRefs) { |
| 277 | const branch = c.ref.replace(/^refs\/heads\//, ''); |
| 278 | const first = !this.refs().size; |
| 279 | if (first) this.setMeta('default_branch', branch); |
| 280 | const isDefault = branch === this.defaultBranch(); |
| 281 | this.sql.exec(`INSERT INTO branches (name, status, created_by, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (name) DO NOTHING`, branch, isDefault ? 'kept' : 'new', pusher.handle, now); |
| 282 | this.setRef(branch, c.neu); |
| 283 | const list = newCommits.get(c.ref) || []; |
| 284 | for (const s of list) { |
| 285 | const cm = this.commit(s); |
| 286 | this.sql.exec(`INSERT INTO commits (sha, branch, status, pusher, pushed_at, subject, author) VALUES (?, ?, 'new', ?, ?, ?, ?) ON CONFLICT (sha) DO NOTHING`, |
| 287 | s, branch, pusher.handle, now, cm.message.split('\n')[0].slice(0, 200), personName(cm.author)); |
| 288 | } |
| 289 | const repo = this.meta('name') || ''; |
| 290 | progress.push(`Branchwell: ${branch} updated${list.length ? ` with ${list.length} new commit${list.length === 1 ? '' : 's'}` : ''}. Vote at https://branchwell.ai/${repo}/commits/${encodeURIComponent(branch)}\n`); |
| 291 | } |
| 292 | this.setMeta('updated_at', String(now)); |
| 293 | } |
| 294 | for (const c of cmds) { const r = results.get(c.ref); if (r) progress.push(`Branchwell: ${c.ref.replace('refs/heads/', '')} not updated: ${r}\n`); } |
| 295 | |
| 296 | const report = [pkt(`unpack ${unpack === 'ok' ? 'ok' : unpack.replace(/\n/g, ' ')}\n`)]; |
| 297 | for (const c of cmds) { const r = results.get(c.ref); report.push(pkt(r === '' ? `ok ${c.ref}\n` : `ng ${c.ref} ${(r || unpack).replace(/\n/g, ' ')}\n`)); } |
| 298 | report.push(FLUSH); |
| 299 | const outParts: Uint8Array[] = []; |
| 300 | if (band) { |
| 301 | for (const p of progress) outParts.push(...sideband(2, te.encode(p))); |
| 302 | outParts.push(...sideband(1, concat(report))); |
| 303 | outParts.push(FLUSH); |
| 304 | } else outParts.push(...report); |
| 305 | return new Response(concat(outParts), { headers: { 'content-type': 'application/x-git-receive-pack-result', 'cache-control': 'no-cache' } }); |
| 306 | } |
| 307 | |
| 308 | // ---------------- votes ---------------- |
| 309 | async vote(kind: 'commit' | 'branch', target: string, voter: Voter, value: number): Promise<{ ok: boolean; message: string; status?: string; up?: number; down?: number }> { |
| 310 | if (!voter.canVote) return { ok: false, message: 'New accounts can vote 24 hours after they are made. This keeps votes fair.' }; |
| 311 | value = value > 0 ? 1 : value < 0 ? -1 : 0; |
| 312 | const table = kind === 'commit' ? 'commits' : 'branches'; |
| 313 | const key = kind === 'commit' ? 'sha' : 'name'; |
| 314 | const row = this.sql.exec(`SELECT * FROM ${table} WHERE ${key} = ?`, target).toArray()[0]; |
| 315 | if (!row) return { ok: false, message: `That ${kind} isn't open for votes.` }; |
| 316 | if (row.status === 'removed') return { ok: false, message: `That ${kind} was already removed by votes.` }; |
| 317 | if (row.status === 'system') return { ok: false, message: 'Removals made by votes are not voted on.' }; |
| 318 | if (row.status === 'kept') return { ok: false, message: `That ${kind} already got ${VOTES_TO_DECIDE} votes up and stays for good.`, status: 'kept' }; |
| 319 | const owner = kind === 'commit' ? row.pusher : row.created_by; |
| 320 | if (owner === voter.handle && value > 0) return { ok: false, message: 'You can vote down your own work, but not up. Others decide what stays.' }; |
| 321 | if (value === 0) this.sql.exec('DELETE FROM votes WHERE kind = ? AND target = ? AND account = ?', kind, target, voter.id); |
| 322 | else this.sql.exec('INSERT INTO votes (kind, target, account, handle, value, at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (kind, target, account) DO UPDATE SET value = excluded.value, at = excluded.at', |
| 323 | kind, target, voter.id, voter.handle, value, Date.now()); |
| 324 | const t = this.sql.exec('SELECT SUM(value > 0) AS up, SUM(value < 0) AS down FROM votes WHERE kind = ? AND target = ?', kind, target).toArray()[0]; |
| 325 | const up = (t.up as number) || 0, down = (t.down as number) || 0; |
| 326 | this.sql.exec(`UPDATE ${table} SET up = ?, down = ? WHERE ${key} = ?`, up, down, target); |
| 327 | if (down >= VOTES_TO_DECIDE) { |
| 328 | const msg = kind === 'commit' ? this.removeCommit(target) : this.removeBranch(target); |
| 329 | return { ok: true, message: msg, status: 'removed', up, down }; |
| 330 | } |
| 331 | if (up >= VOTES_TO_DECIDE) { |
| 332 | this.sql.exec(`UPDATE ${table} SET status = 'kept' WHERE ${key} = ?`, target); |
| 333 | return { ok: true, message: `${VOTES_TO_DECIDE} votes up: it stays for good.`, status: 'kept', up, down }; |
| 334 | } |
| 335 | return { ok: true, message: 'Vote counted.', status: row.status as string, up, down }; |
| 336 | } |
| 337 | |
| 338 | removeBranch(name: string): string { |
| 339 | if (name === this.defaultBranch()) { this.sql.exec("UPDATE branches SET status = 'kept' WHERE name = ?", name); return 'The main branch always stays.'; } |
| 340 | this.sql.exec("UPDATE branches SET status = 'removed', removed_at = ? WHERE name = ?", Date.now(), name); |
| 341 | this.sql.exec('DELETE FROM refs WHERE name = ?', 'refs/heads/' + name); |
| 342 | return `${VOTES_TO_DECIDE} votes down: the branch ${name} was removed.`; |
| 343 | } |
| 344 | |
| 345 | /** Takes a commit's changes back out of its branch with a new commit, file by file. History is never rewritten. */ |
| 346 | removeCommit(sha: string): string { |
| 347 | const row = this.sql.exec('SELECT * FROM commits WHERE sha = ?', sha).toArray()[0]; |
| 348 | const branch = row.branch as string; |
| 349 | const tip = this.refs().get('refs/heads/' + branch); |
| 350 | if (!tip) { this.sql.exec("UPDATE commits SET status = 'removed', note = ? WHERE sha = ?", 'branch already removed', sha); return 'Removed.'; } |
| 351 | const { commit: c, files } = this.changes(sha); |
| 352 | const cur = this.flatten(this.commit(tip).tree); |
| 353 | let undone = 0, skipped = 0; |
| 354 | for (const f of files) { |
| 355 | const now = cur.get(f.path); |
| 356 | const same = (a?: { mode: string; sha: string }, b?: { mode: string; sha: string }) => (!a && !b) || (!!a && !!b && a.sha === b.sha && a.mode === b.mode); |
| 357 | if (!same(now, f.after)) { skipped++; continue; } // changed again later: leave the newer work alone |
| 358 | if (f.before) cur.set(f.path, f.before); else cur.delete(f.path); |
| 359 | undone++; |
| 360 | } |
| 361 | let note = `${undone} file${undone === 1 ? '' : 's'} restored`; |
| 362 | if (skipped) note += `, ${skipped} left alone because later commits changed them`; |
| 363 | if (undone) { |
| 364 | const tree = this.buildTree(cur); |
| 365 | const ts = Math.floor(Date.now() / 1000); |
| 366 | const who = `Branchwell votes <votes@branchwell.ai> ${ts} +0000`; |
| 367 | const subject = c.message.split('\n')[0].slice(0, 120); |
| 368 | const msg = `Remove "${subject}" (voted down)\n\n${VOTES_TO_DECIDE} people voted down commit ${sha.slice(0, 10)}, so its changes were taken back out.\n${note}.\n`; |
| 369 | const neu = this.make('commit', te.encode(`tree ${tree}\nparent ${tip}\nauthor ${who}\ncommitter ${who}\n\n${msg}`)); |
| 370 | this.setRef(branch, neu); |
| 371 | this.sql.exec(`INSERT INTO commits (sha, branch, status, pusher, pushed_at, subject, author, note) VALUES (?, ?, 'system', 'branchwell', ?, ?, 'Branchwell votes', ?)`, |
| 372 | neu, branch, Date.now(), `Remove "${subject}" (voted down)`, sha); |
| 373 | } |
| 374 | this.sql.exec("UPDATE commits SET status = 'removed', note = ? WHERE sha = ?", note, sha); |
| 375 | return `${VOTES_TO_DECIDE} votes down: the commit was removed from ${branch} (${note}).`; |
| 376 | } |
| 377 | |
| 378 | // ---------------- reads for the web pages ---------------- |
| 379 | async init(name: string) { if (!this.meta('name')) { this.setMeta('name', name); this.setMeta('created_at', String(Date.now())); } return true; } |
| 380 | |
| 381 | resolve(ref: string): string | null { |
| 382 | const refs = this.refs(); |
| 383 | if (refs.has('refs/heads/' + ref)) return refs.get('refs/heads/' + ref)!; |
| 384 | if (/^[0-9a-f]{40}$/.test(ref) && this.has(ref)) return ref; |
| 385 | if (/^[0-9a-f]{7,39}$/.test(ref)) { const r = this.sql.exec("SELECT sha FROM objects WHERE sha LIKE ? || '%' AND type = 1 LIMIT 2", ref).toArray(); if (r.length === 1) return r[0].sha as string; } |
| 386 | return null; |
| 387 | } |
| 388 | |
| 389 | async overview() { |
| 390 | const branches = this.sql.exec('SELECT name, status, up, down, created_by, created_at, removed_at, last_sha FROM branches ORDER BY (name = ?) DESC, created_at DESC', this.defaultBranch()).toArray(); |
| 391 | const counts = this.sql.exec("SELECT COUNT(*) AS n, SUM(status = 'new') AS open, SUM(status = 'removed') AS removed FROM commits").toArray()[0]; |
| 392 | return { name: this.meta('name'), defaultBranch: this.defaultBranch(), empty: this.refs().size === 0, branches, commits: counts, updatedAt: Number(this.meta('updated_at') || 0) }; |
| 393 | } |
| 394 | |
| 395 | async listTree(ref: string, path: string) { |
| 396 | const sha = this.resolve(ref); if (!sha) return null; |
| 397 | const c = this.commit(sha); |
| 398 | let t = c.tree; |
| 399 | for (const part of path.split('/').filter(Boolean)) { |
| 400 | const e = this.tree(t).find((x) => x.name === part); |
| 401 | if (!e) return null; |
| 402 | if (e.mode !== '40000') return { kind: 'blob' as const, commit: sha }; |
| 403 | t = e.sha; |
| 404 | } |
| 405 | const entries = this.tree(t).map((e) => ({ name: e.name, dir: e.mode === '40000', sha: e.sha, size: e.mode === '40000' ? 0 : ((this.sql.exec('SELECT size FROM objects WHERE sha = ?', e.sha).toArray()[0]?.size as number) || 0) })) |
| 406 | .sort((a, b) => (a.dir === b.dir ? a.name.localeCompare(b.name) : a.dir ? -1 : 1)); |
| 407 | return { kind: 'tree' as const, commit: sha, entries, last: { sha, subject: c.message.split('\n')[0], author: personName(c.author), time: c.time } }; |
| 408 | } |
| 409 | |
| 410 | async readBlob(ref: string, path: string): Promise<{ data: Uint8Array; sha: string; commit: string } | null> { |
| 411 | const sha = this.resolve(ref); if (!sha) return null; |
| 412 | let t = this.commit(sha).tree; |
| 413 | const parts = path.split('/').filter(Boolean); |
| 414 | for (let i = 0; i < parts.length; i++) { |
| 415 | const e = this.tree(t).find((x) => x.name === parts[i]); |
| 416 | if (!e) return null; |
| 417 | if (i === parts.length - 1) { if (e.mode === '40000') return null; const o = this.get(e.sha); return o ? { data: o.data, sha: e.sha, commit: sha } : null; } |
| 418 | if (e.mode !== '40000') return null; |
| 419 | t = e.sha; |
| 420 | } |
| 421 | return null; |
| 422 | } |
| 423 | |
| 424 | async log(ref: string, skip = 0, limit = 30) { |
| 425 | const tip = this.resolve(ref); if (!tip) return null; |
| 426 | const out: Record<string, unknown>[] = []; |
| 427 | const seen = new Set<string>(); const heap: { sha: string; time: number }[] = [{ sha: tip, time: this.commit(tip).time }]; |
| 428 | let i = 0; |
| 429 | while (heap.length && out.length < limit) { |
| 430 | heap.sort((a, b) => b.time - a.time); |
| 431 | const { sha } = heap.shift()!; if (seen.has(sha)) continue; seen.add(sha); |
| 432 | const c = this.commit(sha); |
| 433 | for (const p of c.parents) if (!seen.has(p)) heap.push({ sha: p, time: this.commit(p).time }); |
| 434 | if (i++ < skip) continue; |
| 435 | const m = this.sql.exec('SELECT branch, status, up, down, pusher, pushed_at, note FROM commits WHERE sha = ?', sha).toArray()[0] || null; |
| 436 | out.push({ sha, subject: c.message.split('\n')[0], author: personName(c.author), time: c.time, parents: c.parents, meta: m }); |
| 437 | } |
| 438 | return { tip, commits: out, more: heap.length > 0 }; |
| 439 | } |
| 440 | |
| 441 | async commitInfo(ref: string) { |
| 442 | const sha = this.resolve(ref); if (!sha) return null; |
| 443 | const { commit: c, files } = this.changes(sha); |
| 444 | const meta = this.sql.exec('SELECT branch, status, up, down, pusher, pushed_at, note FROM commits WHERE sha = ?', sha).toArray()[0] || null; |
| 445 | const voters = this.sql.exec("SELECT handle, value FROM votes WHERE kind = 'commit' AND target = ? ORDER BY at", sha).toArray(); |
| 446 | const diffs = files.slice(0, 50).map((f) => { |
| 447 | const a = f.before ? this.get(f.before.sha) : null, b = f.after ? this.get(f.after.sha) : null; |
| 448 | return { path: f.path, status: f.status, before: a && isText(a.data) && a.data.length < 200_000 ? td.decode(a.data) : a ? null : '', after: b && isText(b.data) && b.data.length < 200_000 ? td.decode(b.data) : b ? null : '' }; |
| 449 | }); |
| 450 | return { sha, commit: c, meta, voters, files: files.map((f) => ({ path: f.path, status: f.status })), diffs }; |
| 451 | } |
| 452 | |
| 453 | async myVotes(account: string, kind: string, targets: string[]): Promise<Record<string, number>> { |
| 454 | const out: Record<string, number> = {}; |
| 455 | for (const t of targets.slice(0, 200)) { const r = this.sql.exec('SELECT value FROM votes WHERE kind = ? AND target = ? AND account = ?', kind, t, account).toArray()[0]; if (r) out[t] = r.value as number; } |
| 456 | return out; |
| 457 | } |
| 458 | |
| 459 | async branchVotes(name: string) { |
| 460 | return this.sql.exec("SELECT handle, value FROM votes WHERE kind = 'branch' AND target = ? ORDER BY at", name).toArray(); |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | export function isText(d: Uint8Array): boolean { |
| 465 | const n = Math.min(d.length, 8000); |
| 466 | for (let i = 0; i < n; i++) if (d[i] === 0) return false; |
| 467 | return true; |
| 468 | } |