|
1 | 1 | import { Hono } from 'hono' |
2 | 2 | import type { Database } from 'bun:sqlite' |
3 | 3 | import { spawn } from 'child_process' |
4 | | -import { createWriteStream } from 'fs' |
| 4 | +import { copyFileSync, createReadStream, createWriteStream, existsSync } from 'fs' |
5 | 5 | import { mkdirSync, mkdtempSync, writeFileSync } from 'fs' |
6 | 6 | import { Readable } from 'stream' |
7 | 7 | import { pipeline } from 'stream/promises' |
@@ -42,8 +42,94 @@ interface CommitBody { |
42 | 42 | gzip?: boolean |
43 | 43 | } |
44 | 44 |
|
| 45 | +interface PatchBody { |
| 46 | + baseHead?: string | null |
| 47 | + patch?: string |
| 48 | + force?: boolean |
| 49 | +} |
| 50 | + |
45 | 51 | const LEGACY_UPGRADE_MESSAGE = 'this ocm CLI is too old for this server; upgrade to ocm-cli >= 0.1.2 (the mirror upload protocol changed to chunked uploads)' |
46 | 52 |
|
| 53 | +function gitRaw(repoPath: string, args: string[], env: NodeJS.ProcessEnv = process.env, input?: string): Promise<string> { |
| 54 | + return new Promise((resolve, reject) => { |
| 55 | + const child = spawn('git', args, { cwd: repoPath, env }) |
| 56 | + let stdout = '' |
| 57 | + let stderr = '' |
| 58 | + child.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString() }) |
| 59 | + child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() }) |
| 60 | + child.on('error', reject) |
| 61 | + child.on('close', (code) => { |
| 62 | + if (code === 0) resolve(stdout) |
| 63 | + else reject(new Error(stderr.trim() || `git exited with code ${code}`)) |
| 64 | + }) |
| 65 | + if (input !== undefined) child.stdin.end(input) |
| 66 | + }) |
| 67 | +} |
| 68 | + |
| 69 | +async function createMirrorPatch(fullPath: string): Promise<string> { |
| 70 | + const untracked = (await gitRaw(fullPath, ['ls-files', '--others', '--exclude-standard', '-z']).catch(() => '')) |
| 71 | + .split('\0') |
| 72 | + .filter(Boolean) |
| 73 | + if (untracked.length === 0) return gitRaw(fullPath, ['diff', '--binary', 'HEAD', '--']) |
| 74 | + |
| 75 | + const indexPath = (await safeGitOut(fullPath, ['rev-parse', '--git-path', 'index']))?.trim() |
| 76 | + const tempIndexDir = mkdtempSync(join(getReposPath(), '.ocm-index-')) |
| 77 | + const tempIndex = join(tempIndexDir, 'index') |
| 78 | + const env = { ...process.env, GIT_INDEX_FILE: tempIndex } |
| 79 | + |
| 80 | + try { |
| 81 | + if (indexPath && existsSync(join(fullPath, indexPath))) { |
| 82 | + copyFileSync(join(fullPath, indexPath), tempIndex) |
| 83 | + } |
| 84 | + await gitRaw(fullPath, ['add', '-N', '--', ...untracked], env) |
| 85 | + return gitRaw(fullPath, ['diff', '--binary', 'HEAD', '--'], env) |
| 86 | + } finally { |
| 87 | + await fsp.rm(tempIndexDir, { recursive: true, force: true }).catch(() => {}) |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +async function applyMirrorPatch(fullPath: string, patch: string): Promise<void> { |
| 92 | + if (!patch) return |
| 93 | + await gitRaw(fullPath, ['apply', '--binary', '--whitespace=nowarn', '-'], process.env, patch) |
| 94 | +} |
| 95 | + |
| 96 | +async function importBundle(fullPath: string, bundlePath: string, branch: string | null): Promise<void> { |
| 97 | + await gitRaw(fullPath, ['fetch', bundlePath, '+refs/heads/*:refs/remotes/ocm-sync/*', '+refs/tags/*:refs/tags/*']) |
| 98 | + const refs = await gitRaw(fullPath, ['for-each-ref', '--format=%(refname:strip=3) %(objectname)', 'refs/remotes/ocm-sync']) |
| 99 | + for (const line of refs.split('\n')) { |
| 100 | + const trimmed = line.trim() |
| 101 | + if (!trimmed) continue |
| 102 | + const firstSpace = trimmed.indexOf(' ') |
| 103 | + if (firstSpace === -1) continue |
| 104 | + const name = trimmed.slice(0, firstSpace) |
| 105 | + const sha = trimmed.slice(firstSpace + 1) |
| 106 | + await gitRaw(fullPath, ['update-ref', `refs/heads/${name}`, sha]) |
| 107 | + } |
| 108 | + |
| 109 | + if (branch) { |
| 110 | + await gitRaw(fullPath, ['checkout', branch]) |
| 111 | + const head = (await gitRaw(fullPath, ['rev-parse', `refs/remotes/ocm-sync/${branch}`])).trim() |
| 112 | + if (head) await gitRaw(fullPath, ['reset', '--hard', head]) |
| 113 | + } |
| 114 | + |
| 115 | + await gitRaw(fullPath, ['for-each-ref', '--format=%(refname)', 'refs/remotes/ocm-sync']) |
| 116 | + .then(async (out) => { |
| 117 | + for (const ref of out.split('\n').map((line) => line.trim()).filter(Boolean)) { |
| 118 | + await gitRaw(fullPath, ['update-ref', '-d', ref]) |
| 119 | + } |
| 120 | + }) |
| 121 | + .catch(() => {}) |
| 122 | +} |
| 123 | + |
| 124 | +async function createBundle(fullPath: string): Promise<string> { |
| 125 | + const stagingRoot = join(getReposPath(), '.ocm-staging') |
| 126 | + mkdirSync(stagingRoot, { recursive: true }) |
| 127 | + const bundleDir = mkdtempSync(join(stagingRoot, 'bundle-')) |
| 128 | + const bundlePath = join(bundleDir, 'repo.bundle') |
| 129 | + await gitRaw(fullPath, ['bundle', 'create', bundlePath, '--all']) |
| 130 | + return bundlePath |
| 131 | +} |
| 132 | + |
47 | 133 | export function createInternalRepoMirrorRoutes(db: Database) { |
48 | 134 | const app = new Hono() |
49 | 135 |
|
@@ -214,6 +300,146 @@ export function createInternalRepoMirrorRoutes(db: Database) { |
214 | 300 | return c.json({ ok: true }) |
215 | 301 | }) |
216 | 302 |
|
| 303 | + app.get('/:repoId/mirror/bundle', async (c) => { |
| 304 | + const repoIdRaw = c.req.param('repoId') |
| 305 | + const repoId = Number(repoIdRaw) |
| 306 | + if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400) |
| 307 | + const repo = getRepoById(db, repoId) |
| 308 | + if (!repo) return c.json({ error: 'repo not found' }, 404) |
| 309 | + |
| 310 | + let bundlePath: string | undefined |
| 311 | + try { |
| 312 | + bundlePath = await createBundle(repo.fullPath) |
| 313 | + const stream = createReadStream(bundlePath) |
| 314 | + stream.on('close', () => { |
| 315 | + if (bundlePath) fsp.rm(join(bundlePath, '..'), { recursive: true, force: true }).catch(() => {}) |
| 316 | + }) |
| 317 | + return new Response(Readable.toWeb(stream) as ReadableStream, { |
| 318 | + headers: { 'Content-Type': 'application/octet-stream' }, |
| 319 | + }) |
| 320 | + } catch (error) { |
| 321 | + logger.error('mirror bundle download failed:', error) |
| 322 | + if (bundlePath) await fsp.rm(join(bundlePath, '..'), { recursive: true, force: true }).catch(() => {}) |
| 323 | + return c.json({ error: getErrorMessage(error) }, 500) |
| 324 | + } |
| 325 | + }) |
| 326 | + |
| 327 | + app.post('/:repoId/mirror/bundle', async (c) => { |
| 328 | + const repoIdRaw = c.req.param('repoId') |
| 329 | + const repoId = Number(repoIdRaw) |
| 330 | + if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400) |
| 331 | + const repo = getRepoById(db, repoId) |
| 332 | + if (!repo) return c.json({ error: 'repo not found' }, 404) |
| 333 | + if (isRepoInUse(db, repoId) && c.req.query('force') !== '1') { |
| 334 | + return c.json({ error: 'repo_in_use', message: 'open OpenCode sessions are using this repo; rerun with force=1' }, 409) |
| 335 | + } |
| 336 | + |
| 337 | + const rawBody = c.req.raw.body |
| 338 | + if (!rawBody) return c.json({ error: 'no body provided' }, 400) |
| 339 | + |
| 340 | + const stagingRoot = join(getReposPath(), '.ocm-staging') |
| 341 | + mkdirSync(stagingRoot, { recursive: true }) |
| 342 | + const bundleDir = mkdtempSync(join(stagingRoot, 'bundle-upload-')) |
| 343 | + const bundlePath = join(bundleDir, 'repo.bundle') |
| 344 | + const branch = c.req.header('x-ocm-branch')?.trim() || null |
| 345 | + |
| 346 | + try { |
| 347 | + const body = Readable.fromWeb(rawBody as unknown as Parameters<typeof Readable.fromWeb>[0]) |
| 348 | + await pipeline(body, createWriteStream(bundlePath)) |
| 349 | + await importBundle(repo.fullPath, bundlePath, branch) |
| 350 | + |
| 351 | + const branchName = await safeGitOut(repo.fullPath, ['rev-parse', '--abbrev-ref', 'HEAD']) |
| 352 | + const head = await safeGitOut(repo.fullPath, ['rev-parse', 'HEAD']) |
| 353 | + if (branchName) updateRepoBranch(db, repoId, branchName.trim()) |
| 354 | + updateLastPulled(db, repoId) |
| 355 | + |
| 356 | + return c.json({ |
| 357 | + repoId, |
| 358 | + fullPath: repo.fullPath, |
| 359 | + branch: branchName?.trim() || null, |
| 360 | + head: head?.trim() || null, |
| 361 | + created: false, |
| 362 | + }) |
| 363 | + } catch (error) { |
| 364 | + logger.error('mirror bundle upload failed:', error) |
| 365 | + return c.json({ error: getErrorMessage(error) }, 409) |
| 366 | + } finally { |
| 367 | + await fsp.rm(bundleDir, { recursive: true, force: true }).catch(() => {}) |
| 368 | + } |
| 369 | + }) |
| 370 | + |
| 371 | + app.get('/:repoId/mirror/patch', async (c) => { |
| 372 | + const repoIdRaw = c.req.param('repoId') |
| 373 | + const repoId = Number(repoIdRaw) |
| 374 | + if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400) |
| 375 | + const repo = getRepoById(db, repoId) |
| 376 | + if (!repo) return c.json({ error: 'repo not found' }, 404) |
| 377 | + |
| 378 | + try { |
| 379 | + const branchName = await safeGitOut(repo.fullPath, ['rev-parse', '--abbrev-ref', 'HEAD']) |
| 380 | + const head = await safeGitOut(repo.fullPath, ['rev-parse', 'HEAD']) |
| 381 | + const patch = await createMirrorPatch(repo.fullPath) |
| 382 | + return c.json({ |
| 383 | + repoId: repo.id, |
| 384 | + branch: branchName?.trim() || null, |
| 385 | + head: head?.trim() || null, |
| 386 | + patch, |
| 387 | + }) |
| 388 | + } catch (error) { |
| 389 | + logger.error('mirror patch snapshot failed:', error) |
| 390 | + return c.json({ error: getErrorMessage(error) }, 500) |
| 391 | + } |
| 392 | + }) |
| 393 | + |
| 394 | + app.post('/:repoId/mirror/patch', async (c) => { |
| 395 | + const repoIdRaw = c.req.param('repoId') |
| 396 | + const repoId = Number(repoIdRaw) |
| 397 | + if (!Number.isFinite(repoId)) return c.json({ error: 'invalid repoId' }, 400) |
| 398 | + |
| 399 | + let body: PatchBody |
| 400 | + try { |
| 401 | + body = (await c.req.json()) as PatchBody |
| 402 | + } catch { |
| 403 | + return c.json({ error: 'invalid json body' }, 400) |
| 404 | + } |
| 405 | + |
| 406 | + const repo = getRepoById(db, repoId) |
| 407 | + if (!repo) return c.json({ error: 'repo not found' }, 404) |
| 408 | + if (!body.patch && body.patch !== '') return c.json({ error: 'patch required' }, 400) |
| 409 | + if (body.force !== true && isRepoInUse(db, repoId)) { |
| 410 | + return c.json({ error: 'repo_in_use', message: 'open OpenCode sessions are using this repo; rerun with force=1' }, 409) |
| 411 | + } |
| 412 | + |
| 413 | + try { |
| 414 | + const currentHead = await safeGitOut(repo.fullPath, ['rev-parse', 'HEAD']) |
| 415 | + const currentHeadTrimmed = currentHead?.trim() || null |
| 416 | + const baseHead = body.baseHead?.trim() || null |
| 417 | + if (baseHead && currentHeadTrimmed && baseHead !== currentHeadTrimmed) { |
| 418 | + return c.json({ error: 'head_mismatch', message: 'Manager repo HEAD differs from patch base' }, 409) |
| 419 | + } |
| 420 | + |
| 421 | + await applyMirrorPatch(repo.fullPath, body.patch) |
| 422 | + |
| 423 | + const branchName = await safeGitOut(repo.fullPath, ['rev-parse', '--abbrev-ref', 'HEAD']) |
| 424 | + const head = await safeGitOut(repo.fullPath, ['rev-parse', 'HEAD']) |
| 425 | + |
| 426 | + if (branchName) updateRepoBranch(db, repoId, branchName.trim()) |
| 427 | + updateLastPulled(db, repoId) |
| 428 | + |
| 429 | + return c.json({ |
| 430 | + repoId, |
| 431 | + fullPath: repo.fullPath, |
| 432 | + branch: branchName?.trim() || null, |
| 433 | + head: head?.trim() || null, |
| 434 | + created: false, |
| 435 | + applied: true, |
| 436 | + }) |
| 437 | + } catch (error) { |
| 438 | + logger.error('mirror patch failed:', error) |
| 439 | + return c.json({ error: getErrorMessage(error) }, 409) |
| 440 | + } |
| 441 | + }) |
| 442 | + |
217 | 443 | app.get('/:repoId/mirror', async (c) => { |
218 | 444 | const repoIdRaw = c.req.param('repoId') |
219 | 445 | const repoId = Number(repoIdRaw) |
|
0 commit comments