연령제한 음원 받기: 429 쉼을 시작할 때만 보던 것 — 곡마다 로그인 페이지 요청과 다운로드 직전에도 <쿠키 파일>.cooldown을 보고, 걸리면(RateLimited) 실패 곡으로 세지 않고 작업을 바로 끝냄. 서버나 다른 수집 작업이 도중에 429를 받아도 요청이 계속 나가던 것. 회귀 테스트(도중 쉼 → 다운로드·다음 곡 없음)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-03 22:43:05 +09:00
parent ba6f14f38c
commit 8a52fd3b68
2 changed files with 28 additions and 3 deletions

View File

@@ -10,7 +10,7 @@ import { loudnessGain, quizSong } from '../songs/quiz';
import { tempDbPath } from '../test-utils';
import { cookieForms, collectAgeAudio } from './age-audio';
import { Catalog } from './catalog';
import { cooldownUntil } from './cookie-jar';
import { cooldownUntil, startCooldown } from './cookie-jar';
import { Blocked } from './charts';
import { collectLoudness, isAgeGated } from './loudness';
@@ -138,4 +138,23 @@ describe('연령제한 곡', () => {
expect(downloads).toBe(1);
expect(db.query<{ status: string; log: string }, []>("SELECT status, log FROM collect_jobs WHERE kind = 'age-audio' ORDER BY id DESC").get()).toMatchObject({ status: 'failed', log: expect.stringContaining('429') });
});
test('a pause started elsewhere while it runs stops it before the next signed-in request or download', async () => {
const { db, dir } = setup(3);
db.query('UPDATE songs SET age_video = youtube_id').run();
const cookiePath = join(mkdtempSync(join(tmpdir(), 'mq-age-')), 'ytm_cookie.txt');
writeFileSync(cookiePath, 'SAPISID=a; __Secure-1PSID=b');
let pages = 0;
let downloads = 0;
// the first page is read, then the server gets a 429: neither its download nor the next songs go out
const r = await collectAgeAudio(db, dir, {
delayMs: 0,
cookiePath,
fetchSignedIn: async () => (pages++, startCooldown(cookiePath), ok(-9)),
download: async (_, out) => (downloads++, writeFileSync(out, 'x')),
});
expect([pages, downloads, r.downloaded, r.failed]).toEqual([1, 0, 0, 0]);
expect(db.query<{ n: number }, []>("SELECT COUNT(*) n FROM signals WHERE kind = 'yt_audio_tried'").get()!.n).toBe(0);
expect(db.query<{ status: string; log: string }, []>("SELECT status, log FROM collect_jobs WHERE kind = 'age-audio' ORDER BY id DESC").get()).toMatchObject({ status: 'failed', log: expect.stringContaining('429') });
});
});

View File

@@ -127,7 +127,11 @@ export async function collectAgeAudio(db: Database, dir: string, opts: AgeAudioO
// 2. download with the adult-verified account (not during a 429 pause; a block here starts one — cookie-jar.ts)
// (tests that inject both without a cookie path touch no cookie file)
const path = opts.fetchSignedIn && opts.download ? opts.cookiePath : (opts.cookiePath ?? process.env.YT_COOKIE_PATH ?? '/home/claude/.config/music_quiz/ytm_cookie.txt');
if (path && cooldownUntil(path) > Date.now()) throw new RateLimited(cooldownUntil(path));
// checked before every signed-in request: the server or another collector may get a 429 while this runs
const waitOut = () => {
if (path && cooldownUntil(path) > Date.now()) throw new RateLimited(cooldownUntil(path));
};
waitOut();
const todo = pending();
job.progress(done, recheck.length + todo.length);
let fetchSignedIn = opts.fetchSignedIn;
@@ -142,6 +146,7 @@ export async function collectAgeAudio(db: Database, dir: string, opts: AgeAudioO
}
for (const s of todo) {
try {
waitOut();
const page = await fetchSignedIn!(s.youtube_id);
if (isAgeGated(page)) throw new CookieProblem('쿠키 계정으로도 성인 인증 페이지가 나와요(쿠키가 만료됐거나 성인 인증이 안 된 계정)');
// the anonymous page of an age-restricted video has no loudness / heatmap: take them from this one
@@ -149,13 +154,14 @@ export async function collectAgeAudio(db: Database, dir: string, opts: AgeAudioO
const sec = s.highlight_source === 'admin' || s.highlight_source === 'heatmap' ? null : pickHighlight(parseHeatmap(page));
if (sec !== null)
db.query("UPDATE songs SET highlight_sec = ?, highlight_source = 'heatmap', updated_at = ? WHERE id = ? AND COALESCE(highlight_source, '') <> 'admin'").run(sec, Date.now(), s.id);
waitOut();
await download!(s.youtube_id, audioFile(dir, s.youtube_id));
db.query('UPDATE songs SET audio_video = ?, updated_at = ? WHERE id = ? AND youtube_id = ?').run(s.youtube_id, Date.now(), s.id, s.youtube_id);
stats.downloaded++;
job.log(`${s.youtube_id} downloaded`);
} catch (e) {
if (e instanceof Blocked && path) startCooldown(path);
if (e instanceof Blocked || e instanceof CookieProblem) throw e;
if (e instanceof Blocked || e instanceof CookieProblem || e instanceof RateLimited) throw e;
stats.failed++;
cat.signal(s.id, 'yt_audio_tried', Date.now());
job.log(`${s.youtube_id} download failed: ${(e as Error).message}`);