원곡 찾기 진행 상황 자세히: 상태 배지(찾는 중·검색 실패 대기·N분째 진행 없음·프로세스 없음), 숫자 카드(처리·남은 곡·최근 10분 속도·지난/남은 시간·끝 예상·마지막 처리), 검색 방법, 결과 비율 막대, 방금 처리한 곡 8개, 작업 기록(쉬운 말), 지난 작업, 전체 확정 비율·다음 자동 실행. 끝 예상은 최근 10분 속도로, 마감(--deadline)은 시작 로그에서 읽음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-19 22:09:45 +09:00
parent 8d4e32d737
commit 0c0b822adc
7 changed files with 341 additions and 45 deletions

View File

@@ -45,6 +45,8 @@ export async function matchYoutube(db: Database, ytm: Pick<YtMusic, 'searchSongs
const stats = { matched: 0, candidate: 0, none: 0 };
let tried = 0;
const src = opts.source ?? 'ytmusic';
// 관리자 → 원곡 찾기 reads the deadline back from this line
job.log(`start ${rows.length} songs via ${src}${opts.deadline !== undefined ? ` deadline ${new Date(opts.deadline).toISOString()}` : ''}`);
/**
* Writes the result only if the song is still open for automatic matching: an admin may have saved a video
* while we were waiting on the search. Returns whether the row was changed.

View File

@@ -32,22 +32,95 @@ export function reviewCounts(db: Database): Record<ReviewTab, number> {
return Object.fromEntries(REVIEW_TABS.map((t) => [t, r[t] ?? 0])) as Record<ReviewTab, number>;
}
/** The latest match-youtube run, with what it has decided so far. */
export function reviewJob(db: Database) {
const job = db
.query<{ id: number; status: string; done: number; total: number; started_at: number; finished_at: number | null }, []>(
"SELECT id, status, done, total, started_at, finished_at FROM collect_jobs WHERE kind = 'match-youtube' ORDER BY id DESC LIMIT 1",
)
.get();
const pidAlive = (pid: number) => {
try {
process.kill(pid, 0);
return true;
} catch (e) {
return (e as NodeJS.ErrnoException).code === 'EPERM'; // there, owned by someone else
}
};
/** Speed and ETA are taken over the last 10 minutes, so a slow start or a 60s retry wait fades out. */
export const RATE_WINDOW = 10 * 60_000;
/**
* The latest match-youtube run, in detail: what it decided so far, how fast it goes, when it should end,
* whether its process is still there, the last songs it looked at, its log, and the runs before it.
*/
export function reviewJob(db: Database, now = Date.now(), alive: (pid: number) => boolean = pidAlive) {
type JobRow = { id: number; status: string; done: number; total: number; started_at: number; finished_at: number | null };
const history = db
.query<JobRow, []>("SELECT id, status, done, total, started_at, finished_at FROM collect_jobs WHERE kind = 'match-youtube' ORDER BY id DESC LIMIT 6")
.all();
const job = history[0];
if (!job) return null;
const end = job.finished_at ?? Date.now() + 1;
const { pid, log } = db.query<{ pid: number | null; log: string }, [number]>('SELECT pid, log FROM collect_jobs WHERE id = ?').get(job.id)!;
const running = job.status === 'running';
const end = job.finished_at ?? now + 1;
const tried = `t.kind LIKE 'yt_tried_%' AND t.value >= ? AND t.value <= ?`;
const r = db
.query<{ matched: number | null; candidate: number | null; none: number | null }, [number, number]>(
`SELECT SUM(s.youtube_status = 'matched') matched, SUM(s.youtube_status = 'candidate') candidate, SUM(s.youtube_status = 'none') none
FROM songs s WHERE s.deleted_at IS NULL AND EXISTS (SELECT 1 FROM signals t WHERE t.song_id = s.id AND t.kind LIKE 'yt_tried_%' AND t.value >= ? AND t.value <= ?)`,
FROM songs s WHERE s.deleted_at IS NULL AND EXISTS (SELECT 1 FROM signals t WHERE t.song_id = s.id AND ${tried})`,
)
.get(job.started_at, end)!;
return { ...job, result: { matched: r.matched ?? 0, candidate: r.candidate ?? 0, none: r.none ?? 0 } };
const recent = db
.query<
{ id: number; title: string; artist: string; youtube_status: string; youtube_source: string | null; youtube_title: string | null; youtube_channel: string | null; kind: string; at: number },
[number, number]
>(
`SELECT s.id, s.title, s.artist, s.youtube_status, s.youtube_source, s.youtube_title, s.youtube_channel, t.kind, t.value at
FROM signals t JOIN songs s ON s.id = t.song_id WHERE ${tried} ORDER BY t.value DESC LIMIT 8`,
)
.all(job.started_at, end);
// speed: songs per minute over the last 10 minutes of the run (the whole run while it is younger than that)
const runEnd = running ? now : end;
const from = Math.max(job.started_at, runEnd - RATE_WINDOW);
const inWindow = db.query<{ n: number }, [number, number]>(`SELECT COUNT(*) n FROM signals t WHERE ${tried}`).get(from, end)!.n;
const perMin = runEnd > from ? (inWindow / (runEnd - from)) * 60_000 : 0;
const left = Math.max(0, job.total - job.done);
const lines = parseLog(log, job.started_at);
const deadline = lines.reduce<number | null>((d, l) => (l.deadline ? l.deadline : d), null);
const { kind } = recent[0] ?? { kind: '' };
return {
...job,
result: { matched: r.matched ?? 0, candidate: r.candidate ?? 0, none: r.none ?? 0 },
/** Search used: ytmusic (with the cookie) or the youtube fallback. */
source: kind ? kind.slice('yt_tried_'.length) : null,
lastAt: recent[0]?.at ?? null,
perMin: Math.round(perMin * 10) / 10,
eta: running && perMin > 0 && left > 0 ? Math.round(now + (left / perMin) * 60_000) : null,
/** Running but its process is gone (container restarted, killed): the row is stale. */
alive: running && pid ? alive(pid) : null,
deadline,
recent: recent.map(({ kind: _, ...x }) => x),
log: lines.slice(-12).map(({ at, text }) => ({ at, text })),
history: history.slice(1),
};
}
/**
* Job log lines are "HH:MM:SS text" in UTC; turn the time back into epoch ms (the run may cross midnight).
* The matcher's start line carries its deadline ("deadline 2026-10-20T07:55:00.000Z").
*/
export function parseLog(log: string, startedAt: number) {
const out: { at: number; text: string; deadline?: number }[] = [];
let day = Math.floor(startedAt / 86400_000) * 86400_000;
let prev = startedAt - 60_000;
for (const line of log.split('\n')) {
const m = /^(\d\d):(\d\d):(\d\d) (.*)$/.exec(line);
if (!m) continue;
let at = day + ((+m[1]! * 60 + +m[2]!) * 60 + +m[3]!) * 1000;
if (at < prev - 3600_000) {
day += 86400_000;
at += 86400_000;
}
prev = at;
const d = / deadline (\S+)/.exec(m[4]!);
out.push({ at, text: m[4]!, ...(d && Number.isFinite(Date.parse(d[1]!)) ? { deadline: Date.parse(d[1]!) } : {}) });
}
return out;
}
export interface ReviewRow {

View File

@@ -3,6 +3,7 @@ import { afterEach, expect, test } from 'bun:test';
import { Catalog } from './collector/catalog';
import { matchYoutube } from './collector/match-youtube';
import { quizSong } from './songs/quiz';
import { parseLog, reviewJob } from './songs/youtube-review';
import { api, boot, discordLogin, TEST_SUPERADMINS } from './test-utils';
let s: ReturnType<typeof boot>;
@@ -77,3 +78,36 @@ test('원곡 찾기 tabs and actions; admin choices stick across matcher runs',
expect(audit).toEqual(expect.arrayContaining(['song.youtube.unconfirm', 'song.youtube.none', 'song.update']));
expect((await call('/youtube?tab=nope')).body.tab).toBe('candidate');
});
test('원곡 찾기 진행 상황: speed over the last 10 minutes, ETA, stale process, last songs, log across midnight, earlier runs', () => {
s = boot();
const c = new Catalog(s.db);
const ids = Array.from({ length: 30 }, (_, i) => c.upsert({ title: `곡${i}`, artists: [{ name: '가수' }], source: 't', ref: String(i) })[0]!);
const day = Date.UTC(2026, 9, 19);
const start = day + 23 * 3600_000 + 50 * 60_000; // 23:50 UTC
s.db.query("INSERT INTO collect_jobs (kind, status, done, total, started_at, finished_at) VALUES ('match-youtube', 'done', 5, 5, ?, ?)").run(start - 86400_000, start - 86000_000);
const log = ['23:50:00 start 100 songs via ytmusic deadline 2026-10-20T07:55:00.000Z', '23:59:59 youtube 50/100 matched 40 candidate 5 none 5', '00:01:00 search failed (429), waiting 60s', ''].join('\n');
const job = Number(s.db.query("INSERT INTO collect_jobs (kind, status, done, total, started_at, pid, log) VALUES ('match-youtube', 'running', 30, 100, ?, 4242, ?)").run(start, log).lastInsertRowid);
// 20 songs in the first 10 minutes, 10 in the last 10: the ETA follows the recent pace (1 song a minute)
const now = start + 20 * 60_000;
ids.forEach((id, i) => {
const at = i < 20 ? start + i * 30_000 : now - 10 * 60_000 + (i - 19) * 60_000 - 1;
s.db.query("INSERT INTO signals (song_id, kind, value, fetched_at) VALUES (?, 'yt_tried_ytmusic', ?, ?)").run(id, at, at);
});
s.db.query("UPDATE songs SET youtube_status = 'matched', youtube_id = 'v', youtube_title = '영상' WHERE id = ?").run(ids[29]!);
const alive: number[] = [];
const r = reviewJob(s.db, now, (pid) => (alive.push(pid), false))!;
expect(r).toMatchObject({ id: job, status: 'running', source: 'ytmusic', alive: false, lastAt: now - 1, deadline: Date.parse('2026-10-20T07:55:00.000Z') });
expect(alive).toEqual([4242]);
expect(r.perMin).toBe(1);
expect(r.eta).toBe(now + 70 * 60_000);
expect(r.result).toEqual({ matched: 1, candidate: 0, none: 29 });
expect(r.recent.map((x) => x.id)).toEqual(ids.slice(22).reverse());
expect(r.recent[0]).toMatchObject({ youtube_status: 'matched', youtube_title: '영상' });
expect(r.log.map((l) => l.at)).toEqual([start, day + 86400_000 - 1000, day + 86400_000 + 60_000]);
expect(r.history).toHaveLength(1);
// a finished run: no ETA, no process check
s.db.query("UPDATE collect_jobs SET status = 'done', finished_at = ? WHERE id = ?").run(now, job);
expect(reviewJob(s.db, now + 3600_000, () => true)).toMatchObject({ eta: null, alive: null, perMin: 1 });
expect(parseLog('garbage\n10:00:00 hi', Date.UTC(2026, 0, 1, 9))).toEqual([{ at: Date.UTC(2026, 0, 1, 10), text: 'hi' }]);
});