fix(ocm-cli): chunked mirror upload and macOS metadata exclusion (#238)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-05-25 13:32:31 -04:00
1 parent 0597bf6a37
commit 04ab63932b
8 files changed
+801 -344

No files matched your search

+2
View File
@@ -35,6 +35,7 @@ import { createAuth } from './auth'
import { createAuthMiddleware } from './auth/middleware'
import { createPromptTemplateRoutes } from './routes/prompt-templates'
import { createInternalRoutes } from './routes/internal'
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
import { sseAggregator } from './services/sse-aggregator'
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
@@ -245,6 +246,7 @@ try {
logger.info('Workspace directories initialized')
await cleanupExpiredCache()
await sweepStaleUploadSessions()
await ensureDefaultConfigExists()
await backfillOpenCodeModelStateFromFile()
@@ -0,0 +1,178 @@
import { spawn } from 'child_process'
import { existsSync, mkdirSync, mkdtempSync, readdirSync, statSync } from 'fs'
import * as fsp from 'fs/promises'
import { createReadStream } from 'fs'
import { dirname, join } from 'path'
import { pipeline } from 'stream/promises'
import { randomUUID } from 'crypto'
import { getReposPath } from '@opencode-manager/shared/config/env'
export const MIRROR_CHUNK_SIZE = 8 * 1024 * 1024
const STALE_UPLOAD_MS = 24 * 60 * 60 * 1000
export interface UploadMeta {
uploadId: string
repoId: number
fullPath: string
created: boolean
createdRepoId?: number
force: boolean
startedAt: number
}
export function getStagingRoot(): string {
return join(getReposPath(), '.ocm-staging')
}
export function getUploadsRoot(): string {
return join(getStagingRoot(), 'uploads')
}
export function getUploadDir(uploadId: string): string {
return join(getUploadsRoot(), uploadId)
}
export function getPartsDir(uploadId: string): string {
return join(getUploadDir(uploadId), 'parts')
}
export function getMetaPath(uploadId: string): string {
return join(getUploadDir(uploadId), 'meta.json')
}
export function getPartPath(uploadId: string, index: number): string {
return join(getPartsDir(uploadId), `${index}.bin`)
}
export async function createUploadSession(meta: Omit<UploadMeta, 'uploadId' | 'startedAt'>): Promise<UploadMeta> {
const uploadId = randomUUID()
mkdirSync(getPartsDir(uploadId), { recursive: true })
const full: UploadMeta = { ...meta, uploadId, startedAt: Date.now() }
await fsp.writeFile(getMetaPath(uploadId), JSON.stringify(full), 'utf-8')
return full
}
export async function readUploadMeta(uploadId: string): Promise<UploadMeta | null> {
try {
const raw = await fsp.readFile(getMetaPath(uploadId), 'utf-8')
return JSON.parse(raw) as UploadMeta
} catch {
return null
}
}
export async function deleteUploadSession(uploadId: string): Promise<void> {
await fsp.rm(getUploadDir(uploadId), { recursive: true, force: true }).catch(() => {})
}
export async function sweepStaleUploadSessions(now = Date.now(), ttlMs = STALE_UPLOAD_MS): Promise<void> {
const root = getUploadsRoot()
if (!existsSync(root)) return
let entries: string[]
try {
entries = readdirSync(root)
} catch {
return
}
for (const id of entries) {
const meta = await readUploadMeta(id)
if (!meta || now - meta.startedAt > ttlMs) {
await deleteUploadSession(id)
}
}
}
export interface ExtractResult {
extractedRoot: string
staging: string
}
export async function extractPartsToStaging(uploadId: string, totalParts: number, gzip: boolean): Promise<ExtractResult> {
const stagingParent = getStagingRoot()
mkdirSync(stagingParent, { recursive: true })
const staging = mkdtempSync(join(stagingParent, 'recv-'))
const tarArgs = ['-x', '-f', '-', '-C', staging]
if (gzip) tarArgs.unshift('-z')
const child = spawn('tar', tarArgs, { stdio: ['pipe', 'pipe', 'pipe'] })
const stderrChunks: Buffer[] = []
child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk))
const tarDone = new Promise<void>((resolve, reject) => {
child.on('close', (code) => {
if (code === 0) resolve()
else {
const stderr = Buffer.concat(stderrChunks).toString('utf-8').trim()
reject(new Error(`tar exited with code ${code}${stderr ? `: ${stderr}` : ''}`))
}
})
child.on('error', reject)
})
try {
for (let i = 0; i < totalParts; i++) {
const partPath = getPartPath(uploadId, i)
if (!existsSync(partPath)) {
throw new Error(`missing part ${i} for upload ${uploadId}`)
}
await pipeline(createReadStream(partPath), child.stdin, { end: i === totalParts - 1 })
}
await tarDone
} catch (err) {
if (!child.killed) child.kill('SIGKILL')
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
throw err
}
let extractedRoot = staging
const entries = readdirSync(staging)
if (entries.length === 1) {
const candidate = join(staging, entries[0]!)
try {
if (statSync(candidate).isDirectory()) {
extractedRoot = candidate
}
} catch { /* ignore */ }
}
return { extractedRoot, staging }
}
export interface SwapResult {
backupDir?: string
}
export async function atomicSwapIntoPlace(extractedRoot: string, fullPath: string): Promise<SwapResult> {
await fsp.mkdir(dirname(fullPath), { recursive: true })
let backupDir: string | undefined
if (existsSync(fullPath)) {
backupDir = `${fullPath}.ocm-old-${Date.now()}-${Math.random().toString(36).slice(2)}`
await fsp.rename(fullPath, backupDir)
}
try {
await fsp.rename(extractedRoot, fullPath)
} catch (err) {
if (backupDir) {
await fsp.rename(backupDir, fullPath).catch(() => {})
}
throw err
}
return { backupDir }
}
export async function discardBackup(backupDir: string | undefined): Promise<void> {
if (!backupDir) return
await fsp.rm(backupDir, { recursive: true, force: true }).catch(() => {})
}
export async function restoreBackup(fullPath: string, backupDir: string | undefined): Promise<void> {
if (!backupDir) return
if (existsSync(fullPath)) {
await fsp.rm(fullPath, { recursive: true, force: true }).catch(() => {})
}
await fsp.rename(backupDir, fullPath).catch(() => {})
}
+160 -108
View File
@@ -1,10 +1,11 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { spawn } from 'child_process'
import { pipeline } from 'stream/promises'
import { createWriteStream } from 'fs'
import { mkdirSync, mkdtempSync, writeFileSync } from 'fs'
import { Readable } from 'stream'
import { mkdtempSync, mkdirSync, readdirSync, statSync, existsSync, writeFileSync } from 'fs'
import { dirname, join } from 'path'
import { pipeline } from 'stream/promises'
import { join } from 'path'
import * as fsp from 'fs/promises'
import { getReposPath } from '@opencode-manager/shared/config/env'
import { getRepoById, updateLastPulled, updateRepoBranch, deleteRepo } from '../../db/queries'
@@ -12,22 +13,54 @@ import { ensureMirrorTargetPath, createRepoRow, isRepoInUse } from '../../servic
import { logger } from '../../utils/logger'
import { getErrorMessage } from '../../utils/error-utils'
import { safeGitOut, gitOut } from './repo-sync-helpers'
import {
MIRROR_CHUNK_SIZE,
createUploadSession,
readUploadMeta,
deleteUploadSession,
getPartPath,
extractPartsToStaging,
atomicSwapIntoPlace,
discardBackup,
restoreBackup,
} from './repo-mirror-helpers'
const HARDCODED_EXCLUDES = ['node_modules', 'dist', '.next', '.venv', '__pycache__', '.turbo']
interface BeginBody {
create?: boolean
name?: string
originUrl?: string
branch?: string
force?: boolean
}
interface CommitBody {
uploadId: string
totalParts: number
gzip?: boolean
}
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)'
export function createInternalRepoMirrorRoutes(db: Database) {
const app = new Hono()
app.post('/:repoId/mirror', async (c) => {
const repoIdRaw = c.req.param('repoId')
const force = c.req.query('force') === '1'
const create = c.req.query('create') === '1'
const name = c.req.query('name')
const originUrl = c.req.query('originUrl')
const branch = c.req.query('branch')
app.post('/:repoId/mirror', (c) => {
return c.json({ error: 'cli_too_old', message: LEGACY_UPGRADE_MESSAGE }, 410)
})
const rawBody = c.req.raw.body
if (!rawBody) return c.json({ error: 'no body provided' }, 400)
app.post('/:repoId/mirror/begin', async (c) => {
const repoIdRaw = c.req.param('repoId')
let body: BeginBody
try {
body = (await c.req.json()) as BeginBody
} catch {
return c.json({ error: 'invalid json body' }, 400)
}
const force = body.force === true
const create = body.create === true
let repoId: number
let fullPath: string
@@ -35,9 +68,15 @@ export function createInternalRepoMirrorRoutes(db: Database) {
let createdRepoId: number | undefined
if (repoIdRaw === '0' && create) {
if (!name) return c.json({ error: 'name required', message: 'provide a name query param' }, 400)
const target = ensureMirrorTargetPath(name)
const { repo: newRepo, created: wasCreated } = createRepoRow(db, { name, originUrl, localPath: target.localPath, fullPath: target.fullPath, branch })
if (!body.name) return c.json({ error: 'name required', message: 'provide name in body' }, 400)
const target = ensureMirrorTargetPath(body.name)
const { repo: newRepo, created: wasCreated } = createRepoRow(db, {
name: body.name,
originUrl: body.originUrl,
localPath: target.localPath,
fullPath: target.fullPath,
branch: body.branch,
})
repoId = newRepo.id
fullPath = newRepo.fullPath
created = wasCreated
@@ -59,107 +98,120 @@ export function createInternalRepoMirrorRoutes(db: Database) {
}
}
let staging: string | undefined
let backupDir: string | undefined
try {
const stagingParent = join(getReposPath(), '.ocm-staging')
mkdirSync(stagingParent, { recursive: true })
staging = mkdtempSync(join(stagingParent, 'recv-'))
const isGzip = c.req.header('Content-Encoding') === 'gzip'
const tarArgs = ['-x', '-f', '-', '-C', staging]
if (isGzip) tarArgs.unshift('-z')
const child = spawn('tar', tarArgs, { stdio: ['pipe', 'pipe', 'pipe'] })
const stderrChunks: Buffer[] = []
child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk))
const tarDone = new Promise<void>((resolve, reject) => {
child.on('close', (code) => {
if (code === 0) resolve()
else {
const stderr = Buffer.concat(stderrChunks).toString('utf-8').trim()
reject(new Error(`tar exited with code ${code}${stderr ? `: ${stderr}` : ''}`))
}
})
child.on('error', reject)
})
const body = Readable.fromWeb(rawBody as unknown as Parameters<typeof Readable.fromWeb>[0])
await pipeline(body, child.stdin)
await tarDone
const entries = readdirSync(staging)
let extractedRoot = staging
if (entries.length === 1) {
const candidate = join(staging, entries[0]!)
try {
if (statSync(candidate).isDirectory()) {
extractedRoot = candidate
}
} catch { /* ignore stat errors */ }
}
await fsp.mkdir(dirname(fullPath), { recursive: true })
if (existsSync(fullPath)) {
backupDir = `${fullPath}.ocm-old-${Date.now()}-${Math.random().toString(36).slice(2)}`
await fsp.rename(fullPath, backupDir)
}
await fsp.rename(extractedRoot, fullPath)
if (backupDir) {
await fsp.rm(backupDir, { recursive: true, force: true }).catch(() => {})
backupDir = undefined
}
const branchName = await safeGitOut(fullPath, ['rev-parse', '--abbrev-ref', 'HEAD'])
const head = await safeGitOut(fullPath, ['rev-parse', 'HEAD'])
if (branchName) {
updateRepoBranch(db, repoId, branchName.trim())
}
updateLastPulled(db, repoId)
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
return c.json({
repoId,
fullPath,
branch: branchName?.trim() || null,
head: head?.trim() || null,
created,
})
const meta = await createUploadSession({ repoId, fullPath, created, createdRepoId, force })
return c.json({ uploadId: meta.uploadId, repoId, chunkSize: MIRROR_CHUNK_SIZE, created })
} catch (error) {
logger.error('mirror POST failed:', error)
if (backupDir) {
try {
if (existsSync(fullPath)) {
await fsp.rm(fullPath, { recursive: true, force: true })
}
await fsp.rename(backupDir, fullPath)
} catch {
logger.error('failed to restore old repo from backup')
}
}
logger.error('mirror begin failed:', error)
if (createdRepoId !== undefined) {
try {
deleteRepo(db, createdRepoId)
} catch {
logger.error('failed to delete created repo row on failure')
}
}
if (staging) {
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
try { deleteRepo(db, createdRepoId) } catch { /* ignore */ }
}
return c.json({ error: getErrorMessage(error) }, 500)
}
})
app.put('/:repoId/mirror/parts/:uploadId/:index', async (c) => {
const repoIdRaw = c.req.param('repoId')
const uploadId = c.req.param('uploadId')
const indexRaw = c.req.param('index')
const index = Number(indexRaw)
if (!Number.isFinite(index) || index < 0 || !Number.isInteger(index)) {
return c.json({ error: 'invalid index' }, 400)
}
const meta = await readUploadMeta(uploadId)
if (!meta) return c.json({ error: 'upload session not found' }, 404)
const repoIdNum = Number(repoIdRaw)
if (!Number.isFinite(repoIdNum) || repoIdNum !== meta.repoId) {
if (!(repoIdRaw === '0' && meta.created)) {
return c.json({ error: 'upload session does not belong to repo' }, 403)
}
}
const rawBody = c.req.raw.body
if (!rawBody) return c.json({ error: 'no body provided' }, 400)
const partPath = getPartPath(uploadId, index)
try {
const body = Readable.fromWeb(rawBody as unknown as Parameters<typeof Readable.fromWeb>[0])
await pipeline(body, createWriteStream(partPath))
const stat = await fsp.stat(partPath)
return c.json({ index, size: stat.size })
} catch (error) {
logger.error(`mirror part ${index} upload failed:`, error)
await fsp.rm(partPath, { force: true }).catch(() => {})
return c.json({ error: getErrorMessage(error) }, 500)
}
})
app.post('/:repoId/mirror/commit', async (c) => {
let body: CommitBody
try {
body = (await c.req.json()) as CommitBody
} catch {
return c.json({ error: 'invalid json body' }, 400)
}
const { uploadId, totalParts, gzip } = body
if (!uploadId) return c.json({ error: 'uploadId required' }, 400)
if (!Number.isInteger(totalParts) || totalParts < 0) return c.json({ error: 'totalParts must be a non-negative integer' }, 400)
const meta = await readUploadMeta(uploadId)
if (!meta) return c.json({ error: 'upload session not found' }, 404)
let backupDir: string | undefined
let staging: string | undefined
try {
const extracted = await extractPartsToStaging(uploadId, totalParts, gzip === true)
staging = extracted.staging
const swap = await atomicSwapIntoPlace(extracted.extractedRoot, meta.fullPath)
backupDir = swap.backupDir
const branchName = await safeGitOut(meta.fullPath, ['rev-parse', '--abbrev-ref', 'HEAD'])
const head = await safeGitOut(meta.fullPath, ['rev-parse', 'HEAD'])
if (branchName) updateRepoBranch(db, meta.repoId, branchName.trim())
updateLastPulled(db, meta.repoId)
await discardBackup(backupDir)
backupDir = undefined
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
staging = undefined
await deleteUploadSession(uploadId)
return c.json({
repoId: meta.repoId,
fullPath: meta.fullPath,
branch: branchName?.trim() || null,
head: head?.trim() || null,
created: meta.created,
})
} catch (error) {
logger.error('mirror commit failed:', error)
await restoreBackup(meta.fullPath, backupDir)
if (meta.createdRepoId !== undefined) {
try { deleteRepo(db, meta.createdRepoId) } catch { /* ignore */ }
}
if (staging) {
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
}
await deleteUploadSession(uploadId)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
app.delete('/:repoId/mirror/uploads/:uploadId', async (c) => {
const uploadId = c.req.param('uploadId')
const meta = await readUploadMeta(uploadId)
if (meta?.createdRepoId !== undefined) {
try { deleteRepo(db, meta.createdRepoId) } catch { /* ignore */ }
}
await deleteUploadSession(uploadId)
return c.json({ ok: true })
})
app.get('/:repoId/mirror', async (c) => {
const repoIdRaw = c.req.param('repoId')
const repoId = Number(repoIdRaw)
+191 -156
View File
@@ -4,7 +4,6 @@ import { spawnSync } from 'child_process'
import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'fs'
import { join } from 'path'
import { tmpdir } from 'os'
import { gzipSync } from 'zlib'
const { mockGetActiveDirectories, mockGitOut, mockSafeGitOut, getTmpRoot, setTmpRoot } = vi.hoisted(() => {
const mockGetActiveDirectories = vi.fn().mockReturnValue([])
@@ -65,6 +64,77 @@ vi.mock('../../../src/services/repo', () => ({
import { createInternalRepoMirrorRoutes } from '../../../src/routes/internal/repo-mirror'
const CHUNK_SIZE = 8 * 1024 * 1024
interface BeginResponse {
uploadId: string
repoId: number
chunkSize: number
created: boolean
}
interface CommitResponse {
repoId: number
fullPath: string
branch: string | null
head: string | null
created: boolean
}
async function begin(app: Hono, urlRepoId: number, body: Record<string, unknown>): Promise<Response> {
return app.request(`/api/internal/repos/${urlRepoId}/mirror/begin`, {
method: 'POST',
body: JSON.stringify(body),
headers: { 'content-type': 'application/json' },
})
}
async function putPart(app: Hono, urlRepoId: number, uploadId: string, index: number, chunk: Buffer): Promise<Response> {
return app.request(`/api/internal/repos/${urlRepoId}/mirror/parts/${uploadId}/${index}`, {
method: 'PUT',
body: chunk,
headers: { 'content-type': 'application/octet-stream' },
})
}
async function commit(app: Hono, urlRepoId: number, uploadId: string, totalParts: number, gzip = false): Promise<Response> {
return app.request(`/api/internal/repos/${urlRepoId}/mirror/commit`, {
method: 'POST',
body: JSON.stringify({ uploadId, totalParts, gzip }),
headers: { 'content-type': 'application/json' },
})
}
async function pushTarball(
app: Hono,
urlRepoId: number,
body: Record<string, unknown>,
tarball: Buffer,
): Promise<{ beginRes: Response; commitRes: Response | null }> {
const beginRes = await begin(app, urlRepoId, body)
if (beginRes.status !== 200) return { beginRes, commitRes: null }
const beginJson = (await beginRes.clone().json()) as BeginResponse
const { uploadId, repoId } = beginJson
let index = 0
for (let offset = 0; offset < tarball.length; offset += CHUNK_SIZE) {
const chunk = tarball.subarray(offset, Math.min(offset + CHUNK_SIZE, tarball.length))
const putRes = await putPart(app, repoId, uploadId, index, Buffer.from(chunk))
if (putRes.status !== 200) {
return { beginRes, commitRes: putRes }
}
index += 1
}
if (tarball.length === 0) {
const putRes = await putPart(app, repoId, uploadId, 0, Buffer.alloc(0))
if (putRes.status !== 200) {
return { beginRes, commitRes: putRes }
}
index = 1
}
const commitRes = await commit(app, repoId, uploadId, index)
return { beginRes, commitRes }
}
describe('internal-repo-mirror routes', () => {
let app: Hono
@@ -125,8 +195,22 @@ describe('internal-repo-mirror routes', () => {
})
})
describe('POST /:repoId/mirror', () => {
it('creates a repo with create=1 and populates from tarball', async () => {
describe('legacy POST /:repoId/mirror', () => {
it('returns 410 with cli_too_old code so old CLIs get a clear error', async () => {
const res = await app.request('/api/internal/repos/1/mirror', {
method: 'POST',
body: Buffer.from('legacy tarball'),
headers: { 'content-type': 'application/x-tar' },
})
expect(res.status).toBe(410)
const json = (await res.json()) as { error: string; message: string }
expect(json.error).toBe('cli_too_old')
expect(json.message).toMatch(/upgrade to ocm-cli/i)
})
})
describe('chunked upload flow (begin/parts/commit)', () => {
it('creates a repo and populates from chunked tarball', async () => {
const targetPath = join(getTmpRoot(), 'test-repo')
mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'test-repo', fullPath: targetPath })
mockCreateRepoRow.mockImplementation((_db: any, input: any) => ({ repo: { id: 1, fullPath: input.fullPath, localPath: input.localPath }, created: true }))
@@ -138,14 +222,11 @@ describe('internal-repo-mirror routes', () => {
const result = spawnSync('tar', ['-c', '-C', sourceDir, '.'], { encoding: 'buffer' })
const tarball = result.stdout as Buffer
const res = await app.request('/api/internal/repos/0/mirror?create=1&name=test-repo', {
method: 'POST',
body: tarball,
headers: { 'content-type': 'application/x-tar' },
})
const { beginRes, commitRes } = await pushTarball(app, 0, { create: true, name: 'test-repo' }, tarball)
expect(res.status).toBe(200)
const json = (await res.json()) as { created: boolean; repoId: number; fullPath: string }
expect(beginRes.status).toBe(200)
expect(commitRes?.status).toBe(200)
const json = (await commitRes!.json()) as CommitResponse
expect(json.created).toBe(true)
expect(json.repoId).toBe(1)
expect(json.fullPath).toBe(targetPath)
@@ -156,6 +237,41 @@ describe('internal-repo-mirror routes', () => {
expect(mockCreateRepoRow).toHaveBeenCalled()
})
it('splits a tarball across multiple PUTs of a fixed test chunk size', async () => {
const targetPath = join(getTmpRoot(), 'test-repo')
mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'test-repo', fullPath: targetPath })
mockCreateRepoRow.mockImplementation((_db: any, input: any) => ({ repo: { id: 1, fullPath: input.fullPath, localPath: input.localPath }, created: true }))
const sourceDir = join(getTmpRoot(), 'source-multi')
mkdirSync(sourceDir, { recursive: true })
writeFileSync(join(sourceDir, 'a.bin'), Buffer.alloc(64 * 1024, 0xab))
writeFileSync(join(sourceDir, 'b.bin'), Buffer.alloc(64 * 1024, 0xcd))
const tarFile = join(getTmpRoot(), 'multi.tar')
spawnSync('tar', ['-c', '-C', sourceDir, '-f', tarFile, '.'], { stdio: 'ignore' })
const tarball = readFileSync(tarFile)
const testChunkSize = 16 * 1024
expect(tarball.length).toBeGreaterThan(testChunkSize * 3)
const beginRes = await begin(app, 0, { create: true, name: 'test-repo' })
expect(beginRes.status).toBe(200)
const beginJson = (await beginRes.json()) as BeginResponse
let index = 0
for (let offset = 0; offset < tarball.length; offset += testChunkSize) {
const chunk = Buffer.from(tarball.subarray(offset, Math.min(offset + testChunkSize, tarball.length)))
const putRes = await putPart(app, beginJson.repoId, beginJson.uploadId, index, chunk)
expect(putRes.status).toBe(200)
index += 1
}
expect(index).toBeGreaterThanOrEqual(3)
const commitRes = await commit(app, beginJson.repoId, beginJson.uploadId, index)
expect(commitRes.status).toBe(200)
expect(existsSync(join(targetPath, 'a.bin'))).toBe(true)
expect(existsSync(join(targetPath, 'b.bin'))).toBe(true)
})
it('creates the mirror target parent before final rename', async () => {
const targetPath = join(getTmpRoot(), 'nested', 'test-repo')
mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'nested/test-repo', fullPath: targetPath })
@@ -168,19 +284,14 @@ describe('internal-repo-mirror routes', () => {
const result = spawnSync('tar', ['-c', '-C', sourceDir, '.'], { encoding: 'buffer' })
const tarball = result.stdout as Buffer
const res = await app.request('/api/internal/repos/0/mirror?create=1&name=test-repo', {
method: 'POST',
body: tarball,
headers: { 'content-type': 'application/x-tar' },
})
expect(res.status).toBe(200)
const json = (await res.json()) as { fullPath: string }
const { commitRes } = await pushTarball(app, 0, { create: true, name: 'test-repo' }, tarball)
expect(commitRes?.status).toBe(200)
const json = (await commitRes!.json()) as CommitResponse
expect(json.fullPath).toBe(targetPath)
expect(existsSync(join(targetPath, 'payload.txt'))).toBe(true)
})
it('returns 409 when repo is in use and force not set', async () => {
it('returns 409 from begin when repo is in use and force not set', async () => {
const repoDir = join(getTmpRoot(), 'test-repo')
mkdirSync(repoDir, { recursive: true })
writeFileSync(join(repoDir, 'existing.txt'), 'existing')
@@ -188,127 +299,72 @@ describe('internal-repo-mirror routes', () => {
mockGetRepoById.mockReturnValue({ id: 1, fullPath: repoDir })
mockIsRepoInUse.mockReturnValue(true)
const sourceDir = join(getTmpRoot(), 'source')
mkdirSync(sourceDir, { recursive: true })
writeFileSync(join(sourceDir, 'payload.txt'), 'payload data')
const result = spawnSync('tar', ['-c', '-C', sourceDir, '.'], { encoding: 'buffer' })
const tarball = result.stdout as Buffer
const res = await app.request('/api/internal/repos/1/mirror', {
method: 'POST',
body: tarball,
headers: { 'content-type': 'application/x-tar' },
})
const res = await begin(app, 1, {})
expect(res.status).toBe(409)
const json = (await res.json()) as { error: string }
expect(json.error).toBe('repo_in_use')
})
it('returns 400 when create=1 but name missing', async () => {
const res = await app.request('/api/internal/repos/0/mirror?create=1', {
method: 'POST',
body: Buffer.alloc(0),
headers: { 'content-type': 'application/x-tar' },
})
it('returns 400 when create=true but name missing', async () => {
const res = await begin(app, 0, { create: true })
expect(res.status).toBe(400)
const json = (await res.json()) as { error: string }
expect(json.error).toBe('name required')
})
it('returns 400 with no body and does not create DB row', async () => {
const res = await app.request('/api/internal/repos/0/mirror?create=1&name=foo', {
method: 'POST',
headers: { 'content-type': 'application/x-tar' },
})
expect(res.status).toBe(400)
const json = (await res.json()) as { error: string }
expect(json.error).toBe('no body provided')
expect(mockCreateRepoRow).not.toHaveBeenCalled()
})
it('returns 404 for non-existent repo without create', async () => {
it('returns 404 from begin for non-existent repo without create', async () => {
mockGetRepoById.mockReturnValue(null)
const sourceDir = join(getTmpRoot(), 'source')
mkdirSync(sourceDir, { recursive: true })
writeFileSync(join(sourceDir, 'payload.txt'), 'payload data')
const result = spawnSync('tar', ['-c', '-C', sourceDir, '.'], { encoding: 'buffer' })
const tarball = result.stdout as Buffer
const res = await app.request('/api/internal/repos/99999/mirror', {
method: 'POST',
body: tarball,
headers: { 'content-type': 'application/x-tar' },
})
const res = await begin(app, 99999, {})
expect(res.status).toBe(404)
})
it('rolls back created DB row when tarball extraction fails', async () => {
it('returns 404 from PUT for unknown uploadId', async () => {
const res = await putPart(app, 1, 'no-such-upload', 0, Buffer.from('payload'))
expect(res.status).toBe(404)
})
it('returns 404 from commit for unknown uploadId', async () => {
const res = await commit(app, 1, 'no-such-upload', 1)
expect(res.status).toBe(404)
})
it('rolls back created DB row when commit fails on invalid tarball', async () => {
const targetPath = join(getTmpRoot(), 'test-repo')
mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'test-repo', fullPath: targetPath })
mockCreateRepoRow.mockImplementation((_db: any, input: any) => ({ repo: { id: 1, fullPath: input.fullPath, localPath: input.localPath }, created: true }))
mockDeleteRepo.mockReturnValue(undefined)
const res = await app.request('/api/internal/repos/0/mirror?create=1&name=test-repo', {
method: 'POST',
body: Buffer.from('not a tarball'),
headers: { 'content-type': 'application/x-tar' },
})
const beginRes = await begin(app, 0, { create: true, name: 'test-repo' })
expect(beginRes.status).toBe(200)
const beginJson = (await beginRes.json()) as BeginResponse
expect(res.status).toBe(500)
const putRes = await putPart(app, beginJson.repoId, beginJson.uploadId, 0, Buffer.from('not a tarball'))
expect(putRes.status).toBe(200)
const commitRes = await commit(app, beginJson.repoId, beginJson.uploadId, 1)
expect(commitRes.status).toBe(500)
expect(mockDeleteRepo).toHaveBeenCalledWith({}, 1)
})
it('returns 500 without hanging on very small invalid body (tar exit race)', async () => {
const targetPath = join(getTmpRoot(), 'test-repo-race')
mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'test-repo-race', fullPath: targetPath })
mockCreateRepoRow.mockImplementation((_db: any, input: any) => ({ repo: { id: 1, fullPath: input.fullPath, localPath: input.localPath }, created: true }))
it('does not delete existing repo on commit failure when createRepoRow returns non-created', async () => {
const existingRepoPath = join(getTmpRoot(), 'existing-repo-fail')
mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'new-name', fullPath: join(getTmpRoot(), 'new-name') })
mockCreateRepoRow.mockImplementation(() => ({
repo: { id: 5, fullPath: existingRepoPath, localPath: 'existing-repo' },
created: false,
}))
mockDeleteRepo.mockReturnValue(undefined)
const res = await app.request('/api/internal/repos/0/mirror?create=1&name=test-repo-race', {
method: 'POST',
body: Buffer.from([0x00]),
headers: { 'content-type': 'application/x-tar' },
})
const beginRes = await begin(app, 0, { create: true, name: 'new-name' })
expect(beginRes.status).toBe(200)
const beginJson = (await beginRes.json()) as BeginResponse
expect(res.status).toBe(500)
expect(mockDeleteRepo).toHaveBeenCalledWith({}, 1)
})
const putRes = await putPart(app, beginJson.repoId, beginJson.uploadId, 0, Buffer.from('not a tarball'))
expect(putRes.status).toBe(200)
it('handles gzip-compressed tarball with Content-Encoding: gzip', async () => {
const targetPath = join(getTmpRoot(), 'test-repo-gzip')
mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'test-repo-gzip', fullPath: targetPath })
mockCreateRepoRow.mockImplementation((_db: any, input: any) => ({ repo: { id: 1, fullPath: input.fullPath, localPath: input.localPath }, created: true }))
const sourceDir = join(getTmpRoot(), 'source-gzip')
mkdirSync(sourceDir, { recursive: true })
writeFileSync(join(sourceDir, 'gzip.txt'), 'gzip payload')
const result = spawnSync('tar', ['-c', '-C', sourceDir, '.'], { encoding: 'buffer' })
const tarball = result.stdout as Buffer
const gzipped = gzipSync(tarball)
const res = await app.request('/api/internal/repos/0/mirror?create=1&name=test-repo-gzip', {
method: 'POST',
body: gzipped,
headers: {
'content-type': 'application/x-tar',
'Content-Encoding': 'gzip',
},
})
expect(res.status).toBe(200)
const json = (await res.json()) as { created: boolean; repoId: number; fullPath: string }
expect(json.created).toBe(true)
expect(json.repoId).toBe(1)
expect(json.fullPath).toBe(targetPath)
expect(existsSync(join(json.fullPath, 'gzip.txt'))).toBe(true)
expect(readFileSync(join(json.fullPath, 'gzip.txt'), 'utf-8')).toBe('gzip payload')
const commitRes = await commit(app, beginJson.repoId, beginJson.uploadId, 1)
expect(commitRes.status).toBe(500)
expect(mockDeleteRepo).not.toHaveBeenCalled()
})
it('returns 409 when create-on-push finds existing repo in use and force not set', async () => {
@@ -320,24 +376,13 @@ describe('internal-repo-mirror routes', () => {
}))
mockIsRepoInUse.mockReturnValue(true)
const sourceDir = join(getTmpRoot(), 'source-inuse')
mkdirSync(sourceDir, { recursive: true })
writeFileSync(join(sourceDir, 'file.txt'), 'should not land')
const result = spawnSync('tar', ['-c', '-C', sourceDir, '.'], { encoding: 'buffer' })
const tarball = result.stdout as Buffer
const res = await app.request('/api/internal/repos/0/mirror?create=1&name=existing-repo', {
method: 'POST',
body: tarball,
headers: { 'content-type': 'application/x-tar' },
})
const res = await begin(app, 0, { create: true, name: 'existing-repo' })
expect(res.status).toBe(409)
const json = (await res.json()) as { error: string }
expect(json.error).toBe('repo_in_use')
})
it('allows create-on-push of existing repo when force=1 even if in use', async () => {
it('allows create-on-push of existing repo when force=true even if in use', async () => {
const existingRepoPath = join(getTmpRoot(), 'existing-repo-force')
mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'existing-repo-force', fullPath: existingRepoPath })
mockCreateRepoRow.mockImplementation(() => ({
@@ -352,14 +397,9 @@ describe('internal-repo-mirror routes', () => {
const result = spawnSync('tar', ['-c', '-C', sourceDir, '.'], { encoding: 'buffer' })
const tarball = result.stdout as Buffer
const res = await app.request('/api/internal/repos/0/mirror?create=1&name=existing-repo-force&force=1', {
method: 'POST',
body: tarball,
headers: { 'content-type': 'application/x-tar' },
})
expect(res.status).toBe(200)
const json = (await res.json()) as { created: boolean; repoId: number; fullPath: string }
const { commitRes } = await pushTarball(app, 0, { create: true, name: 'existing-repo-force', force: true }, tarball)
expect(commitRes?.status).toBe(200)
const json = (await commitRes!.json()) as CommitResponse
expect(json.created).toBe(false)
expect(json.repoId).toBe(7)
expect(existsSync(join(json.fullPath, 'forced.txt'))).toBe(true)
@@ -380,14 +420,9 @@ describe('internal-repo-mirror routes', () => {
const result = spawnSync('tar', ['-c', '-C', sourceDir, '.'], { encoding: 'buffer' })
const tarball = result.stdout as Buffer
const res = await app.request('/api/internal/repos/0/mirror?create=1&name=new-name', {
method: 'POST',
body: tarball,
headers: { 'content-type': 'application/x-tar' },
})
expect(res.status).toBe(200)
const json = (await res.json()) as { created: boolean; repoId: number; fullPath: string }
const { commitRes } = await pushTarball(app, 0, { create: true, name: 'new-name' }, tarball)
expect(commitRes?.status).toBe(200)
const json = (await commitRes!.json()) as CommitResponse
expect(json.created).toBe(false)
expect(json.repoId).toBe(5)
expect(json.fullPath).toBe(existingRepoPath)
@@ -396,23 +431,23 @@ describe('internal-repo-mirror routes', () => {
expect(readFileSync(join(json.fullPath, 'file.txt'), 'utf-8')).toBe('existing content')
})
it('does not delete existing repo on failure when createRepoRow returns non-created repo', async () => {
const existingRepoPath = join(getTmpRoot(), 'existing-repo-fail')
mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'new-name', fullPath: join(getTmpRoot(), 'new-name') })
mockCreateRepoRow.mockImplementation(() => ({
repo: { id: 5, fullPath: existingRepoPath, localPath: 'existing-repo' },
created: false,
}))
it('DELETE removes the upload session and deletes the created repo', async () => {
mockEnsureMirrorTargetPath.mockReturnValue({ localPath: 'abort-repo', fullPath: join(getTmpRoot(), 'abort-repo') })
mockCreateRepoRow.mockImplementation((_db: any, input: any) => ({ repo: { id: 11, fullPath: input.fullPath, localPath: input.localPath }, created: true }))
mockDeleteRepo.mockReturnValue(undefined)
const res = await app.request('/api/internal/repos/0/mirror?create=1&name=new-name', {
method: 'POST',
body: Buffer.from('not a tarball'),
headers: { 'content-type': 'application/x-tar' },
})
const beginRes = await begin(app, 0, { create: true, name: 'abort-repo' })
expect(beginRes.status).toBe(200)
const beginJson = (await beginRes.json()) as BeginResponse
expect(res.status).toBe(500)
expect(mockDeleteRepo).not.toHaveBeenCalled()
const delRes = await app.request(`/api/internal/repos/${beginJson.repoId}/mirror/uploads/${beginJson.uploadId}`, {
method: 'DELETE',
})
expect(delRes.status).toBe(200)
expect(mockDeleteRepo).toHaveBeenCalledWith({}, 11)
const commitRes = await commit(app, beginJson.repoId, beginJson.uploadId, 0)
expect(commitRes.status).toBe(404)
})
})
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-manager/ocm-cli",
"version": "0.1.1",
"version": "0.1.2",
"description": "OpenCode Manager CLI: attach a local OpenCode TUI to a Manager-hosted repo.",
"license": "MIT",
"repository": {
+92 -25
View File
@@ -1,3 +1,56 @@
export interface MirrorBeginOpts {
force?: boolean
create?: { name: string; originUrl: string | null; branch: string | null }
}
export interface MirrorBeginResult {
uploadId: string
repoId: number
chunkSize: number
created: boolean
}
export interface MirrorCommitResult {
repoId: number
fullPath: string
branch: string | null
head: string | null
created: boolean
}
export class ManagerApiError extends Error {
constructor(
message: string,
public readonly status: number,
public readonly code: string | null,
public readonly operation: string,
) {
super(message)
this.name = 'ManagerApiError'
}
}
async function formatErrorResponse(res: Response, operation: string): Promise<ManagerApiError> {
const text = await res.text().catch(() => '')
let code: string | null = null
let detail = text
if (text) {
try {
const parsed = JSON.parse(text) as { error?: unknown; message?: unknown }
const errField = typeof parsed.error === 'string' ? parsed.error : null
const msgField = typeof parsed.message === 'string' ? parsed.message : null
code = errField
detail = msgField ?? errField ?? text
} catch {
/* not JSON, keep raw text */
}
}
const message = detail
? `${operation} failed (${res.status}): ${detail}`
: `${operation} failed (${res.status})`
return new ManagerApiError(message, res.status, code, operation)
}
export class ManagerApi {
constructor(
private baseUrl: string,
@@ -8,35 +61,49 @@ export class ManagerApi {
return { Authorization: `Bearer ${this.token}`, ...extra }
}
async mirrorUp(
repoId: number,
body: ReadableStream<Uint8Array>,
opts: { force?: boolean; create?: { name: string; originUrl: string | null; branch: string | null } },
): Promise<{ repoId: number; branch: string; head: string; created: boolean }> {
const params = new URLSearchParams()
if (opts.force) params.set('force', '1')
async mirrorBegin(repoId: number, opts: MirrorBeginOpts): Promise<MirrorBeginResult> {
const url = `${this.baseUrl}/api/internal/repos/${repoId}/mirror/begin`
const body: Record<string, unknown> = { force: opts.force === true }
if (opts.create) {
params.set('create', '1')
params.set('name', opts.create.name)
if (opts.create.originUrl) params.set('originUrl', opts.create.originUrl)
if (opts.create.branch) params.set('branch', opts.create.branch)
body.create = true
body.name = opts.create.name
if (opts.create.originUrl) body.originUrl = opts.create.originUrl
if (opts.create.branch) body.branch = opts.create.branch
}
const qs = params.toString() ? `?${params.toString()}` : ''
const url = `${this.baseUrl}/api/internal/repos/${repoId}/mirror${qs}`
const res = await fetch(url, {
method: 'POST',
headers: {
...this.headers(),
'Content-Type': 'application/x-tar',
},
body,
duplex: 'half',
} as RequestInit & { duplex: 'half' })
headers: { ...this.headers(), 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!res.ok) throw await formatErrorResponse(res, 'mirror begin')
return (await res.json()) as MirrorBeginResult
}
if (!res.ok) throw new Error(`mirror ${res.status}: ${await res.text()}`)
return (await res.json()) as { repoId: number; branch: string; head: string; created: boolean }
async mirrorUploadPart(repoId: number, uploadId: string, index: number, chunk: Buffer): Promise<void> {
const url = `${this.baseUrl}/api/internal/repos/${repoId}/mirror/parts/${uploadId}/${index}`
const ab = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength)
const res = await fetch(url, {
method: 'PUT',
headers: { ...this.headers(), 'Content-Type': 'application/octet-stream' },
body: ab as ArrayBuffer,
})
if (!res.ok) throw await formatErrorResponse(res, `mirror part ${index}`)
}
async mirrorCommit(repoId: number, uploadId: string, totalParts: number): Promise<MirrorCommitResult> {
const url = `${this.baseUrl}/api/internal/repos/${repoId}/mirror/commit`
const res = await fetch(url, {
method: 'POST',
headers: { ...this.headers(), 'Content-Type': 'application/json' },
body: JSON.stringify({ uploadId, totalParts }),
})
if (!res.ok) throw await formatErrorResponse(res, 'mirror commit')
return (await res.json()) as MirrorCommitResult
}
async mirrorAbort(repoId: number, uploadId: string): Promise<void> {
const url = `${this.baseUrl}/api/internal/repos/${repoId}/mirror/uploads/${uploadId}`
await fetch(url, { method: 'DELETE', headers: this.headers() }).catch(() => { /* best-effort */ })
}
async mirrorDown(repoId: number): Promise<ReadableStream<Uint8Array>> {
@@ -44,7 +111,7 @@ export class ManagerApi {
headers: this.headers(),
})
if (!res.ok) throw new Error(`mirror ${res.status}: ${await res.text()}`)
if (!res.ok) throw await formatErrorResponse(res, 'mirror download')
return res.body!
}
}
+103 -12
View File
@@ -6,8 +6,11 @@ import { join } from 'path'
import { tmpdir } from 'os'
import { getRepoRoot, getOriginUrl, getDirtyPaths, urlsEqual } from './local-repo.js'
import type { ManagerApi } from './manager-api.js'
import { ManagerApiError } from './manager-api.js'
const HARDCODED_EXCLUDES = ['node_modules', 'dist', '.next', '.venv', '__pycache__', '.turbo']
const HARDCODED_EXCLUDES = ['node_modules', 'dist', '.next', '.venv', '__pycache__', '.turbo', '.DS_Store', '._*']
const PART_RETRIES = 3
const PART_BACKOFF_MS = [500, 2000, 8000]
function getGitignoreExclusions(repoRoot: string): string[] {
const res = spawnSync('git', ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'], {
@@ -56,10 +59,93 @@ export interface MirrorUpOpts {
create?: { name: string; originUrl: string | null; branch: string | null }
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
function isRetryablePartError(err: unknown): boolean {
if (err instanceof ManagerApiError) {
return err.status >= 500 || err.status === 408 || err.status === 429
}
return true
}
async function uploadPartWithRetry(
api: ManagerApi,
repoId: number,
uploadId: string,
index: number,
chunk: Buffer,
): Promise<void> {
let lastError: unknown
for (let attempt = 0; attempt < PART_RETRIES; attempt++) {
try {
await api.mirrorUploadPart(repoId, uploadId, index, chunk)
return
} catch (err) {
lastError = err
if (!isRetryablePartError(err)) break
if (attempt < PART_RETRIES - 1) {
await delay(PART_BACKOFF_MS[attempt]!)
}
}
}
throw lastError instanceof Error ? lastError : new Error(`part ${index} failed: ${String(lastError)}`)
}
interface PartFlusher {
push(buf: Buffer): Promise<void>
finish(): Promise<number>
}
function createPartFlusher(
api: ManagerApi,
repoId: number,
uploadId: string,
chunkSize: number,
): PartFlusher {
let acc: Buffer[] = []
let accLen = 0
let index = 0
const flush = async (): Promise<void> => {
if (accLen === 0) return
const buf = Buffer.concat(acc, accLen)
acc = []
accLen = 0
await uploadPartWithRetry(api, repoId, uploadId, index, buf)
index += 1
}
return {
async push(buf: Buffer): Promise<void> {
let offset = 0
while (offset < buf.length) {
const room = chunkSize - accLen
const take = Math.min(room, buf.length - offset)
acc.push(buf.subarray(offset, offset + take))
accLen += take
offset += take
if (accLen >= chunkSize) {
await flush()
}
}
},
async finish(): Promise<number> {
await flush()
return index
},
}
}
export async function mirrorUp(
plan: MirrorPlan,
opts: MirrorUpOpts,
): Promise<{ repoId: number; branch: string; head: string; created: boolean }> {
): Promise<{ repoId: number; branch: string | null; head: string | null; created: boolean }> {
const repoId = opts.create ? 0 : plan.matched[0]!.repoId
const begin = await opts.api.mirrorBegin(repoId, { force: opts.force, create: opts.create })
const tarArgs = ['-c', '-C', plan.repoRoot]
for (const dir of HARDCODED_EXCLUDES) tarArgs.push('--exclude', dir)
@@ -74,7 +160,10 @@ export async function mirrorUp(
tarArgs.push('.')
const child = spawn('tar', tarArgs, { stdio: ['pipe', 'pipe', 'pipe'] })
const child = spawn('tar', tarArgs, {
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, COPYFILE_DISABLE: '1' },
})
const stderrChunks: Buffer[] = []
child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk))
@@ -90,18 +179,20 @@ export async function mirrorUp(
child.on('error', reject)
})
const body = Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>
const repoId = opts.create ? 0 : plan.matched[0]!.repoId
const flusher = createPartFlusher(opts.api, begin.repoId, begin.uploadId, begin.chunkSize)
try {
const [result] = await Promise.all([
opts.api.mirrorUp(repoId, body, {
force: opts.force,
create: opts.create,
}),
tarExit,
])
for await (const chunk of child.stdout as AsyncIterable<Buffer>) {
await flusher.push(chunk)
}
await tarExit
const totalParts = await flusher.finish()
const result = await opts.api.mirrorCommit(begin.repoId, begin.uploadId, totalParts)
return result
} catch (err) {
if (!child.killed) child.kill('SIGKILL')
await opts.api.mirrorAbort(begin.repoId, begin.uploadId)
throw err
} finally {
if (excludeFile) {
await fsp.rm(excludeFile, { force: true }).catch(() => {})
+74 -42
View File
@@ -298,7 +298,7 @@ describe('mirrorDown', () => {
})
})
describe('mirrorUp with gitignore', () => {
describe('mirrorUp chunked upload', () => {
let tmpDir: string
beforeEach(() => {
@@ -309,70 +309,106 @@ describe('mirrorUp with gitignore', () => {
rmSync(tmpDir, { recursive: true, force: true })
})
it('excludes gitignored files from tar stream', async () => {
const repoRoot = join(tmpDir, 'repo-up-gitignore')
function makeMockApi(opts: { partFailures?: Record<number, number>; chunkSize?: number } = {}) {
const partsReceived: Buffer[] = []
const partFailures: Record<number, number> = opts.partFailures ?? {}
const chunkSize = opts.chunkSize ?? 8 * 1024 * 1024
let committed = false
let commitTotalParts = 0
const api = {
mirrorBegin: vi.fn().mockResolvedValue({ uploadId: 'upload-1', repoId: 1, chunkSize, created: false }),
mirrorUploadPart: vi.fn().mockImplementation(async (_repoId: number, _uploadId: string, index: number, chunk: Buffer) => {
if (partFailures[index] && partFailures[index] > 0) {
partFailures[index] -= 1
throw new Error(`simulated transient failure on part ${index}`)
}
partsReceived[index] = Buffer.from(chunk)
}),
mirrorCommit: vi.fn().mockImplementation(async (_repoId: number, _uploadId: string, totalParts: number) => {
committed = true
commitTotalParts = totalParts
return { repoId: 1, fullPath: '/tmp/x', branch: 'main', head: 'abc', created: false }
}),
mirrorAbort: vi.fn().mockResolvedValue(undefined),
}
return {
api,
partsReceived,
get committed() { return committed },
get commitTotalParts() { return commitTotalParts },
}
}
it('uploads a small repo as a single part and commits', async () => {
const repoRoot = join(tmpDir, 'repo-small')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'tracked.txt'), 'tracked content')
writeFileSync(join(repoRoot, 'secrets.env'), 'SECRET_KEY=abc123')
writeFileSync(join(repoRoot, '.gitignore'), 'secrets.env\n')
const mockApi = {
mirrorUp: vi.fn().mockResolvedValue({ repoId: 1, branch: 'main', head: 'abc123', created: false }),
} as any
const ctx = makeMockApi()
const plan = {
repoRoot,
localOrigin: 'https://github.com/test/repo.git',
matched: [{ repoId: 1, name: 'test-repo', originUrl: 'https://github.com/test/repo.git', branch: 'main' }],
}
await mirrorUp(plan, { api: mockApi, force: false })
await mirrorUp(plan, { api: ctx.api as any, force: false })
expect(mockApi.mirrorUp).toHaveBeenCalledTimes(1)
expect(mockApi.mirrorUp.mock.calls[0][0]).toBe(1)
const opts = mockApi.mirrorUp.mock.calls[0][2]
expect(opts.force).toBe(false)
expect(ctx.api.mirrorBegin).toHaveBeenCalledTimes(1)
expect(ctx.api.mirrorUploadPart).toHaveBeenCalled()
expect(ctx.api.mirrorCommit).toHaveBeenCalledTimes(1)
expect(ctx.committed).toBe(true)
expect(ctx.commitTotalParts).toBeGreaterThan(0)
})
it('excludes node_modules from tar stream', async () => {
const repoRoot = join(tmpDir, 'repo-up-node-modules')
it('splits a tarball larger than chunkSize across multiple parts', async () => {
const repoRoot = join(tmpDir, 'repo-multi')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'a.bin'), Buffer.alloc(200 * 1024, 0xab))
writeFileSync(join(repoRoot, 'b.bin'), Buffer.alloc(200 * 1024, 0xcd))
writeFileSync(join(repoRoot, 'file.txt'), 'content')
mkdirSync(join(repoRoot, 'node_modules'))
writeFileSync(join(repoRoot, 'node_modules', 'dep.js'), 'dep content')
const mockApi = {
mirrorUp: vi.fn().mockResolvedValue({ repoId: 1, branch: 'main', head: 'abc123', created: false }),
} as any
const ctx = makeMockApi({ chunkSize: 128 * 1024 })
const plan = {
repoRoot,
localOrigin: 'https://github.com/test/repo.git',
matched: [{ repoId: 1, name: 'test-repo', originUrl: 'https://github.com/test/repo.git', branch: 'main' }],
}
await mirrorUp(plan, { api: mockApi, force: false })
await mirrorUp(plan, { api: ctx.api as any, force: false })
expect(mockApi.mirrorUp).toHaveBeenCalledTimes(1)
expect(mockApi.mirrorUp.mock.calls[0][0]).toBe(1)
expect(mockApi.mirrorUp.mock.calls[0][2].force).toBe(false)
expect(ctx.api.mirrorUploadPart.mock.calls.length).toBeGreaterThanOrEqual(2)
expect(ctx.commitTotalParts).toBe(ctx.api.mirrorUploadPart.mock.calls.length)
})
it('does not create exclude file when no gitignored paths exist', async () => {
const repoRoot = join(tmpDir, 'repo-up-no-ignore')
it('retries a failing part and still commits', async () => {
const repoRoot = join(tmpDir, 'repo-retry')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'tracked.txt'), 'tracked content')
writeFileSync(join(repoRoot, 'file.txt'), 'content')
const ctx = makeMockApi({ partFailures: { 0: 2 }, chunkSize: 64 * 1024 })
const plan = {
repoRoot,
localOrigin: 'https://github.com/test/repo.git',
matched: [{ repoId: 1, name: 'test-repo', originUrl: 'https://github.com/test/repo.git', branch: 'main' }],
}
const mockApi = {
mirrorUp: vi.fn().mockResolvedValue({ repoId: 1, branch: 'main', head: 'abc123', created: false }),
} as any
await mirrorUp(plan, { api: ctx.api as any, force: false })
const part0Calls = ctx.api.mirrorUploadPart.mock.calls.filter((c) => c[2] === 0)
expect(part0Calls.length).toBe(3)
expect(ctx.committed).toBe(true)
})
it('aborts the upload session if commit fails terminally', async () => {
const repoRoot = join(tmpDir, 'repo-abort')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'tracked.txt'), 'tracked content')
const ctx = makeMockApi()
ctx.api.mirrorCommit.mockRejectedValueOnce(new Error('boom'))
const plan = {
repoRoot,
@@ -380,11 +416,7 @@ describe('mirrorUp with gitignore', () => {
matched: [{ repoId: 1, name: 'test-repo', originUrl: 'https://github.com/test/repo.git', branch: 'main' }],
}
await mirrorUp(plan, { api: mockApi, force: false })
expect(mockApi.mirrorUp).toHaveBeenCalledTimes(1)
expect(mockApi.mirrorUp.mock.calls[0][0]).toBe(1)
const opts = mockApi.mirrorUp.mock.calls[0][2]
expect(opts.force).toBe(false)
await expect(mirrorUp(plan, { api: ctx.api as any, force: false })).rejects.toThrow('boom')
expect(ctx.api.mirrorAbort).toHaveBeenCalledWith(1, 'upload-1')
})
})