mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(mirror): enable gzip compression for repository mirror transfers (#250)
* feat(mirror): enable gzip compression for repository mirror transfers * fix(mirror): remove stale uncompressed progress, centralize gzip flag, dedupe test mocks * chore(mirror): drop dead progress update() method and unused phase field * chore(ocm-cli): bump version to 0.1.4
This commit is contained in:
1 parent
2b2cb6d23d
commit
500d4dfcc1
10 files changed
+124
-303
No files matched your search
@@ -90,12 +90,12 @@ export class ManagerApi {
|
||||
if (!res.ok) throw await formatErrorResponse(res, `mirror part ${index}`)
|
||||
}
|
||||
|
||||
async mirrorCommit(repoId: number, uploadId: string, totalParts: number): Promise<MirrorCommitResult> {
|
||||
async mirrorCommit(repoId: number, uploadId: string, totalParts: number, gzip: boolean): 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 }),
|
||||
body: JSON.stringify({ uploadId, totalParts, gzip }),
|
||||
})
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror commit')
|
||||
return (await res.json()) as MirrorCommitResult
|
||||
@@ -106,8 +106,9 @@ export class ManagerApi {
|
||||
await fetch(url, { method: 'DELETE', headers: this.headers() }).catch(() => { /* best-effort */ })
|
||||
}
|
||||
|
||||
async mirrorDown(repoId: number): Promise<ReadableStream<Uint8Array>> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror`, {
|
||||
async mirrorDown(repoId: number, gzip: boolean): Promise<ReadableStream<Uint8Array>> {
|
||||
const query = gzip ? '?compress=gzip' : ''
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror${query}`, {
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
|
||||
+10
-35
@@ -1,5 +1,5 @@
|
||||
import { spawnSync, spawn } from 'child_process'
|
||||
import { existsSync, statSync } from 'fs'
|
||||
import { existsSync } from 'fs'
|
||||
import * as fsp from 'fs/promises'
|
||||
import { Readable } from 'stream'
|
||||
import { join, dirname } from 'path'
|
||||
@@ -11,6 +11,7 @@ import { ManagerApiError } from './manager-api.js'
|
||||
const HARDCODED_EXCLUDES = ['node_modules', 'dist', '.next', '.venv', '__pycache__', '.turbo', '.DS_Store', '._*']
|
||||
const PART_RETRIES = 3
|
||||
const PART_BACKOFF_MS = [500, 2000, 8000]
|
||||
const MIRROR_GZIP = true
|
||||
|
||||
function getGitignoreExclusions(repoRoot: string): string[] {
|
||||
const res = spawnSync('git', ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'], {
|
||||
@@ -34,32 +35,6 @@ async function carryOverIgnored(fromDir: string, toDir: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
function listIncludedFiles(repoRoot: string): string[] {
|
||||
const tracked = spawnSync('git', ['ls-files', '-z'], { cwd: repoRoot, encoding: 'utf-8' })
|
||||
const untracked = spawnSync('git', ['ls-files', '--others', '--exclude-standard', '-z'], { cwd: repoRoot, encoding: 'utf-8' })
|
||||
const split = (out: string | null): string[] => (out ?? '').split('\0').filter((p) => p.length > 0)
|
||||
const all = [...split(tracked.stdout), ...split(untracked.stdout)]
|
||||
return all.filter((p) => {
|
||||
const top = p.split('/')[0] ?? p
|
||||
return !HARDCODED_EXCLUDES.includes(top)
|
||||
})
|
||||
}
|
||||
|
||||
export function estimateTarSize(repoRoot: string): number {
|
||||
const files = listIncludedFiles(repoRoot)
|
||||
let total = 0
|
||||
for (const rel of files) {
|
||||
let size = 0
|
||||
try {
|
||||
size = statSync(join(repoRoot, rel)).size
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
total += 512 + Math.ceil(size / 512) * 512
|
||||
}
|
||||
return total + 1024
|
||||
}
|
||||
|
||||
export class MirrorAbort extends Error {
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
@@ -93,9 +68,7 @@ export function prepareMirror(cwd: string, remotes: RemoteRepoSummary[]): Mirror
|
||||
}
|
||||
|
||||
export interface MirrorProgress {
|
||||
phase: 'uploading' | 'committing'
|
||||
bytesSent: number
|
||||
totalBytes: number
|
||||
}
|
||||
|
||||
export interface MirrorUpOpts {
|
||||
@@ -192,10 +165,10 @@ export async function mirrorUp(
|
||||
|
||||
const begin = await opts.api.mirrorBegin(repoId, { force: opts.force, create: opts.create })
|
||||
|
||||
const totalBytes = estimateTarSize(plan.repoRoot)
|
||||
let bytesSent = 0
|
||||
|
||||
const tarArgs = ['-c', '-C', plan.repoRoot]
|
||||
if (MIRROR_GZIP) tarArgs.unshift('-z')
|
||||
for (const dir of HARDCODED_EXCLUDES) tarArgs.push('--exclude', dir)
|
||||
|
||||
const ignoredPaths = getGitignoreExclusions(plan.repoRoot)
|
||||
@@ -234,12 +207,12 @@ export async function mirrorUp(
|
||||
for await (const chunk of child.stdout as AsyncIterable<Buffer>) {
|
||||
await flusher.push(chunk)
|
||||
bytesSent += chunk.length
|
||||
opts.onProgress?.({ phase: 'uploading', bytesSent, totalBytes })
|
||||
opts.onProgress?.({ bytesSent })
|
||||
}
|
||||
await tarExit
|
||||
const totalParts = await flusher.finish()
|
||||
opts.onProgress?.({ phase: 'committing', bytesSent, totalBytes })
|
||||
const result = await opts.api.mirrorCommit(begin.repoId, begin.uploadId, totalParts)
|
||||
opts.onProgress?.({ bytesSent })
|
||||
const result = await opts.api.mirrorCommit(begin.repoId, begin.uploadId, totalParts, MIRROR_GZIP)
|
||||
return result
|
||||
} catch (err) {
|
||||
if (!child.killed) child.kill('SIGKILL')
|
||||
@@ -266,9 +239,11 @@ export async function mirrorDown(
|
||||
await fsp.mkdir(staging, { recursive: true })
|
||||
|
||||
try {
|
||||
const tarball = await api.mirrorDown(repoId)
|
||||
const tarball = await api.mirrorDown(repoId, MIRROR_GZIP)
|
||||
|
||||
const child = spawn('tar', ['-x', '-f', '-', '-C', staging], { stdio: ['pipe', 'pipe', 'pipe'] })
|
||||
const tarArgs = ['-x', '-f', '-', '-C', staging]
|
||||
if (MIRROR_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))
|
||||
|
||||
@@ -19,7 +19,6 @@ export interface ProgressSink {
|
||||
}
|
||||
|
||||
export interface ProgressReporter {
|
||||
update(current: number, total: number): void
|
||||
tick(bytes: number): void
|
||||
done(): void
|
||||
}
|
||||
@@ -31,30 +30,11 @@ export function createProgressReporter(
|
||||
): ProgressReporter {
|
||||
let finished = false
|
||||
let lastRenderAt = -Infinity
|
||||
let lastBucket = -1
|
||||
let lastNonTtyTickAt = -Infinity
|
||||
let frameIndex = 0
|
||||
const isTTY = out.isTTY === true
|
||||
|
||||
return {
|
||||
update(current: number, total: number): void {
|
||||
if (finished) return
|
||||
|
||||
if (isTTY) {
|
||||
const t = now()
|
||||
if (t - lastRenderAt < 80) return
|
||||
lastRenderAt = t
|
||||
const pct = total > 0 ? Math.min(99, Math.floor((current / total) * 100)) : 0
|
||||
out.write(`\r\x1b[K${label}: ${pct}% (${formatBytes(current)} / ${formatBytes(total)})`)
|
||||
} else {
|
||||
const pct = total > 0 ? Math.min(99, Math.floor((current / total) * 100)) : 0
|
||||
const bucket = Math.floor(pct / 10)
|
||||
if (bucket === lastBucket) return
|
||||
lastBucket = bucket
|
||||
out.write(`${label}: ${pct}% (${formatBytes(current)} / ${formatBytes(total)})\n`)
|
||||
}
|
||||
},
|
||||
|
||||
tick(bytes: number): void {
|
||||
if (finished) return
|
||||
const t = now()
|
||||
|
||||
Reference in new issue
Block a user