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

+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(() => {})