import { CASE_FILES, type FindingRow } from "yt-dlp-transcript-common/lib/research/caseTypes"; import { readFindings as readAt } from "yt-dlp-transcript-common/lib/research/caseStore-server"; import { assertNoPrivateNames } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; import { rowGateText } from "yt-dlp-transcript-common/lib/research/casePipeline"; import { CaseError, labelOf, privateHashes, stageDir, stageFile, withFileLock, writeWhole } from "./case-stage-files"; // --------------------------------------------------------------------------- // FINDINGS, AS VERIFY CHANGES THEM (release 38 lane C, stage 7), on lane A's // store: rows read by its readFindings (every line checked), and the file // rewritten whole under ITS lock (`findings.jsonl.lock`, the one appendFindings // and writeFindings hold) and ITS privacy gate (rowGateText → PrivacyBlocked, // counts and row ids, never the name). Read-change-write happens inside the // one lock, so an append landing meanwhile is never lost. A file with a line // that does not check is never rewritten (it would be dropped): 409, the line // named. // --------------------------------------------------------------------------- export type FindingsRead = { rows: FindingRow[]; bad: { line: number; error: string }[] }; export async function readFindings(caseId: string): Promise { const r = await readAt(await stageDir(caseId)); return { rows: r.rows, bad: r.invalid.map((x) => ({ line: x.line, error: x.errors.join("; ") })) }; } /** Read every row, let `fn` change them in place, gate them, and write the file whole. */ export async function mutateFindings(caseId: string, fn: (rows: FindingRow[]) => T | Promise): Promise<{ rows: FindingRow[]; result: T }> { const dir = await stageDir(caseId); const hashes = await privateHashes(caseId); const file = stageFile(dir, CASE_FILES.findings); return withFileLock(file, async () => { const r = await readAt(dir); if (r.invalid.length) { const b = r.invalid[0]; throw new CaseError(`${labelOf(caseId, CASE_FILES.findings)} line ${b.line} does not check (${b.errors.join("; ")}); it is never rewritten until it is fixed`, 409); } const result = await fn(r.rows); assertNoPrivateNames("the findings", r.rows.map((x) => ({ id: x.row, text: rowGateText(x) })), hashes); await writeWhole(file, r.rows.map((x) => JSON.stringify(x)).join("\n") + (r.rows.length ? "\n" : "")); return { rows: r.rows, result }; }); } /** One row, or a 404. */ export function rowOf(rows: FindingRow[], row: string): FindingRow { const hit = rows.find((r) => r.row === row); if (!hit) throw new CaseError(`no finding ${row}`, 404); return hit; }