// "NEW SINCE LAST VISIT" (lane posts-library): when the operator pressed Mark // seen on a topic. UMTOOL'S OWN STATE, beside the projects, never a file of // the library (umtool writes none of those): // // REPORTS_ROOT/.umtool/posts-library.json // { format: "umtool-posts-library", version: 1, // libraries: { "": { topics: { "": { seenAt, previous? } } } } } // // MOVED ONLY BY AN EXPLICIT PRESS (the page's Mark seen, `umtool library // seen`): opening the page moves nothing, so "new" stays new until the // operator says he has seen it, on whichever device. `previous` is the mark it // replaced. // // SEVERAL PROCESSES WRITE IT (the app, `umtool library seen`): a write is a // read-modify-rename under a LOCK FILE beside it (`posts-library.json.lock`, // made exclusively; one left by a process that died is taken over after 10 s), // and serialised in-process too, so two marks at once are both kept. Every // write is a whole file to a temp name and a rename. A file that does not // parse is never overwritten. // // Plain ESM. import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SEEN_FORMAT = "umtool-posts-library"; const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; const TOPIC = /^[a-z0-9][a-z0-9-]{0,119}$/; export function seenFile(reportsRoot) { return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "posts-library.json"); } const isIso = (v) => typeof v === "string" && Number.isFinite(Date.parse(v)); function clean(raw) { const libraries = {}; const src = raw && typeof raw === "object" && raw.libraries && typeof raw.libraries === "object" ? raw.libraries : {}; for (const [slug, lib] of Object.entries(src)) { if (!SLUG.test(slug) || !lib || typeof lib !== "object") continue; const topics = {}; for (const [topic, t] of Object.entries(lib.topics && typeof lib.topics === "object" ? lib.topics : {})) { if (!TOPIC.test(topic) || !t || !isIso(t.seenAt)) continue; topics[topic] = { seenAt: t.seenAt, ...(isIso(t.previous) ? { previous: t.previous } : {}) }; } libraries[slug] = { topics }; } return libraries; } /** * Every mark: `{ libraries, error? }`. A missing file is empty; an unreadable one is empty with `error`. * @param {string} reportsRoot */ export async function readSeen(reportsRoot) { let text; try { text = await readFile(/* turbopackIgnore: true */ seenFile(reportsRoot), "utf8"); } catch (err) { if (err?.code === "ENOENT") return { libraries: {} }; return { libraries: {}, error: `posts-library.json cannot be read: ${err?.message ?? err}` }; } try { return { libraries: clean(JSON.parse(text)) }; } catch { return { libraries: {}, error: "posts-library.json does not parse: nothing is marked seen until it is fixed" }; } } /** A library's marks: { [topicId]: seenAt }. */ export async function seenOf(reportsRoot, slug) { const { libraries } = await readSeen(reportsRoot); return Object.fromEntries(Object.entries(libraries[slug]?.topics ?? {}).map(([t, v]) => [t, v.seenAt])); } let chain = Promise.resolve(); export const SEEN_LOCK_STALE_MS = 10_000; const LOCK_WAIT_MS = 5_000; /** Run `fn` holding the state file's lock (an exclusive create; a stale one is taken over). */ async function locked(file, fn) { const lock = `${file}.lock`; await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); const deadline = Date.now() + LOCK_WAIT_MS; for (;;) { try { const fh = await open(/* turbopackIgnore: true */ lock, "wx"); await fh.writeFile(`${process.pid}\n`); await fh.close(); break; } catch (err) { if (err?.code !== "EEXIST") throw err; const st = await stat(/* turbopackIgnore: true */ lock).catch(() => null); if (st && Date.now() - st.mtimeMs > SEEN_LOCK_STALE_MS) { await rm(/* turbopackIgnore: true */ lock, { force: true }); continue; } if (Date.now() > deadline) throw new Error("posts-library.json is being written by another umtool process: nothing was marked, press again"); await new Promise((r) => setTimeout(r, 25)); } } try { return await fn(); } finally { await rm(/* turbopackIgnore: true */ lock, { force: true }).catch(() => {}); } } /** One read-modify-write of the state file, under its lock and in turn. `change(lib)` edits the library's entry and answers the result. */ function mutate(reportsRoot, slug, change) { const run = () => locked(seenFile(reportsRoot), async () => { const current = await readSeen(reportsRoot); if (current.error) throw new Error(current.error); const lib = current.libraries[slug] ?? { topics: {} }; const result = change(lib); current.libraries[slug] = lib; const file = seenFile(reportsRoot); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify({ format: SEEN_FORMAT, version: 1, libraries: current.libraries }, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); } catch (err) { await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); throw err; } return result; }); const p = chain.then(run, run); chain = p.catch(() => {}); return p; } /** * Mark topics of a library seen now. Refuses (throws) an ill-shaped name, and * a file that is there and does not parse. * @param {string} reportsRoot * @param {{ slug: string, topics: string[], now?: number }} o * @returns {Promise<{ slug: string, topics: Record }>} */ export function markSeen(reportsRoot, { slug, topics, now = Date.now() }) { if (!SLUG.test(String(slug))) return Promise.reject(new Error(`"${slug}" is not a library's slug`)); if (!Array.isArray(topics) || topics.length === 0 || !topics.every((t) => TOPIC.test(String(t)))) return Promise.reject(new Error("Mark seen needs the topic ids to mark")); return mutate(reportsRoot, slug, (lib) => { const seenAt = new Date(now).toISOString(); const marked = {}; for (const t of topics) { const was = lib.topics[t]?.seenAt; lib.topics[t] = { seenAt, ...(was ? { previous: was } : {}) }; marked[t] = lib.topics[t]; } return { slug, topics: marked }; }); } /** * TOPICS WERE MERGED IN THE EDITOR (lane x-trending-publish): their marks become one. The topic that stays keeps * the EARLIEST of the marks the merged topics had, so nothing a mark had not covered is hidden as seen; a topic * that stays and was never marked stays unmarked (all of it new). The merged topics' marks are dropped. Writes * nothing when there is nothing to change. * @param {string} reportsRoot * @param {{ slug: string, into: string, from: string[] }} o * @returns {Promise<{ slug: string, into: string, seenAt: string | null, changed: boolean }>} */ export async function mergeSeen(reportsRoot, { slug, into, from }) { if (!SLUG.test(String(slug))) throw new Error(`"${slug}" is not a library's slug`); if (!TOPIC.test(String(into)) || !Array.isArray(from) || !from.every((t) => TOPIC.test(String(t)))) throw new Error("a merge names the topic that stays and the topics merged into it"); const current = (await seenOf(reportsRoot, slug)) ?? {}; if (!from.some((t) => current[t]) ) return { slug, into, seenAt: current[into] ?? null, changed: false }; return mutate(reportsRoot, slug, (lib) => { const mine = lib.topics[into]?.seenAt; const marks = [mine, ...from.map((t) => lib.topics[t]?.seenAt)].filter(Boolean).sort(); for (const t of from) delete lib.topics[t]; if (mine && marks[0] !== mine) lib.topics[into] = { seenAt: marks[0], previous: mine }; return { slug, into, seenAt: lib.topics[into]?.seenAt ?? null, changed: true }; }); }