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>
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user