원곡 찾기 진행 상황 자세히: 상태 배지(찾는 중·검색 실패 대기·N분째 진행 없음·프로세스 없음), 숫자 카드(처리·남은 곡·최근 10분 속도·지난/남은 시간·끝 예상·마지막 처리), 검색 방법, 결과 비율 막대, 방금 처리한 곡 8개, 작업 기록(쉬운 말), 지난 작업, 전체 확정 비율·다음 자동 실행. 끝 예상은 최근 10분 속도로, 마감(--deadline)은 시작 로그에서 읽음
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user