Compare commits

...

1 Commits

Author SHA1 Message Date
48e0421135 fix(rp): 사진 다운로드 HTTP 429(속도제한) 내성 강화
증상: 리소스팩 설치기 사진 다운로드에서 "N번 사진 다운로드 실패: HTTP 429" 로
설치가 중단됨. 원인: 음악(yt-dlp) 단계가 유튜브를 많이 두드려 IP 가 일시
throttle 되고, 사진 단계는 순차이긴 하나 요청 간 간격이 없어 i.ytimg.com 429 를
유발/회복하지 못하고 첫 장부터 실패.

- 음악 단계 직후 사진 단계 시작 전 쿨다운(4s).
- 사진 요청 사이 간격(0.8s+jitter)으로 429 유발 억제.
- 재시도 5→6회, 재시도마다 로그/진행률로 대기 상태 표시(멈춘 것처럼 보이지 않게).
- 최종 실패가 429면 "잠시 뒤 다시 시도하면 이어받는다"는 안내 추가.
- 버전 0.4.3→0.4.4.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-17 00:29:23 +09:00
4 changed files with 55 additions and 16 deletions

View File

@@ -100,6 +100,8 @@
"imageDownloading": "{{idx}}번 사진 다운로드 중…",
"imageDone": "{{idx}}번 사진 완료: {{name}}",
"imageSkip": "{{idx}}번 사진은 이전에 받아둠 → 건너뜀(이어받기)",
"imageCooldown": "음악 다운로드 직후라 유튜브 속도제한을 피하려고 {{secs}}초 대기합니다…",
"imageRetry": "{{idx}}번 사진 재시도 {{attempt}}회차 (HTTP {{code}}) — {{secs}}초 후 다시 시도",
"baseDownload": "베이스 리소스팩 다운로드: {{path}}",
"baseUrl": " URL: {{url}}",
"baseReceived": "베이스 리소스팩 받음 ({{kb}} KB)",
@@ -133,7 +135,8 @@
"baseDownloading": "베이스 리소스팩 다운로드 중",
"buildingWithBase": "베이스에 음악·사진 추가 중",
"buildingZip": "zip 빌드 중",
"installComplete": "설치 완료"
"installComplete": "설치 완료",
"imageRetry": "속도제한(HTTP {{code}}) — {{secs}}초 후 재시도"
},
"pack": {
"description": "음악퀴즈 리소스팩 - {{name}}"
@@ -145,6 +148,7 @@
"cancelledByUser": "사용자가 설치를 취소했습니다.",
"musicDownloadFailed": "{{idx}}번 노래 다운로드 실패: {{message}}",
"imageDownloadFailed": "{{idx}}번 사진 다운로드 실패: {{message}}",
"imageRateLimitHint": "유튜브가 IP를 잠시 속도제한(429)했습니다. 몇 분 뒤 다시 설치를 시도하면 이미 받은 사진은 건너뛰고 이어받습니다.",
"imageNormalizeFailed": "{{idx}}번 사진 정규화 실패: {{message}}",
"baseDownloadFailed": "베이스 리소스팩 다운로드 실패: {{message}}",
"ytdlpSignal": "yt-dlp 가 신호 {{signal}} 로 종료됨",

View File

@@ -1,6 +1,6 @@
{
"name": "minecraft-music-quiz-installer",
"version": "0.4.3",
"version": "0.4.4",
"description": "마인크래프트 음악퀴즈 간편설치기 + 관리 사이트",
"main": "dist/installer/main.js",
"scripts": {

View File

@@ -35,10 +35,16 @@ export function ytIdFromUrl(url: string): string {
* 5xx 게이트웨이 계열도 잠깐 뒤 다시 받으면 성공하는 경우가 많다.
*/
const TRANSIENT_CODES = new Set([408, 425, 429, 500, 502, 503, 504])
const MAX_RETRIES = 5
const MAX_RETRIES = 6
/** 백오프 상한(ms). Retry-After 헤더가 비정상적으로 커도 이 이상은 기다리지 않는다. */
const MAX_BACKOFF_MS = 60000
/**
* 재시도가 일어날 때 호출되는 훅. 상위(main)에서 로그/진행률로 표시해, 429 백오프
* 대기 중에도 화면이 멈춘 것처럼 보이지 않게 한다.
*/
export type ImageRetryHook = (info: { attempt: number; delayMs: number; code: number | null }) => void
/** Retry-After 헤더(초 또는 HTTP-date) → 대기 ms. 못 읽으면 null. */
function parseRetryAfter(h: string | string[] | undefined): number | null {
if (!h) return null
@@ -57,7 +63,7 @@ const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms
* 429/5xx 등 일시적 오류는 지수 백오프(+jitter, Retry-After 우선)로 최대
* MAX_RETRIES 회 재시도한다. 그 외 4xx 나 재시도 소진 시 reject.
*/
function fetchBuffer(url: string, redirects = 0, attempt = 0): Promise<Buffer> {
function fetchBuffer(url: string, redirects = 0, attempt = 0, onRetry?: ImageRetryHook): Promise<Buffer> {
return new Promise((resolve, reject) => {
if (redirects > 8) {
reject(new Error(t('common.tooManyRedirects')))
@@ -65,10 +71,11 @@ function fetchBuffer(url: string, redirects = 0, attempt = 0): Promise<Buffer> {
}
const target = new URL(url)
const lib = target.protocol === 'https:' ? https : http
const retryLater = (headerDelay: number | null): void => {
const retryLater = (headerDelay: number | null, code: number | null): void => {
const backoff = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** attempt) + Math.floor(Math.random() * 500)
const delay = headerDelay ?? backoff
sleep(delay).then(() => fetchBuffer(url, redirects, attempt + 1).then(resolve, reject))
try { onRetry?.({ attempt: attempt + 1, delayMs: delay, code }) } catch { /* noop */ }
sleep(delay).then(() => fetchBuffer(url, redirects, attempt + 1, onRetry).then(resolve, reject))
}
const req = lib.get(target, {
timeout: 30000,
@@ -77,13 +84,13 @@ function fetchBuffer(url: string, redirects = 0, attempt = 0): Promise<Buffer> {
const code = res.statusCode || 0
if (code >= 300 && code < 400 && res.headers.location) {
res.resume()
fetchBuffer(new URL(res.headers.location, target).toString(), redirects + 1, attempt)
fetchBuffer(new URL(res.headers.location, target).toString(), redirects + 1, attempt, onRetry)
.then(resolve, reject)
return
}
if (TRANSIENT_CODES.has(code) && attempt < MAX_RETRIES) {
res.resume()
retryLater(parseRetryAfter(res.headers['retry-after']))
retryLater(parseRetryAfter(res.headers['retry-after']), code)
return
}
if (code !== 200) {
@@ -98,7 +105,7 @@ function fetchBuffer(url: string, redirects = 0, attempt = 0): Promise<Buffer> {
req.on('error', (err) => {
// 연결 끊김/리셋 등 네트워크 오류도 몇 번은 재시도.
if (attempt < MAX_RETRIES) {
retryLater(null)
retryLater(null, null)
return
}
reject(err)
@@ -134,18 +141,18 @@ function decodeDataUrl(url: string): Buffer | null {
* 실패하면 `hqdefault.jpg` 로 폴백.
* - 그 외 URL 은 HTTP GET 으로 그대로 받음.
*/
export async function downloadImage(rawUrl: string): Promise<Buffer> {
export async function downloadImage(rawUrl: string, onRetry?: ImageRetryHook): Promise<Buffer> {
const dataBuf = decodeDataUrl(rawUrl)
if (dataBuf) return dataBuf
const ytId = ytIdFromUrl(rawUrl)
if (ytId) {
try {
return await fetchBuffer(`https://i.ytimg.com/vi/${ytId}/maxresdefault.jpg`)
return await fetchBuffer(`https://i.ytimg.com/vi/${ytId}/maxresdefault.jpg`, 0, 0, onRetry)
} catch {
return await fetchBuffer(`https://i.ytimg.com/vi/${ytId}/hqdefault.jpg`)
return await fetchBuffer(`https://i.ytimg.com/vi/${ytId}/hqdefault.jpg`, 0, 0, onRetry)
}
}
return fetchBuffer(rawUrl)
return fetchBuffer(rawUrl, 0, 0, onRetry)
}
/**

View File

@@ -77,6 +77,13 @@ function pickMusicConcurrency(): number {
*/
const MUSIC_START_STAGGER_MS = 2000
/** 사진(썸네일) 다운로드 사이 최소 간격(ms). i.ytimg.com 429(rate limit) 를 유발하지 않도록 순차 요청을 살짝 벌린다. */
const IMAGE_REQUEST_INTERVAL_MS = 800
/** 음악(yt-dlp) 단계 직후엔 유튜브가 IP 를 일시 throttle 할 수 있어, 사진 단계 전 잠깐 쉬어 429 를 피한다. */
const IMAGE_PHASE_COOLDOWN_MS = 4000
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
/** start-gate. 여러 worker 가 동시에 acquire 해도 직렬화되어 순차 통과. */
let musicStartChain: Promise<void> = Promise.resolve()
let nextMusicStartAt = 0
@@ -503,6 +510,13 @@ ipcMain.handle('rp:install:start', async (): Promise<{ resourcepackPath: string
const paintingDir = path.join(tempRoot, 'painting')
await fsp.mkdir(paintingDir, { recursive: true })
sendLog(t('log.imageStart', { total: imageTotal }))
// 음악(yt-dlp) 단계에서 유튜브를 많이 두드렸다면 IP throttle 이 남아 사진 첫 장부터
// 429 가 날 수 있다. 다운로드할 사진이 실제로 있고 직전에 음악을 받았다면 잠깐 쉰다.
if (imageTotal > 0 && musicTotal > 0) {
sendLog(t('log.imageCooldown', { secs: Math.round(IMAGE_PHASE_COOLDOWN_MS / 1000) }))
await sleep(IMAGE_PHASE_COOLDOWN_MS)
}
let imageRequests = 0
for (let i = 0; i < imageTotal; i++) {
throwIfCancelled()
const entry = pack.list.images[i]
@@ -514,16 +528,30 @@ ipcMain.handle('rp:install:start', async (): Promise<{ resourcepackPath: string
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 100, status: 'done' })
continue
}
// 실제 네트워크 요청을 하는 사진들 사이에만 간격을 둔다(건너뛴 것 사이엔 대기 없음).
if (imageRequests > 0) await sleep(IMAGE_REQUEST_INTERVAL_MS + Math.floor(Math.random() * 300))
imageRequests++
sendLog(t('log.imageDownloading', { idx }))
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 10, status: 'running' })
let buf: Buffer
try {
buf = await downloadImage(entry.url)
buf = await downloadImage(entry.url, (info) => {
const secs = Math.ceil(info.delayMs / 1000)
sendLog(t('log.imageRetry', { idx, attempt: info.attempt, code: info.code ?? '-', secs }))
sendProgress({
phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 10, status: 'running',
message: t('progress.imageRetry', { code: info.code ?? '-', secs })
})
})
} catch (err) {
// 부분 생성됐을 수 있는 커버 파일 제거(이어받기 시 완성본 오인 방지).
await fsp.rm(coverPath, { force: true }).catch(() => {})
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 0, status: 'error', message: (err as Error).message })
throw new Error(t('errors.imageDownloadFailed', { idx, message: (err as Error).message }))
const rawMsg = (err as Error).message
// 429(rate limit)는 유튜브가 IP 를 일시 차단한 것. 잠시 뒤 다시 시도하면
// 이미 받은 사진은 건너뛰고 이어받는다는 안내를 덧붙인다.
const msg = /429/.test(rawMsg) ? `${rawMsg}${t('errors.imageRateLimitHint')}` : rawMsg
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 0, status: 'error', message: msg })
throw new Error(t('errors.imageDownloadFailed', { idx, message: msg }))
}
throwIfCancelled()
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 60, status: 'running' })