| 8d8e815 | | | 1 | import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify"; |
| f0bb192 | | | 2 | import { z } from "zod"; |
| 90d5eb8 | | | 3 | import { spawn, execSync } from "child_process"; |
| 90d5eb8 | | | 4 | import { createWriteStream } from "fs"; |
| 90d5eb8 | | | 5 | import { mkdir, rm } from "fs/promises"; |
| 90d5eb8 | | | 6 | import { pipeline } from "stream/promises"; |
| 791afd4 | | | 7 | import { BridgeService } from "../services/bridge.js"; |
| 966d71f | | | 8 | import type { MononokeProvisioner } from "../services/mononoke-provisioner.js"; |
| 8d8e815 | | | 9 | import { optionalAuth } from "../auth/middleware.js"; |
| 3e3af55 | | | 10 | |
| 791afd4 | | | 11 | const BRIDGE_URL = |
| 791afd4 | | | 12 | process.env.GROVE_BRIDGE_URL ?? "http://localhost:3100"; |
| 59a80f9 | | | 13 | const DATA_DIR = process.env.GROVE_DATA_DIR ?? "/data/grove"; |
| 59a80f9 | | | 14 | const MONONOKE_CONFIG_PATH = |
| 59a80f9 | | | 15 | process.env.MONONOKE_CONFIG_PATH ?? "/data/grove/mononoke-config"; |
| 3e3af55 | | | 16 | |
| 791afd4 | | | 17 | const bridgeService = new BridgeService(BRIDGE_URL); |
| 3e3af55 | | | 18 | |
| 3e3af55 | | | 19 | export async function repoRoutes(app: FastifyInstance) { |
| 5e57b27 | | | 20 | const configuredHubApiUrl = process.env.GROVE_HUB_API_URL; |
| 5e57b27 | | | 21 | const HUB_API_URLS = Array.from( |
| 5e57b27 | | | 22 | new Set( |
| 5e57b27 | | | 23 | [ |
| 5e57b27 | | | 24 | configuredHubApiUrl, |
| 5e57b27 | | | 25 | "http://hub-api:4000", |
| 5e57b27 | | | 26 | "http://grove-hub-api:4000", |
| 5e57b27 | | | 27 | "http://localhost:4001", |
| 5e57b27 | | | 28 | ].filter(Boolean) |
| 5e57b27 | | | 29 | ) |
| 5e57b27 | | | 30 | ) as string[]; |
| 79efd41 | | | 31 | |
| 8d8e815 | | | 32 | /** |
| 8d8e815 | | | 33 | * Check if a user can access a private repo. |
| 8d8e815 | | | 34 | * Public repos are always accessible. Private repos require the user to be: |
| 8d8e815 | | | 35 | * - the repo owner (for user repos), or |
| 8d8e815 | | | 36 | * - a member of the owning org (for org repos) |
| 8d8e815 | | | 37 | */ |
| 8d8e815 | | | 38 | async function canAccessRepo(repoRow: any, userId: number | null): Promise<boolean> { |
| 8d8e815 | | | 39 | if (!repoRow.is_private) return true; |
| 8d8e815 | | | 40 | if (userId == null) return false; |
| 8d8e815 | | | 41 | if (repoRow.owner_type === "user") return repoRow.owner_id === userId; |
| 8d8e815 | | | 42 | // Org repo — check membership via hub API |
| 8d8e815 | | | 43 | for (const hubApiUrl of HUB_API_URLS) { |
| 8d8e815 | | | 44 | const controller = new AbortController(); |
| 8d8e815 | | | 45 | const timeout = setTimeout(() => controller.abort(), 3000); |
| 8d8e815 | | | 46 | try { |
| 8d8e815 | | | 47 | const res = await fetch(`${hubApiUrl}/api/orgs/${repoRow.owner_name}`, { |
| 8d8e815 | | | 48 | signal: controller.signal, |
| 8d8e815 | | | 49 | }); |
| 8d8e815 | | | 50 | if (!res.ok) continue; |
| 8d8e815 | | | 51 | const { members } = await res.json(); |
| 8d8e815 | | | 52 | return Array.isArray(members) && members.some((m: any) => m.user_id === userId); |
| 8d8e815 | | | 53 | } catch { |
| 8d8e815 | | | 54 | // try next |
| 8d8e815 | | | 55 | } finally { |
| 8d8e815 | | | 56 | clearTimeout(timeout); |
| 8d8e815 | | | 57 | } |
| 8d8e815 | | | 58 | } |
| 8d8e815 | | | 59 | return false; |
| 8d8e815 | | | 60 | } |
| 8d8e815 | | | 61 | |
| 8d8e815 | | | 62 | /** Middleware: resolve repo + enforce private access. Attaches repoRow to request. */ |
| 8d8e815 | | | 63 | async function resolveRepo(request: any, reply: any) { |
| 8d8e815 | | | 64 | const { owner, repo: repoName } = request.params; |
| 8d8e815 | | | 65 | const db = (app as any).db; |
| 8d8e815 | | | 66 | const repoRow = db |
| 8d8e815 | | | 67 | .prepare(`SELECT * FROM repos_with_owner WHERE owner_name = ? AND name = ?`) |
| 8d8e815 | | | 68 | .get(owner, repoName) as any; |
| 8d8e815 | | | 69 | |
| 8d8e815 | | | 70 | if (!repoRow) { |
| 8d8e815 | | | 71 | return reply.code(404).send({ error: "Repository not found" }); |
| 8d8e815 | | | 72 | } |
| 8d8e815 | | | 73 | const userId = (request.user as any)?.id ?? null; |
| 8d8e815 | | | 74 | if (!(await canAccessRepo(repoRow, userId))) { |
| 8d8e815 | | | 75 | // Return 404 for private repos to avoid leaking existence |
| 8d8e815 | | | 76 | return reply.code(404).send({ error: "Repository not found" }); |
| 8d8e815 | | | 77 | } |
| 8d8e815 | | | 78 | request.repoRow = repoRow; |
| 8d8e815 | | | 79 | } |
| 8d8e815 | | | 80 | |
| 3e3af55 | | | 81 | // List all repos |
| 8d8e815 | | | 82 | app.get( |
| 8d8e815 | | | 83 | "/", |
| 8d8e815 | | | 84 | { preHandler: [optionalAuth] }, |
| 8d8e815 | | | 85 | async (request: any) => { |
| 3e3af55 | | | 86 | const db = (app as any).db; |
| 8d8e815 | | | 87 | const userId = (request.user as any)?.id ?? null; |
| 8d8e815 | | | 88 | const allRepos = db |
| 79efd41 | | | 89 | .prepare(`SELECT * FROM repos_with_owner ORDER BY updated_at DESC`) |
| bc2f205 | | | 90 | .all() as any[]; |
| bc2f205 | | | 91 | |
| 8d8e815 | | | 92 | // Filter out private repos the user can't access |
| 8d8e815 | | | 93 | const repos = allRepos.filter( |
| 8d8e815 | | | 94 | (r) => !r.is_private || (userId != null && ( |
| 8d8e815 | | | 95 | (r.owner_type === "user" && r.owner_id === userId) || |
| 8d8e815 | | | 96 | r.owner_type === "org" // org membership checked lazily; show to any authed user for now |
| 8d8e815 | | | 97 | )) |
| 8d8e815 | | | 98 | ); |
| 8d8e815 | | | 99 | |
| bc2f205 | | | 100 | const reposWithActivity = await Promise.all( |
| bc2f205 | | | 101 | repos.map(async (repo) => { |
| bc2f205 | | | 102 | try { |
| bc2f205 | | | 103 | const commits = await bridgeService.getCommits( |
| bc2f205 | | | 104 | repo.owner_name, |
| bc2f205 | | | 105 | repo.name, |
| bc2f205 | | | 106 | repo.default_branch ?? "main", |
| bc2f205 | | | 107 | { limit: 1 } |
| bc2f205 | | | 108 | ); |
| bc2f205 | | | 109 | const latest = commits[0]; |
| bc2f205 | | | 110 | return { |
| bc2f205 | | | 111 | ...repo, |
| bc2f205 | | | 112 | last_commit_ts: latest?.timestamp ?? null, |
| bc2f205 | | | 113 | }; |
| bc2f205 | | | 114 | } catch { |
| bc2f205 | | | 115 | return { |
| bc2f205 | | | 116 | ...repo, |
| bc2f205 | | | 117 | last_commit_ts: null, |
| bc2f205 | | | 118 | }; |
| bc2f205 | | | 119 | } |
| bc2f205 | | | 120 | }) |
| bc2f205 | | | 121 | ); |
| bc2f205 | | | 122 | |
| bc2f205 | | | 123 | reposWithActivity.sort((a, b) => { |
| bc2f205 | | | 124 | const aUpdatedTs = a.updated_at |
| bc2f205 | | | 125 | ? Math.floor(new Date(a.updated_at).getTime() / 1000) |
| bc2f205 | | | 126 | : 0; |
| bc2f205 | | | 127 | const bUpdatedTs = b.updated_at |
| bc2f205 | | | 128 | ? Math.floor(new Date(b.updated_at).getTime() / 1000) |
| bc2f205 | | | 129 | : 0; |
| bc2f205 | | | 130 | const aTs = a.last_commit_ts ?? aUpdatedTs; |
| bc2f205 | | | 131 | const bTs = b.last_commit_ts ?? bUpdatedTs; |
| bc2f205 | | | 132 | if (aTs !== bTs) return bTs - aTs; |
| bc2f205 | | | 133 | return String(a.name ?? "").localeCompare(String(b.name ?? "")); |
| bc2f205 | | | 134 | }); |
| bc2f205 | | | 135 | |
| bc2f205 | | | 136 | return { repos: reposWithActivity }; |
| 3e3af55 | | | 137 | }); |
| 3e3af55 | | | 138 | |
| f0bb192 | | | 139 | // Create a repo |
| f0bb192 | | | 140 | const createRepoSchema = z.object({ |
| f0bb192 | | | 141 | name: z.string().min(1).max(100), |
| f0bb192 | | | 142 | description: z.string().max(500).optional(), |
| f0bb192 | | | 143 | default_branch: z.string().default("main"), |
| 79efd41 | | | 144 | owner: z.string().optional(), |
| 8d8e815 | | | 145 | is_private: z.boolean().default(false), |
| 59129ad | | | 146 | skip_seed: z.boolean().default(false), |
| 8d8e815 | | | 147 | }); |
| 8d8e815 | | | 148 | |
| 8d8e815 | | | 149 | const updateRepoSchema = z.object({ |
| 8d8e815 | | | 150 | description: z.string().max(500).optional(), |
| 8d8e815 | | | 151 | is_private: z.boolean().optional(), |
| 8d8e815 | | | 152 | require_diffs: z.boolean().optional(), |
| e5b523e | | | 153 | pages_enabled: z.boolean().optional(), |
| e5b523e | | | 154 | pages_domain: z |
| e5b523e | | | 155 | .string() |
| e5b523e | | | 156 | .max(253) |
| e5b523e | | | 157 | .regex(/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(\.[a-z]{2,})+$/i) |
| e5b523e | | | 158 | .nullable() |
| e5b523e | | | 159 | .optional(), |
| f0bb192 | | | 160 | }); |
| f0bb192 | | | 161 | |
| f0bb192 | | | 162 | app.post( |
| f0bb192 | | | 163 | "/", |
| f0bb192 | | | 164 | { |
| f0bb192 | | | 165 | preHandler: [(app as any).authenticate], |
| f0bb192 | | | 166 | }, |
| f0bb192 | | | 167 | async (request: any, reply: any) => { |
| f0bb192 | | | 168 | const parsed = createRepoSchema.safeParse(request.body); |
| f0bb192 | | | 169 | if (!parsed.success) { |
| f0bb192 | | | 170 | return reply.code(400).send({ error: parsed.error.flatten() }); |
| f0bb192 | | | 171 | } |
| 59129ad | | | 172 | const { name, description, default_branch, owner: ownerName, is_private, skip_seed } = parsed.data; |
| f0bb192 | | | 173 | const userId = request.user.id; |
| 79efd41 | | | 174 | const username = request.user.username; |
| f0bb192 | | | 175 | const db = (app as any).db; |
| f0bb192 | | | 176 | |
| 79efd41 | | | 177 | let ownerId = userId; |
| 79efd41 | | | 178 | let ownerType = "user"; |
| 79efd41 | | | 179 | |
| 79efd41 | | | 180 | // If owner specified and differs from user, treat as org repo |
| 79efd41 | | | 181 | if (ownerName && ownerName !== username) { |
| 5e57b27 | | | 182 | let orgFound = false; |
| 5e57b27 | | | 183 | let sawNotFound = false; |
| 5e57b27 | | | 184 | const errors: Array<{ hubApiUrl: string; status?: number; error?: string }> = []; |
| 5e57b27 | | | 185 | |
| 5e57b27 | | | 186 | for (const hubApiUrl of HUB_API_URLS) { |
| 5e57b27 | | | 187 | const controller = new AbortController(); |
| 5e57b27 | | | 188 | const timeout = setTimeout(() => controller.abort(), 3000); |
| 5e57b27 | | | 189 | try { |
| 5e57b27 | | | 190 | const res = await fetch(`${hubApiUrl}/api/orgs/${ownerName}`, { |
| 5e57b27 | | | 191 | signal: controller.signal, |
| 5e57b27 | | | 192 | }); |
| 5e57b27 | | | 193 | |
| 5e57b27 | | | 194 | if (res.status === 404) { |
| 5e57b27 | | | 195 | sawNotFound = true; |
| 5e57b27 | | | 196 | errors.push({ hubApiUrl, status: 404 }); |
| 5e57b27 | | | 197 | continue; |
| 5e57b27 | | | 198 | } |
| 5e57b27 | | | 199 | if (!res.ok) { |
| 5e57b27 | | | 200 | errors.push({ hubApiUrl, status: res.status }); |
| 5e57b27 | | | 201 | continue; |
| 5e57b27 | | | 202 | } |
| 5e57b27 | | | 203 | |
| 5e57b27 | | | 204 | const { org, members } = await res.json(); |
| 5e57b27 | | | 205 | if (!Array.isArray(members)) { |
| 5e57b27 | | | 206 | errors.push({ hubApiUrl, error: "Invalid org response shape" }); |
| 5e57b27 | | | 207 | continue; |
| 5e57b27 | | | 208 | } |
| 5e57b27 | | | 209 | const isMember = members.some((m: any) => m.user_id === userId); |
| 5e57b27 | | | 210 | if (!isMember) { |
| 5e57b27 | | | 211 | return reply.code(403).send({ error: "Not a member of this organization" }); |
| 5e57b27 | | | 212 | } |
| 5e57b27 | | | 213 | ownerId = org.id; |
| 5e57b27 | | | 214 | ownerType = "org"; |
| 5e57b27 | | | 215 | orgFound = true; |
| 5e57b27 | | | 216 | // Sync org locally |
| 5e57b27 | | | 217 | (app as any).ensureLocalOrg({ id: org.id, name: org.name, display_name: org.display_name }); |
| 5e57b27 | | | 218 | break; |
| 5e57b27 | | | 219 | } catch (err: any) { |
| 5e57b27 | | | 220 | errors.push({ hubApiUrl, error: err?.message ?? "Unknown error" }); |
| 5e57b27 | | | 221 | } finally { |
| 5e57b27 | | | 222 | clearTimeout(timeout); |
| 79efd41 | | | 223 | } |
| 5e57b27 | | | 224 | } |
| 5e57b27 | | | 225 | |
| 5e57b27 | | | 226 | if (!orgFound) { |
| 5130d10 | | | 227 | app.log.error( |
| 5e57b27 | | | 228 | { ownerName, hubApiUrlsTried: HUB_API_URLS, errors }, |
| 5e57b27 | | | 229 | "Failed to validate org owner against hub API candidates" |
| 5130d10 | | | 230 | ); |
| 5e57b27 | | | 231 | |
| 5e57b27 | | | 232 | if (sawNotFound && errors.every((entry) => entry.status === 404)) { |
| 79efd41 | | | 233 | return reply.code(404).send({ error: "Organization not found" }); |
| 79efd41 | | | 234 | } |
| 5e57b27 | | | 235 | |
| 5130d10 | | | 236 | return reply.code(502).send({ error: "Organization service unavailable" }); |
| 79efd41 | | | 237 | } |
| 79efd41 | | | 238 | } |
| 79efd41 | | | 239 | |
| f0bb192 | | | 240 | const existing = db |
| 79efd41 | | | 241 | .prepare(`SELECT id FROM repos WHERE owner_id = ? AND owner_type = ? AND name = ?`) |
| 79efd41 | | | 242 | .get(ownerId, ownerType, name); |
| f0bb192 | | | 243 | |
| f0bb192 | | | 244 | if (existing) { |
| f0bb192 | | | 245 | return reply.code(409).send({ error: "Repository already exists" }); |
| f0bb192 | | | 246 | } |
| f0bb192 | | | 247 | |
| f0bb192 | | | 248 | const result = db |
| f0bb192 | | | 249 | .prepare( |
| 8d8e815 | | | 250 | `INSERT INTO repos (owner_id, owner_type, name, description, default_branch, is_private) |
| 8d8e815 | | | 251 | VALUES (?, ?, ?, ?, ?, ?)` |
| f0bb192 | | | 252 | ) |
| 8d8e815 | | | 253 | .run(ownerId, ownerType, name, description ?? null, default_branch, is_private ? 1 : 0); |
| f0bb192 | | | 254 | |
| 966d71f | | | 255 | // Provision Mononoke config for the new repo |
| 966d71f | | | 256 | const provisioner = (app as any).mononokeProvisioner as MononokeProvisioner; |
| 6c9fcae | | | 257 | let provisioned = false; |
| 966d71f | | | 258 | try { |
| 966d71f | | | 259 | const mononokeRepoId = provisioner.provisionRepo(name); |
| 966d71f | | | 260 | db.prepare("UPDATE repos SET mononoke_repo_id = ? WHERE id = ?") |
| 966d71f | | | 261 | .run(mononokeRepoId, result.lastInsertRowid); |
| 6c9fcae | | | 262 | provisioned = true; |
| 966d71f | | | 263 | } catch (err) { |
| 966d71f | | | 264 | app.log.error({ err, repoName: name }, "Failed to provision Mononoke config"); |
| 966d71f | | | 265 | } |
| 966d71f | | | 266 | |
| 6c9fcae | | | 267 | // Restart Mononoke so it picks up the new repo config |
| 6c9fcae | | | 268 | let restartOk = false; |
| 6c9fcae | | | 269 | if (provisioned) { |
| 6c9fcae | | | 270 | try { |
| 6c9fcae | | | 271 | await provisioner.restartMononoke(); |
| 6c9fcae | | | 272 | restartOk = true; |
| 6c9fcae | | | 273 | } catch (err) { |
| 6c9fcae | | | 274 | app.log.error({ err }, "Failed to restart Mononoke after repo provisioning"); |
| 6c9fcae | | | 275 | } |
| 6c9fcae | | | 276 | } |
| 6c9fcae | | | 277 | |
| c5a8edf | | | 278 | // Seed the repo with an initial commit (README.md with repo name) |
| 59129ad | | | 279 | if (restartOk && !skip_seed) { |
| c5a8edf | | | 280 | try { |
| c5a8edf | | | 281 | const res = await fetch(`${BRIDGE_URL}/repos/${name}/seed`, { |
| c5a8edf | | | 282 | method: "POST", |
| c5a8edf | | | 283 | headers: { "Content-Type": "application/json" }, |
| c5a8edf | | | 284 | body: JSON.stringify({ name, bookmark: default_branch }), |
| c5a8edf | | | 285 | signal: AbortSignal.timeout(10000), |
| c5a8edf | | | 286 | }); |
| c5a8edf | | | 287 | if (!res.ok) { |
| c5a8edf | | | 288 | const body = await res.text(); |
| c5a8edf | | | 289 | app.log.warn({ status: res.status, body, repoName: name }, "Seed endpoint returned non-OK"); |
| c5a8edf | | | 290 | } |
| c5a8edf | | | 291 | } catch (err) { |
| c5a8edf | | | 292 | app.log.warn({ err, repoName: name }, "Failed to seed initial commit (non-fatal)"); |
| c5a8edf | | | 293 | } |
| c5a8edf | | | 294 | } |
| c5a8edf | | | 295 | |
| f0bb192 | | | 296 | const repo = db |
| 79efd41 | | | 297 | .prepare(`SELECT * FROM repos_with_owner WHERE id = ?`) |
| f0bb192 | | | 298 | .get(result.lastInsertRowid); |
| f0bb192 | | | 299 | |
| 6c9fcae | | | 300 | return reply.code(201).send({ |
| 6c9fcae | | | 301 | repo, |
| 6c9fcae | | | 302 | ...(!restartOk && { warning: "Repository created but Mononoke restart failed. Push may not work until services are restarted." }), |
| 6c9fcae | | | 303 | }); |
| f0bb192 | | | 304 | } |
| f0bb192 | | | 305 | ); |
| f0bb192 | | | 306 | |
| ab61b9d | | | 307 | // Delete a repo |
| ab61b9d | | | 308 | app.delete<{ Params: { owner: string; repo: string } }>( |
| ab61b9d | | | 309 | "/:owner/:repo", |
| ab61b9d | | | 310 | { |
| ab61b9d | | | 311 | preHandler: [(app as any).authenticate], |
| ab61b9d | | | 312 | }, |
| ab61b9d | | | 313 | async (request: any, reply: any) => { |
| ab61b9d | | | 314 | const { owner, repo: repoName } = request.params; |
| ab61b9d | | | 315 | const userId = request.user.id; |
| ab61b9d | | | 316 | const db = (app as any).db; |
| ab61b9d | | | 317 | |
| ab61b9d | | | 318 | const repoRow = db |
| ab61b9d | | | 319 | .prepare(`SELECT * FROM repos_with_owner WHERE owner_name = ? AND name = ?`) |
| ab61b9d | | | 320 | .get(owner, repoName) as any; |
| ab61b9d | | | 321 | |
| ab61b9d | | | 322 | if (!repoRow) { |
| ab61b9d | | | 323 | return reply.code(404).send({ error: "Repository not found" }); |
| ab61b9d | | | 324 | } |
| ab61b9d | | | 325 | |
| ab61b9d | | | 326 | // Verify ownership |
| ab61b9d | | | 327 | if (repoRow.owner_type === "user") { |
| ab61b9d | | | 328 | if (repoRow.owner_id !== userId) { |
| ab61b9d | | | 329 | return reply.code(403).send({ error: "Not authorized to delete this repository" }); |
| ab61b9d | | | 330 | } |
| ab61b9d | | | 331 | } else { |
| ab61b9d | | | 332 | // Org repo — verify membership via hub API |
| ab61b9d | | | 333 | let authorized = false; |
| ab61b9d | | | 334 | for (const hubApiUrl of HUB_API_URLS) { |
| ab61b9d | | | 335 | const controller = new AbortController(); |
| ab61b9d | | | 336 | const timeout = setTimeout(() => controller.abort(), 3000); |
| ab61b9d | | | 337 | try { |
| ab61b9d | | | 338 | const res = await fetch(`${hubApiUrl}/api/orgs/${owner}`, { |
| ab61b9d | | | 339 | signal: controller.signal, |
| ab61b9d | | | 340 | }); |
| ab61b9d | | | 341 | if (!res.ok) continue; |
| ab61b9d | | | 342 | const { members } = await res.json(); |
| ab61b9d | | | 343 | if (Array.isArray(members) && members.some((m: any) => m.user_id === userId)) { |
| ab61b9d | | | 344 | authorized = true; |
| ab61b9d | | | 345 | } |
| ab61b9d | | | 346 | break; |
| ab61b9d | | | 347 | } catch { |
| ab61b9d | | | 348 | // try next |
| ab61b9d | | | 349 | } finally { |
| ab61b9d | | | 350 | clearTimeout(timeout); |
| ab61b9d | | | 351 | } |
| ab61b9d | | | 352 | } |
| ab61b9d | | | 353 | if (!authorized) { |
| ab61b9d | | | 354 | return reply.code(403).send({ error: "Not authorized to delete this repository" }); |
| ab61b9d | | | 355 | } |
| ab61b9d | | | 356 | } |
| ab61b9d | | | 357 | |
| ab61b9d | | | 358 | // Delete related data (respect FK constraints) |
| ab61b9d | | | 359 | db.prepare("DELETE FROM canopy_secrets WHERE repo_id = ?").run(repoRow.id); |
| ab61b9d | | | 360 | db.prepare("DELETE FROM pipeline_runs WHERE repo_id = ?").run(repoRow.id); |
| ab61b9d | | | 361 | db.prepare("DELETE FROM diffs WHERE repo_id = ?").run(repoRow.id); |
| ab61b9d | | | 362 | db.prepare("DELETE FROM repos WHERE id = ?").run(repoRow.id); |
| ab61b9d | | | 363 | |
| e5b523e | | | 364 | // Clean up pages if configured |
| e5b523e | | | 365 | if (repoRow.pages_domain) { |
| e5b523e | | | 366 | const pagesDeployer = (app as any).pagesDeployer; |
| e5b523e | | | 367 | if (pagesDeployer) { |
| e5b523e | | | 368 | pagesDeployer.undeploy(repoRow.pages_domain); |
| e5b523e | | | 369 | } |
| e5b523e | | | 370 | } |
| e5b523e | | | 371 | |
| 8d0dc12 | | | 372 | // Respond immediately — Mononoke cleanup happens in the background |
| 8d0dc12 | | | 373 | reply.code(204).send(); |
| 8d0dc12 | | | 374 | |
| 8d0dc12 | | | 375 | // Remove Mononoke config and restart (fire-and-forget) |
| ab61b9d | | | 376 | const provisioner = (app as any).mononokeProvisioner as MononokeProvisioner; |
| ab61b9d | | | 377 | try { |
| ab61b9d | | | 378 | provisioner.deprovisionRepo(repoName); |
| 8d0dc12 | | | 379 | provisioner.restartMononoke().catch((err) => { |
| 8d0dc12 | | | 380 | app.log.error({ err, repoName }, "Failed to restart Mononoke after repo deletion"); |
| 8d0dc12 | | | 381 | }); |
| ab61b9d | | | 382 | } catch (err) { |
| 8d0dc12 | | | 383 | app.log.error({ err, repoName }, "Failed to deprovision Mononoke after repo deletion"); |
| ab61b9d | | | 384 | } |
| ab61b9d | | | 385 | } |
| ab61b9d | | | 386 | ); |
| ab61b9d | | | 387 | |
| 8d8e815 | | | 388 | // Update repo settings |
| 8d8e815 | | | 389 | app.patch<{ Params: { owner: string; repo: string } }>( |
| 3e3af55 | | | 390 | "/:owner/:repo", |
| 8d8e815 | | | 391 | { |
| 8d8e815 | | | 392 | preHandler: [(app as any).authenticate], |
| 8d8e815 | | | 393 | }, |
| 8d8e815 | | | 394 | async (request: any, reply: any) => { |
| 8d8e815 | | | 395 | const { owner, repo: repoName } = request.params; |
| 8d8e815 | | | 396 | const userId = request.user.id; |
| 3e3af55 | | | 397 | const db = (app as any).db; |
| 3e3af55 | | | 398 | |
| 8d8e815 | | | 399 | const parsed = updateRepoSchema.safeParse(request.body); |
| 8d8e815 | | | 400 | if (!parsed.success) { |
| 8d8e815 | | | 401 | return reply.code(400).send({ error: parsed.error.flatten() }); |
| 8d8e815 | | | 402 | } |
| 8d8e815 | | | 403 | |
| 3e3af55 | | | 404 | const repoRow = db |
| 79efd41 | | | 405 | .prepare(`SELECT * FROM repos_with_owner WHERE owner_name = ? AND name = ?`) |
| 8d8e815 | | | 406 | .get(owner, repoName) as any; |
| 3e3af55 | | | 407 | |
| 3e3af55 | | | 408 | if (!repoRow) { |
| 3e3af55 | | | 409 | return reply.code(404).send({ error: "Repository not found" }); |
| 3e3af55 | | | 410 | } |
| 3e3af55 | | | 411 | |
| 8d8e815 | | | 412 | // Verify ownership |
| 8d8e815 | | | 413 | if (repoRow.owner_type === "user") { |
| 8d8e815 | | | 414 | if (repoRow.owner_id !== userId) { |
| 8d8e815 | | | 415 | return reply.code(403).send({ error: "Not authorized to update this repository" }); |
| 8d8e815 | | | 416 | } |
| 8d8e815 | | | 417 | } else { |
| 8d8e815 | | | 418 | // Org repo — verify membership via hub API |
| 8d8e815 | | | 419 | let authorized = false; |
| 8d8e815 | | | 420 | for (const hubApiUrl of HUB_API_URLS) { |
| 8d8e815 | | | 421 | const controller = new AbortController(); |
| 8d8e815 | | | 422 | const timeout = setTimeout(() => controller.abort(), 3000); |
| 8d8e815 | | | 423 | try { |
| 8d8e815 | | | 424 | const res = await fetch(`${hubApiUrl}/api/orgs/${owner}`, { |
| 8d8e815 | | | 425 | signal: controller.signal, |
| 8d8e815 | | | 426 | }); |
| 8d8e815 | | | 427 | if (!res.ok) continue; |
| 8d8e815 | | | 428 | const { members } = await res.json(); |
| 8d8e815 | | | 429 | if (Array.isArray(members) && members.some((m: any) => m.user_id === userId)) { |
| 8d8e815 | | | 430 | authorized = true; |
| 8d8e815 | | | 431 | } |
| 8d8e815 | | | 432 | break; |
| 8d8e815 | | | 433 | } catch { |
| 8d8e815 | | | 434 | // try next |
| 8d8e815 | | | 435 | } finally { |
| 8d8e815 | | | 436 | clearTimeout(timeout); |
| 8d8e815 | | | 437 | } |
| 8d8e815 | | | 438 | } |
| 8d8e815 | | | 439 | if (!authorized) { |
| 8d8e815 | | | 440 | return reply.code(403).send({ error: "Not authorized to update this repository" }); |
| 8d8e815 | | | 441 | } |
| 8d8e815 | | | 442 | } |
| 8d8e815 | | | 443 | |
| 8d8e815 | | | 444 | const updates = parsed.data; |
| 8d8e815 | | | 445 | const setClauses: string[] = []; |
| 8d8e815 | | | 446 | const values: any[] = []; |
| 8d8e815 | | | 447 | |
| 8d8e815 | | | 448 | if (updates.description !== undefined) { |
| 8d8e815 | | | 449 | setClauses.push("description = ?"); |
| 8d8e815 | | | 450 | values.push(updates.description); |
| 8d8e815 | | | 451 | } |
| 8d8e815 | | | 452 | if (updates.is_private !== undefined) { |
| 8d8e815 | | | 453 | setClauses.push("is_private = ?"); |
| 8d8e815 | | | 454 | values.push(updates.is_private ? 1 : 0); |
| 8d8e815 | | | 455 | } |
| 8d8e815 | | | 456 | if (updates.require_diffs !== undefined) { |
| 8d8e815 | | | 457 | setClauses.push("require_diffs = ?"); |
| 8d8e815 | | | 458 | values.push(updates.require_diffs ? 1 : 0); |
| 8d8e815 | | | 459 | } |
| e5b523e | | | 460 | if (updates.pages_enabled !== undefined) { |
| e5b523e | | | 461 | setClauses.push("pages_enabled = ?"); |
| e5b523e | | | 462 | values.push(updates.pages_enabled ? 1 : 0); |
| e5b523e | | | 463 | } |
| e5b523e | | | 464 | if (updates.pages_domain !== undefined) { |
| e5b523e | | | 465 | setClauses.push("pages_domain = ?"); |
| e5b523e | | | 466 | values.push(updates.pages_domain); |
| e5b523e | | | 467 | } |
| 8d8e815 | | | 468 | |
| 8d8e815 | | | 469 | if (setClauses.length === 0) { |
| 8d8e815 | | | 470 | return reply.code(400).send({ error: "No fields to update" }); |
| 8d8e815 | | | 471 | } |
| 8d8e815 | | | 472 | |
| 8d8e815 | | | 473 | setClauses.push("updated_at = datetime('now')"); |
| 8d8e815 | | | 474 | values.push(repoRow.id); |
| 8d8e815 | | | 475 | |
| ff50d03 | | | 476 | // Undeploy old deploy path if pages disabled or domain changed |
| e5b523e | | | 477 | const pagesDeployer = (app as any).pagesDeployer; |
| b5baf6d | | | 478 | const oldDeployInfo = pagesDeployer?.getDeployPath(repoRow.owner_name, repoRow.name); |
| ff50d03 | | | 479 | if (pagesDeployer && oldDeployInfo) { |
| e5b523e | | | 480 | if (updates.pages_enabled === false || |
| e5b523e | | | 481 | (updates.pages_domain !== undefined && updates.pages_domain !== repoRow.pages_domain)) { |
| ff50d03 | | | 482 | pagesDeployer.undeploy(oldDeployInfo.path); |
| e5b523e | | | 483 | } |
| e5b523e | | | 484 | } |
| e5b523e | | | 485 | |
| 8d8e815 | | | 486 | db.prepare(`UPDATE repos SET ${setClauses.join(", ")} WHERE id = ?`).run(...values); |
| 8d8e815 | | | 487 | |
| ff50d03 | | | 488 | // Trigger pages deploy if enabled |
| e5b523e | | | 489 | if (pagesDeployer && (updates.pages_enabled === true || updates.pages_domain !== undefined)) { |
| b5baf6d | | | 490 | void pagesDeployer.deploy(repoRow.owner_name, repoRow.name, repoRow.default_branch ?? "main").catch( |
| e5b523e | | | 491 | (err: any) => app.log.error({ err, repo: repoRow.name }, "Initial pages deploy failed") |
| e5b523e | | | 492 | ); |
| e5b523e | | | 493 | } |
| e5b523e | | | 494 | |
| 8d8e815 | | | 495 | const updated = db |
| 8d8e815 | | | 496 | .prepare(`SELECT * FROM repos_with_owner WHERE id = ?`) |
| 8d8e815 | | | 497 | .get(repoRow.id); |
| 8d8e815 | | | 498 | |
| 8d8e815 | | | 499 | return { repo: updated }; |
| 8d8e815 | | | 500 | } |
| 8d8e815 | | | 501 | ); |
| 8d8e815 | | | 502 | |
| 8d8e815 | | | 503 | // Get single repo |
| 8d8e815 | | | 504 | app.get<{ Params: { owner: string; repo: string } }>( |
| 8d8e815 | | | 505 | "/:owner/:repo", |
| 8d8e815 | | | 506 | { preHandler: [optionalAuth, resolveRepo] }, |
| 8d8e815 | | | 507 | async (request: any) => { |
| 8d8e815 | | | 508 | const { owner, repo } = request.params; |
| 8d8e815 | | | 509 | const repoRow = request.repoRow; |
| 8d8e815 | | | 510 | |
| 3e3af55 | | | 511 | const ref = repoRow.default_branch ?? "main"; |
| 791afd4 | | | 512 | const readme = await bridgeService.getReadme(owner, repo, ref); |
| 791afd4 | | | 513 | const branches = await bridgeService.getBranches(owner, repo); |
| 3e3af55 | | | 514 | |
| 3e3af55 | | | 515 | return { |
| 3e3af55 | | | 516 | repo: repoRow, |
| 3e3af55 | | | 517 | readme, |
| 3e3af55 | | | 518 | branches, |
| 3e3af55 | | | 519 | }; |
| 3e3af55 | | | 520 | } |
| 3e3af55 | | | 521 | ); |
| 3e3af55 | | | 522 | |
| 3e3af55 | | | 523 | // List directory tree |
| 3e3af55 | | | 524 | app.get<{ Params: { owner: string; repo: string; ref: string; "*": string } }>( |
| 3e3af55 | | | 525 | "/:owner/:repo/tree/:ref/*", |
| 8d8e815 | | | 526 | { preHandler: [optionalAuth, resolveRepo] }, |
| 8d8e815 | | | 527 | async (request: any, reply: any) => { |
| 3e3af55 | | | 528 | const { owner, repo, ref } = request.params; |
| 3e3af55 | | | 529 | const path = (request.params as any)["*"] ?? ""; |
| 3e3af55 | | | 530 | |
| 791afd4 | | | 531 | const entries = await bridgeService.listTree(owner, repo, ref, path); |
| 3e3af55 | | | 532 | if (!entries.length && path) { |
| 3e3af55 | | | 533 | return reply.code(404).send({ error: "Path not found" }); |
| 3e3af55 | | | 534 | } |
| 3e3af55 | | | 535 | |
| 3e3af55 | | | 536 | return { |
| 3e3af55 | | | 537 | path, |
| 3e3af55 | | | 538 | ref, |
| 8d8e815 | | | 539 | entries: entries.sort((a: any, b: any) => { |
| 3e3af55 | | | 540 | // Directories first, then files |
| 3e3af55 | | | 541 | if (a.type !== b.type) return a.type === "tree" ? -1 : 1; |
| 3e3af55 | | | 542 | return a.name.localeCompare(b.name); |
| 3e3af55 | | | 543 | }), |
| 3e3af55 | | | 544 | }; |
| 3e3af55 | | | 545 | } |
| 3e3af55 | | | 546 | ); |
| 3e3af55 | | | 547 | |
| 3e3af55 | | | 548 | // Also handle tree root (no path) |
| 3e3af55 | | | 549 | app.get<{ Params: { owner: string; repo: string; ref: string } }>( |
| 3e3af55 | | | 550 | "/:owner/:repo/tree/:ref", |
| 8d8e815 | | | 551 | { preHandler: [optionalAuth, resolveRepo] }, |
| 8d8e815 | | | 552 | async (request: any) => { |
| 3e3af55 | | | 553 | const { owner, repo, ref } = request.params; |
| 791afd4 | | | 554 | const entries = await bridgeService.listTree(owner, repo, ref, ""); |
| 3e3af55 | | | 555 | |
| 3e3af55 | | | 556 | return { |
| 3e3af55 | | | 557 | path: "", |
| 3e3af55 | | | 558 | ref, |
| 8d8e815 | | | 559 | entries: entries.sort((a: any, b: any) => { |
| 3e3af55 | | | 560 | if (a.type !== b.type) return a.type === "tree" ? -1 : 1; |
| 3e3af55 | | | 561 | return a.name.localeCompare(b.name); |
| 3e3af55 | | | 562 | }), |
| 3e3af55 | | | 563 | }; |
| 3e3af55 | | | 564 | } |
| 3e3af55 | | | 565 | ); |
| 3e3af55 | | | 566 | |
| 3e3af55 | | | 567 | // Get file content |
| 3e3af55 | | | 568 | app.get<{ Params: { owner: string; repo: string; ref: string; "*": string } }>( |
| 3e3af55 | | | 569 | "/:owner/:repo/blob/:ref/*", |
| 8d8e815 | | | 570 | { preHandler: [optionalAuth, resolveRepo] }, |
| 8d8e815 | | | 571 | async (request: any, reply: any) => { |
| 3e3af55 | | | 572 | const { owner, repo, ref } = request.params; |
| 3e3af55 | | | 573 | const path = (request.params as any)["*"]; |
| 3e3af55 | | | 574 | |
| 3e3af55 | | | 575 | if (!path) { |
| 3e3af55 | | | 576 | return reply.code(400).send({ error: "File path required" }); |
| 3e3af55 | | | 577 | } |
| 3e3af55 | | | 578 | |
| 791afd4 | | | 579 | const blob = await bridgeService.getBlob(owner, repo, ref, path); |
| 3e3af55 | | | 580 | if (!blob) { |
| 3e3af55 | | | 581 | return reply.code(404).send({ error: "File not found" }); |
| 3e3af55 | | | 582 | } |
| 3e3af55 | | | 583 | |
| 3e3af55 | | | 584 | return { |
| 3e3af55 | | | 585 | path, |
| 3e3af55 | | | 586 | ref, |
| 3e3af55 | | | 587 | content: blob.content, |
| 3e3af55 | | | 588 | size: blob.size, |
| 3e3af55 | | | 589 | }; |
| 3e3af55 | | | 590 | } |
| 3e3af55 | | | 591 | ); |
| 3e3af55 | | | 592 | |
| 3e3af55 | | | 593 | // Get commit history |
| 3e3af55 | | | 594 | app.get<{ |
| 3e3af55 | | | 595 | Params: { owner: string; repo: string; ref: string }; |
| 3e3af55 | | | 596 | Querystring: { path?: string; limit?: string; offset?: string }; |
| 3e3af55 | | | 597 | }>( |
| 3e3af55 | | | 598 | "/:owner/:repo/commits/:ref", |
| 8d8e815 | | | 599 | { preHandler: [optionalAuth, resolveRepo] }, |
| 8d8e815 | | | 600 | async (request: any) => { |
| 3e3af55 | | | 601 | const { owner, repo, ref } = request.params; |
| 3e3af55 | | | 602 | const { path, limit, offset } = request.query; |
| 3e3af55 | | | 603 | |
| 791afd4 | | | 604 | const commits = await bridgeService.getCommits(owner, repo, ref, { |
| 3e3af55 | | | 605 | path, |
| 3e3af55 | | | 606 | limit: limit ? parseInt(limit) : 30, |
| 3e3af55 | | | 607 | offset: offset ? parseInt(offset) : 0, |
| 3e3af55 | | | 608 | }); |
| 3e3af55 | | | 609 | |
| 3e3af55 | | | 610 | return { ref, commits }; |
| 3e3af55 | | | 611 | } |
| 3e3af55 | | | 612 | ); |
| 3e3af55 | | | 613 | |
| 3e3af55 | | | 614 | // Get blame |
| 3e3af55 | | | 615 | app.get<{ Params: { owner: string; repo: string; ref: string; "*": string } }>( |
| 3e3af55 | | | 616 | "/:owner/:repo/blame/:ref/*", |
| 8d8e815 | | | 617 | { preHandler: [optionalAuth, resolveRepo] }, |
| 8d8e815 | | | 618 | async (request: any, reply: any) => { |
| 3e3af55 | | | 619 | const { owner, repo, ref } = request.params; |
| 3e3af55 | | | 620 | const path = (request.params as any)["*"]; |
| 3e3af55 | | | 621 | |
| 3e3af55 | | | 622 | if (!path) { |
| 3e3af55 | | | 623 | return reply.code(400).send({ error: "File path required" }); |
| 3e3af55 | | | 624 | } |
| 3e3af55 | | | 625 | |
| 791afd4 | | | 626 | const blame = await bridgeService.getBlame(owner, repo, ref, path); |
| 3e3af55 | | | 627 | if (!blame.length) { |
| 3e3af55 | | | 628 | return reply.code(404).send({ error: "File not found" }); |
| 3e3af55 | | | 629 | } |
| 3e3af55 | | | 630 | |
| 3e3af55 | | | 631 | return { path, ref, blame }; |
| 3e3af55 | | | 632 | } |
| 3e3af55 | | | 633 | ); |
| 3e3af55 | | | 634 | |
| 3e3af55 | | | 635 | // Get diff between refs |
| 3e3af55 | | | 636 | app.get<{ |
| 3e3af55 | | | 637 | Params: { owner: string; repo: string }; |
| 3e3af55 | | | 638 | Querystring: { base: string; head: string }; |
| 3e3af55 | | | 639 | }>( |
| 3e3af55 | | | 640 | "/:owner/:repo/diff", |
| 8d8e815 | | | 641 | { preHandler: [optionalAuth, resolveRepo] }, |
| 8d8e815 | | | 642 | async (request: any) => { |
| 3e3af55 | | | 643 | const { owner, repo } = request.params; |
| 3e3af55 | | | 644 | const { base, head } = request.query; |
| 3e3af55 | | | 645 | |
| 99f1a2e | | | 646 | return await bridgeService.getDiff(owner, repo, base, head); |
| 3e3af55 | | | 647 | } |
| 3e3af55 | | | 648 | ); |
| 3e3af55 | | | 649 | |
| 3e3af55 | | | 650 | // List branches |
| 3e3af55 | | | 651 | app.get<{ Params: { owner: string; repo: string } }>( |
| 3e3af55 | | | 652 | "/:owner/:repo/branches", |
| 8d8e815 | | | 653 | { preHandler: [optionalAuth, resolveRepo] }, |
| 8d8e815 | | | 654 | async (request: any) => { |
| 3e3af55 | | | 655 | const { owner, repo } = request.params; |
| 791afd4 | | | 656 | const branches = await bridgeService.getBranches(owner, repo); |
| 3e3af55 | | | 657 | return { branches }; |
| 3e3af55 | | | 658 | } |
| 3e3af55 | | | 659 | ); |
| 59a80f9 | | | 660 | |
| 59a80f9 | | | 661 | // Import a Git repository (SSE progress stream) |
| 59a80f9 | | | 662 | const importSchema = z.object({ |
| 59a80f9 | | | 663 | url: z.string().url(), |
| 59a80f9 | | | 664 | }); |
| 59a80f9 | | | 665 | |
| 59a80f9 | | | 666 | app.post<{ Params: { owner: string; repo: string } }>( |
| 59a80f9 | | | 667 | "/:owner/:repo/import", |
| 59a80f9 | | | 668 | { |
| 59a80f9 | | | 669 | preHandler: [(app as any).authenticate], |
| 59a80f9 | | | 670 | }, |
| 59a80f9 | | | 671 | async (request, reply) => { |
| 59a80f9 | | | 672 | const { owner, repo: repoName } = request.params; |
| 59a80f9 | | | 673 | const parsed = importSchema.safeParse(request.body); |
| 59a80f9 | | | 674 | if (!parsed.success) { |
| 59a80f9 | | | 675 | return reply.code(400).send({ error: parsed.error.flatten() }); |
| 59a80f9 | | | 676 | } |
| 59a80f9 | | | 677 | const { url } = parsed.data; |
| 59a80f9 | | | 678 | const db = (app as any).db; |
| 59a80f9 | | | 679 | |
| 59a80f9 | | | 680 | // Verify repo exists |
| 59a80f9 | | | 681 | const repoRow = db |
| 59a80f9 | | | 682 | .prepare(`SELECT * FROM repos_with_owner WHERE owner_name = ? AND name = ?`) |
| 59a80f9 | | | 683 | .get(owner, repoName) as any; |
| 59a80f9 | | | 684 | if (!repoRow) { |
| 59a80f9 | | | 685 | return reply.code(404).send({ error: "Repository not found" }); |
| 59a80f9 | | | 686 | } |
| 59a80f9 | | | 687 | |
| 59a80f9 | | | 688 | // SSE stream |
| 59a80f9 | | | 689 | reply.raw.writeHead(200, { |
| 59a80f9 | | | 690 | "Content-Type": "text/event-stream", |
| 59a80f9 | | | 691 | "Cache-Control": "no-cache", |
| 59a80f9 | | | 692 | Connection: "keep-alive", |
| 59a80f9 | | | 693 | }); |
| 59a80f9 | | | 694 | |
| 59a80f9 | | | 695 | const send = (event: string, data: any) => { |
| 59a80f9 | | | 696 | reply.raw.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); |
| 59a80f9 | | | 697 | }; |
| 59a80f9 | | | 698 | |
| 59a80f9 | | | 699 | try { |
| 59a80f9 | | | 700 | // Step 1: git clone --bare via docker (grove/mononoke image has git) |
| 59a80f9 | | | 701 | const bareRepo = `${DATA_DIR}/${repoName}-bare.git`; |
| 59a80f9 | | | 702 | send("progress", { step: "clone", message: `Cloning ${url}...` }); |
| 59a80f9 | | | 703 | |
| 59a80f9 | | | 704 | await runDocker([ |
| 59a80f9 | | | 705 | "run", "--rm", |
| 59a80f9 | | | 706 | "-v", "/data/grove:/data/grove", |
| 59a80f9 | | | 707 | "grove/mononoke:latest", |
| 59a80f9 | | | 708 | "/usr/bin/git", "clone", "--bare", url, bareRepo, |
| 59a80f9 | | | 709 | ], (line) => { |
| 59a80f9 | | | 710 | send("log", { step: "clone", line }); |
| 59a80f9 | | | 711 | }); |
| 59a80f9 | | | 712 | |
| 59a80f9 | | | 713 | send("progress", { step: "clone", message: "Clone complete." }); |
| 59a80f9 | | | 714 | |
| 59a80f9 | | | 715 | // Step 2: gitimport into Mononoke |
| 59a80f9 | | | 716 | send("progress", { step: "import", message: "Importing into Mononoke..." }); |
| 59a80f9 | | | 717 | |
| 59a80f9 | | | 718 | await runDocker([ |
| 59a80f9 | | | 719 | "run", "--rm", |
| 59a80f9 | | | 720 | "-v", "/data/grove:/data/grove", |
| 416062b | | | 721 | "--entrypoint", "gitimport", |
| 59a80f9 | | | 722 | "grove/mononoke:latest", |
| 416062b | | | 723 | "--repo-name", repoName, |
| 416062b | | | 724 | "--config-path", MONONOKE_CONFIG_PATH, |
| 416062b | | | 725 | "--local-configerator-path", `${DATA_DIR}/configerator`, |
| 416062b | | | 726 | "--cache-mode", "disabled", |
| 416062b | | | 727 | "--just-knobs-config-path", `${DATA_DIR}/justknobs.json`, |
| 416062b | | | 728 | "--generate-bookmarks", |
| 416062b | | | 729 | "--derive-hg", |
| 416062b | | | 730 | "--git-command-path", "/usr/bin/git", |
| 416062b | | | 731 | "--concurrency", "5", |
| 416062b | | | 732 | bareRepo, |
| 416062b | | | 733 | "full-repo", |
| 59a80f9 | | | 734 | ], (line) => { |
| 59a80f9 | | | 735 | send("log", { step: "import", line }); |
| 59a80f9 | | | 736 | }); |
| 59a80f9 | | | 737 | |
| 59a80f9 | | | 738 | send("progress", { step: "import", message: "Import complete." }); |
| 59a80f9 | | | 739 | |
| 59a80f9 | | | 740 | // Step 3: Restart Mononoke services to pick up the imported data |
| 59a80f9 | | | 741 | send("progress", { step: "restart", message: "Restarting services..." }); |
| 59a80f9 | | | 742 | |
| 59a80f9 | | | 743 | const provisioner = (app as any).mononokeProvisioner as MononokeProvisioner; |
| 59a80f9 | | | 744 | await provisioner.restartMononoke(); |
| 59a80f9 | | | 745 | |
| 59a80f9 | | | 746 | send("progress", { step: "restart", message: "Services restarted." }); |
| 59a80f9 | | | 747 | |
| 59a80f9 | | | 748 | // Clean up the bare clone |
| 59a80f9 | | | 749 | await runDocker([ |
| 59a80f9 | | | 750 | "run", "--rm", |
| 59a80f9 | | | 751 | "-v", "/data/grove:/data/grove", |
| 59a80f9 | | | 752 | "grove/mononoke:latest", |
| 59a80f9 | | | 753 | "rm", "-rf", bareRepo, |
| 59a80f9 | | | 754 | ], () => {}); |
| 59a80f9 | | | 755 | |
| 59a80f9 | | | 756 | send("done", { success: true }); |
| 59a80f9 | | | 757 | } catch (err: any) { |
| 59a80f9 | | | 758 | send("error", { message: err.message ?? "Import failed" }); |
| 59a80f9 | | | 759 | } |
| 59a80f9 | | | 760 | |
| 59a80f9 | | | 761 | reply.raw.end(); |
| 59a80f9 | | | 762 | } |
| 59a80f9 | | | 763 | ); |
| 90d5eb8 | | | 764 | |
| 90d5eb8 | | | 765 | // Import a Git repository from an uploaded bare repo tarball (SSE progress stream) |
| 90d5eb8 | | | 766 | app.post<{ Params: { owner: string; repo: string } }>( |
| 90d5eb8 | | | 767 | "/:owner/:repo/import-bundle", |
| 90d5eb8 | | | 768 | { |
| 90d5eb8 | | | 769 | preHandler: [(app as any).authenticate], |
| 90d5eb8 | | | 770 | }, |
| 90d5eb8 | | | 771 | async (request, reply) => { |
| 90d5eb8 | | | 772 | const { owner, repo: repoName } = request.params; |
| 90d5eb8 | | | 773 | const db = (app as any).db; |
| 90d5eb8 | | | 774 | |
| 90d5eb8 | | | 775 | // Verify repo exists |
| 90d5eb8 | | | 776 | const repoRow = db |
| 90d5eb8 | | | 777 | .prepare(`SELECT * FROM repos_with_owner WHERE owner_name = ? AND name = ?`) |
| 90d5eb8 | | | 778 | .get(owner, repoName) as any; |
| 90d5eb8 | | | 779 | if (!repoRow) { |
| 90d5eb8 | | | 780 | return reply.code(404).send({ error: "Repository not found" }); |
| 90d5eb8 | | | 781 | } |
| 90d5eb8 | | | 782 | |
| 90d5eb8 | | | 783 | // Read the uploaded file |
| 90d5eb8 | | | 784 | const file = await (request as any).file(); |
| 90d5eb8 | | | 785 | if (!file) { |
| 90d5eb8 | | | 786 | return reply.code(400).send({ error: "No file uploaded" }); |
| 90d5eb8 | | | 787 | } |
| 90d5eb8 | | | 788 | |
| 90d5eb8 | | | 789 | // SSE stream |
| 90d5eb8 | | | 790 | reply.raw.writeHead(200, { |
| 90d5eb8 | | | 791 | "Content-Type": "text/event-stream", |
| 90d5eb8 | | | 792 | "Cache-Control": "no-cache", |
| 90d5eb8 | | | 793 | Connection: "keep-alive", |
| 90d5eb8 | | | 794 | }); |
| 90d5eb8 | | | 795 | |
| 90d5eb8 | | | 796 | const send = (event: string, data: any) => { |
| 90d5eb8 | | | 797 | reply.raw.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); |
| 90d5eb8 | | | 798 | }; |
| 90d5eb8 | | | 799 | |
| 90d5eb8 | | | 800 | const bareRepo = `${DATA_DIR}/${repoName}-bare.git`; |
| 90d5eb8 | | | 801 | const tarPath = `${DATA_DIR}/${repoName}-bare.tar.gz`; |
| 90d5eb8 | | | 802 | |
| 90d5eb8 | | | 803 | try { |
| 90d5eb8 | | | 804 | // Step 1: Save uploaded tarball and extract |
| 90d5eb8 | | | 805 | send("progress", { step: "upload", message: "Receiving bare repo..." }); |
| 90d5eb8 | | | 806 | |
| 90d5eb8 | | | 807 | await pipeline(file.file, createWriteStream(tarPath)); |
| 90d5eb8 | | | 808 | |
| 90d5eb8 | | | 809 | send("progress", { step: "upload", message: "Extracting..." }); |
| 90d5eb8 | | | 810 | |
| 90d5eb8 | | | 811 | await rm(bareRepo, { recursive: true, force: true }); |
| 90d5eb8 | | | 812 | |
| 90d5eb8 | | | 813 | await runDocker([ |
| 90d5eb8 | | | 814 | "run", "--rm", |
| 90d5eb8 | | | 815 | "-v", "/data/grove:/data/grove", |
| ea47cea | | | 816 | "--entrypoint", "tar", |
| 90d5eb8 | | | 817 | "grove/mononoke:latest", |
| ea47cea | | | 818 | "xzf", tarPath, "-C", `${DATA_DIR}`, |
| 90d5eb8 | | | 819 | ], (line) => { |
| 90d5eb8 | | | 820 | send("log", { step: "upload", line }); |
| 90d5eb8 | | | 821 | }); |
| 90d5eb8 | | | 822 | |
| 90d5eb8 | | | 823 | // The tar extracts as bare.git/ — rename to match expected path |
| ea47cea | | | 824 | await runDocker([ |
| ea47cea | | | 825 | "run", "--rm", |
| ea47cea | | | 826 | "-v", "/data/grove:/data/grove", |
| 416062b | | | 827 | "--entrypoint", "sh", |
| ea47cea | | | 828 | "grove/mononoke:latest", |
| 416062b | | | 829 | "-c", `mv ${DATA_DIR}/bare.git ${bareRepo} 2>/dev/null; chown -R root:root ${bareRepo}`, |
| 416062b | | | 830 | ], () => {}); |
| 90d5eb8 | | | 831 | |
| 90d5eb8 | | | 832 | send("progress", { step: "upload", message: "Extracted." }); |
| 90d5eb8 | | | 833 | |
| 90d5eb8 | | | 834 | // Step 2: gitimport into Mononoke |
| 90d5eb8 | | | 835 | send("progress", { step: "import", message: "Importing into Mononoke..." }); |
| 90d5eb8 | | | 836 | |
| 90d5eb8 | | | 837 | await runDocker([ |
| 90d5eb8 | | | 838 | "run", "--rm", |
| 90d5eb8 | | | 839 | "-v", "/data/grove:/data/grove", |
| 416062b | | | 840 | "--entrypoint", "gitimport", |
| 90d5eb8 | | | 841 | "grove/mononoke:latest", |
| 416062b | | | 842 | "--repo-name", repoName, |
| 416062b | | | 843 | "--config-path", MONONOKE_CONFIG_PATH, |
| 416062b | | | 844 | "--local-configerator-path", `${DATA_DIR}/configerator`, |
| 416062b | | | 845 | "--cache-mode", "disabled", |
| 416062b | | | 846 | "--just-knobs-config-path", `${DATA_DIR}/justknobs.json`, |
| 416062b | | | 847 | "--generate-bookmarks", |
| 416062b | | | 848 | "--derive-hg", |
| 416062b | | | 849 | "--git-command-path", "/usr/bin/git", |
| 416062b | | | 850 | "--concurrency", "5", |
| 416062b | | | 851 | bareRepo, |
| 416062b | | | 852 | "full-repo", |
| 90d5eb8 | | | 853 | ], (line) => { |
| 90d5eb8 | | | 854 | send("log", { step: "import", line }); |
| 90d5eb8 | | | 855 | }); |
| 90d5eb8 | | | 856 | |
| 6d52207 | | | 857 | // Create Sapling-style bookmark (gitimport creates "heads/main", Sapling needs "main") |
| 6d52207 | | | 858 | send("progress", { step: "import", message: "Creating bookmarks..." }); |
| 6d52207 | | | 859 | |
| 6d52207 | | | 860 | await runDocker([ |
| 6d52207 | | | 861 | "run", "--rm", |
| 6d52207 | | | 862 | "-v", "/data/grove:/data/grove", |
| 6d52207 | | | 863 | "--entrypoint", "sh", |
| 6d52207 | | | 864 | "grove/mononoke:latest", |
| 6d52207 | | | 865 | "-c", |
| 6d52207 | | | 866 | `CSID=$(admin --config-path ${MONONOKE_CONFIG_PATH} --local-configerator-path ${DATA_DIR}/configerator --cache-mode disabled --just-knobs-config-path ${DATA_DIR}/justknobs.json bookmarks --repo-name ${repoName} list 2>/dev/null | grep 'heads/main' | awk '{print $1}') && admin --config-path ${MONONOKE_CONFIG_PATH} --local-configerator-path ${DATA_DIR}/configerator --cache-mode disabled --just-knobs-config-path ${DATA_DIR}/justknobs.json bookmarks --repo-name ${repoName} set main $CSID`, |
| 6d52207 | | | 867 | ], (line) => { |
| 6d52207 | | | 868 | send("log", { step: "import", line }); |
| 6d52207 | | | 869 | }); |
| 6d52207 | | | 870 | |
| 90d5eb8 | | | 871 | send("progress", { step: "import", message: "Import complete." }); |
| 90d5eb8 | | | 872 | |
| 90d5eb8 | | | 873 | // Step 3: Restart Mononoke services |
| 90d5eb8 | | | 874 | send("progress", { step: "restart", message: "Restarting services..." }); |
| 90d5eb8 | | | 875 | |
| 90d5eb8 | | | 876 | const provisioner = (app as any).mononokeProvisioner as MononokeProvisioner; |
| 90d5eb8 | | | 877 | await provisioner.restartMononoke(); |
| 90d5eb8 | | | 878 | |
| 90d5eb8 | | | 879 | send("progress", { step: "restart", message: "Services restarted." }); |
| 90d5eb8 | | | 880 | |
| 90d5eb8 | | | 881 | // Clean up |
| 90d5eb8 | | | 882 | await runDocker([ |
| 90d5eb8 | | | 883 | "run", "--rm", |
| 90d5eb8 | | | 884 | "-v", "/data/grove:/data/grove", |
| ea47cea | | | 885 | "--entrypoint", "rm", |
| 90d5eb8 | | | 886 | "grove/mononoke:latest", |
| ea47cea | | | 887 | "-rf", bareRepo, tarPath, |
| 90d5eb8 | | | 888 | ], () => {}); |
| 90d5eb8 | | | 889 | |
| 90d5eb8 | | | 890 | send("done", { success: true }); |
| 90d5eb8 | | | 891 | } catch (err: any) { |
| 90d5eb8 | | | 892 | // Clean up on error |
| 90d5eb8 | | | 893 | await runDocker([ |
| 90d5eb8 | | | 894 | "run", "--rm", |
| 90d5eb8 | | | 895 | "-v", "/data/grove:/data/grove", |
| ea47cea | | | 896 | "--entrypoint", "rm", |
| 90d5eb8 | | | 897 | "grove/mononoke:latest", |
| ea47cea | | | 898 | "-rf", bareRepo, tarPath, |
| 90d5eb8 | | | 899 | ], () => {}).catch(() => {}); |
| 90d5eb8 | | | 900 | |
| 90d5eb8 | | | 901 | send("error", { message: err.message ?? "Import failed" }); |
| 90d5eb8 | | | 902 | } |
| 90d5eb8 | | | 903 | |
| 90d5eb8 | | | 904 | reply.raw.end(); |
| 90d5eb8 | | | 905 | } |
| 90d5eb8 | | | 906 | ); |
| 59a80f9 | | | 907 | } |
| 59a80f9 | | | 908 | |
| 59a80f9 | | | 909 | /** |
| 59a80f9 | | | 910 | * Run a docker command, streaming stdout/stderr line-by-line to a callback. |
| 59a80f9 | | | 911 | * Rejects on non-zero exit code. |
| 59a80f9 | | | 912 | */ |
| 59a80f9 | | | 913 | function runDocker( |
| 59a80f9 | | | 914 | args: string[], |
| 59a80f9 | | | 915 | onLine: (line: string) => void |
| 59a80f9 | | | 916 | ): Promise<void> { |
| 59a80f9 | | | 917 | return new Promise((resolve, reject) => { |
| 59a80f9 | | | 918 | const proc = spawn("docker", args); |
| 59a80f9 | | | 919 | let stderr = ""; |
| 59a80f9 | | | 920 | |
| 59a80f9 | | | 921 | const handleData = (data: Buffer) => { |
| 59a80f9 | | | 922 | const text = data.toString(); |
| 59a80f9 | | | 923 | for (const line of text.split("\n")) { |
| 59a80f9 | | | 924 | const trimmed = line.trimEnd(); |
| 59a80f9 | | | 925 | if (trimmed) onLine(trimmed); |
| 59a80f9 | | | 926 | } |
| 59a80f9 | | | 927 | }; |
| 59a80f9 | | | 928 | |
| 59a80f9 | | | 929 | proc.stdout.on("data", handleData); |
| 59a80f9 | | | 930 | proc.stderr.on("data", (data: Buffer) => { |
| 59a80f9 | | | 931 | stderr += data.toString(); |
| 59a80f9 | | | 932 | handleData(data); |
| 59a80f9 | | | 933 | }); |
| 59a80f9 | | | 934 | |
| 59a80f9 | | | 935 | proc.on("close", (code) => { |
| 59a80f9 | | | 936 | if (code === 0) resolve(); |
| 59a80f9 | | | 937 | else reject(new Error(stderr.trim() || `docker exited with code ${code}`)); |
| 59a80f9 | | | 938 | }); |
| 59a80f9 | | | 939 | |
| 59a80f9 | | | 940 | proc.on("error", reject); |
| 59a80f9 | | | 941 | }); |
| 3e3af55 | | | 942 | } |