Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 2610ce80b706f7839c8cd59260169be5ad32f265
parent 22e2ca7180f2b936511c42adb202591a6bf76f8b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 14:24:56 -0400

forum: two positions — the catch-up keeps its own resume point and never moves the history's; Full re-walk; retry after a block

A forum thread's posts-state.json gains `forum` (lib/forumWalk.ts): the catch-up's mark and resume point and the
history walk's page, re-derived from the archived posts' pages every run, so an overwritten position heals. All-held
pages are stepped past uncounted. The channel page gets Fetch posts + Full re-walk (confirm with the page count and
time), a status line, and Retry after a block (settings.social.xenforo.retryOnBlock); fetch-posts takes
retryOnBlock. FORUM_FIXTURE_DIR lets the e2e server read synthetic saved pages.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MOPERATING.md | 12++++++++++++
Mcommon/bin/archilyzer.ts | 2+-
Mcommon/bin/fetch-posts.ts | 25++++++++++++++++++++++++-
Acommon/controller/fetchForumPosts.test.ts | 195+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchPosts.ts | 209++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/lib/envVars.ts | 1+
Acommon/lib/forumWalk.test.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/forumWalk.ts | 211+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/posts-server.ts | 21+++++++++++++++------
Mcommon/lib/settingsDocs.ts | 2++
Mcommon/lib/settingsSchema.ts | 16++++++++++++++--
Acommon/social/__fixtures__/fakeForumThread.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/fetchers.ts | 15++++++++++++++-
Acommon/social/forumFixtureLoader.ts | 44++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xCookieSource.ts | 16++++++++++++++++
Mcommon/social/xenforoFetcher.test.ts | 172++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/social/xenforoFetcher.ts | 278+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Meditor/CHANGELOG.md | 1+
Meditor/app/api/ops/fetch-posts/route.ts | 25++++++++++++++++++++++---
Meditor/app/channels/[slug]/components/SocialChannelPanel.tsx | 191++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Meditor/app/channels/[slug]/page.tsx | 33+++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/socialActions.ts | 50+++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/app/jobs/jobReplayRegistry.ts | 4++++
Meditor/app/settings/xSessionActions.ts | 8+++++---
Aeditor/e2e/forum-resume.spec.ts | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/package.json | 4++--
Mscripts/archilyzer-ops.mjs | 7++++++-
27 files changed, 1695 insertions(+), 166 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -140,12 +140,24 @@ pnpm ops wayback-import --json '{"slug":"example-pages","year":"2014","show":"no pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}' pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait pnpm ops fetch-posts --json '{"slug":"example-x","older":true}' --wait +pnpm ops fetch-posts --json '{"slug":"example-forum-thread","pages":20,"retryOnBlock":true}' --wait pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait ``` - An X, Bluesky or XenForo URL makes a social channel (its handle derived from the URL). `"older": true` walks back below the oldest archived post and resumes from its saved place; `"full": true` re-walks the timeline. - `capture-posts` saves a screenshot and the attached media of named posts (and a linked X Article). +- A **forum thread** keeps two positions (`posts-state.json` `forum`): **Fetch posts** catches up from the last page + to the newest held post, then continues the history from where it stopped, down to page 1 — `"pages": N` caps + the pages that hold anything new (an all-held page is stepped past uncounted), and a capped catch-up never moves + the history position. **Full re-walk** (`"full": true`) re-reads every page, the last to page 1: edited posts are + updated, posts no page shows any more are counted in the log (kept, not marked). The channel page's status line + says where both stand (`pages read 2338–2600 of 2600 · history to page 1 remaining: 2337 pages (~9.7 h)`). The + history position is re-derived from the archived posts' pages every run, so a lost one heals. +- A browser check that will not clear, or a refusal (403/429), stops a forum walk. `"retryOnBlock": {"minutes": 30, + "max": 12}` waits it out and runs again (max tries in all; never a captcha or a login); the channel page's + **Retry after a block** sets the Fetch posts button's default (`settings.social.xenforo.retryOnBlock`), and + `"retryOnBlock": true` uses it from `pnpm ops`. - Forum pages saved from a browser: `pnpm archilyzer posts import-html <slug> <file-or-dir> --dry-run`. - Which archived posts were deleted at the source: `pnpm archilyzer posts check --slug <slug>`. diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -833,7 +833,7 @@ export const COMMANDS: Command[] = [ script(["duplicates"], "duplicate-shorts.ts", "[--threshold N] [--all-durations] [--blocking title|duration|both] [--near F] [--tolerance N] … on-demand duplicate detection (after index + stats)", 8192), script(["posts", "fetch"], "fetch-posts.ts", - "--slug <channel> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages)"), + "--slug <channel> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M] fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-*: wait out a challenge or refusal page and run again)"), { path: ["posts", "import-html"], usage: diff --git a/common/bin/fetch-posts.ts b/common/bin/fetch-posts.ts @@ -3,11 +3,19 @@ // // pnpm --filter yt-dlp-transcript-common exec tsx bin/fetch-posts.ts \ // --slug <channel-slug> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] +// [--retry-on-block | --retry-minutes N --retry-tries M] // // --pages caps how many pages one run reads, for a source read page by page (a // forum thread: its latest N pages, newest first; the next run continues where // this one stopped). // +// A forum thread keeps two positions (lib/forumWalk.ts): a run catches up from +// the last page, then continues the history where it stopped. +// +// --retry-minutes N --retry-tries M: a challenge or refusal page stops the +// walk; wait N minutes and run again, M tries in all. --retry-on-block uses +// settings.social.xenforo.retryOnBlock (nothing when unset). +// // --full re-walks the account's whole history instead of stopping at the // stored watermark. New posts are still deduped against the posts-archive, so // it repairs a gap rather than creating duplicates. @@ -25,12 +33,13 @@ import { getPaths } from "../lib/paths"; import { getSettings } from "../lib/settings"; import { fetchPosts } from "../controller/fetchPosts"; import { parseFlags } from "./_parseFlags"; +import { retryOnBlockProblem, type RetryOnBlock } from "../lib/forumWalk"; const flags = parseFlags(process.argv.slice(2)); const slug = flags.slug; if (!slug) { console.error( - "Usage: fetch-posts.ts --slug <channel-slug> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N]", + "Usage: fetch-posts.ts --slug <channel-slug> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M]", ); process.exit(2); } @@ -47,6 +56,19 @@ const pages = ? Math.floor(pagesRaw) : undefined; +let retryOnBlock: RetryOnBlock | undefined; +if (flags["retry-minutes"] !== undefined || flags["retry-tries"] !== undefined) { + retryOnBlock = { minutes: Number(flags["retry-minutes"]), max: Number(flags["retry-tries"]) }; + const problem = retryOnBlockProblem(retryOnBlock); + if (problem) { + console.error(`${problem} (--retry-minutes and --retry-tries go together)`); + process.exit(2); + } +} else if (flags["retry-on-block"] === "true") { + retryOnBlock = getSettings().social.xenforo?.retryOnBlock; + if (!retryOnBlock) console.log("No retry after a block is set (settings.social.xenforo.retryOnBlock); a block stops the run."); +} + fetchPosts({ paths: getPaths(), slug, @@ -58,6 +80,7 @@ fetchPosts({ force: flags.force === "true", limit, pages, + ...(retryOnBlock ? { retryOnBlock } : {}), onLog: (line) => console.log(line), }) .then((result) => { diff --git a/common/controller/fetchForumPosts.test.ts b/common/controller/fetchForumPosts.test.ts @@ -0,0 +1,195 @@ +// fetchPosts over a FORUM THREAD (release 37 lane G), end to end through the +// real XenForo fetcher reading SYNTHETIC saved pages (FORUM_FIXTURE_DIR, +// social/forumFixtureLoader.ts): no browser, no network. The two positions in +// posts-state.json, an old single cursor migrating, the full re-walk's edits, +// and the retry on a block over a fake clock. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchForumPosts.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetchforum-")); +const FIXTURES = path.join(ROOT, "forum-fixture"); +// getPaths() is resolved lazily and cached: set before the first call. +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +process.env.FORUM_FIXTURE_DIR = FIXTURES; + +const { THREAD_URL, CHALLENGE_PAGE } = await import("../social/__fixtures__/xenforoPages"); +const { FakeForumThread, FAKE_THREAD_ID } = await import("../social/__fixtures__/fakeForumThread"); +const { fetchPosts, sleepOrStop } = await import("./fetchPosts"); +const { readAllPosts, readPostFetchState, readSeenPostIds, writePostFetchState } = await import("../lib/posts-server"); +const { getPaths } = await import("../lib/paths"); + +let n = 0; +async function channel(): Promise<{ slug: string; root: string }> { + const slug = `forum-${++n}`; + const root = path.join(ROOT, "transcripts", "channels", slug); + await mkdir(root, { recursive: true }); + await writeFile( + path.join(root, "config.json"), + JSON.stringify({ + handling: "transcribe", + sourceKind: "social", + platform: "xenforo", + postFetcher: "xenforo-thread", + socialHandle: "the-teapot-collectors-thread.4242", + name: "Teapot thread", + url: THREAD_URL, + }), + ); + return { slug, root }; +} + +async function run(slug: string, over: Partial<Parameters<typeof fetchPosts>[0]> = {}) { + const log: string[] = []; + const result = await fetchPosts({ paths: getPaths(), slug, settings: {}, onLog: (l) => log.push(l), ...over }); + return { result, log: log.join("\n") }; +} + +test("a capped catch-up leaves the history position alone; posts-state.json keeps both, and no cursor", async () => { + const { slug, root } = await channel(); + const t = new FakeForumThread(30); // 10 pages + await t.writeTo(FIXTURES); + const first = await run(slug, { pages: 5 }); + assert.equal(first.result.ok, true); + let state = await readPostFetchState(root); + assert.equal(state?.cursor, undefined); + assert.deepEqual(state?.forum, { newestPage: 10, oldestPageReached: 6, historyPage: 5, newestPostId: "9030" }); + + t.add(9); + await t.writeTo(FIXTURES); + const capped = await run(slug, { pages: 2 }); + assert.match(capped.log, /caught up to page 10; history resumes at page 5/); + state = await readPostFetchState(root); + assert.equal(state?.forum?.historyPage, 5); + assert.equal(state?.forum?.catchUpPage, 11); + + const rest = await run(slug); + assert.equal(rest.result.complete, true); + state = await readPostFetchState(root); + assert.equal(state?.forum?.complete, true); + assert.equal(state?.forum?.catchUpPage, undefined); + assert.deepEqual([...(await readSeenPostIds(root))].sort(), t.ids().sort()); +}); + +test("an old state's single cursor migrates: read once as the history position, healed from the posts, then dropped", async () => { + const { slug, root } = await channel(); + const t = new FakeForumThread(30); + await t.writeTo(FIXTURES); + // An old fetch read pages 10–5 (posts 13–30) and then a capped catch-up + // overwrote the cursor with its own page (9). + await run(slug, { pages: 6 }); + await writePostFetchState(root, { lastFetchedAt: "2026-10-20T00:00:00.000Z", cursor: "9", lastFetchedCount: 3 }); + const res = await run(slug); + assert.match(res.log, /Read the old single resume point \(page 9\) as the history position\./); + assert.match(res.log, /history resumes at page 6/); + assert.equal(res.result.complete, true); + const state = await readPostFetchState(root); + assert.equal(state?.cursor, undefined, "the old cursor is gone"); + assert.equal(state?.forum?.complete, true); + assert.deepEqual([...(await readSeenPostIds(root))].sort(), t.ids().sort()); +}); + +test("a full re-walk re-reads every page and appends a newer record of an edited post", async () => { + const { slug, root } = await channel(); + const t = new FakeForumThread(9); + await t.writeTo(FIXTURES); + await run(slug); + // Post 9005 edited since; post 9002 deleted. + t.posts = t.posts.map((p) => (p.id === 9005 ? { ...p, body: "Edited words.", editedTs: p.ts + 60 } : p)); + t.remove([9002]); + await t.writeTo(FIXTURES); + const res = await run(slug, { full: true }); + assert.equal(res.result.ok, true); + assert.equal(res.result.updated, 1, "the edit, not the posts renumbered after the deletion"); + assert.match(res.log, /a full re-walk/); + assert.match(res.log, /1 archived post\(s\) were on no page of the thread .*: 9002\. Kept as archived/); + const posts = await readAllPosts(root); + const edited = posts.filter((p) => p.id === "9005"); + assert.match(edited[edited.length - 1].text, /Edited words\./); + assert.ok(posts.some((p) => p.id === "9002"), "a post no page shows is kept"); + const state = await readPostFetchState(root); + assert.equal(state?.forum?.complete, true); +}); + +test("retry on a block: a challenge page is waited out, `minutes` on the fake clock, and the walk resumes", async () => { + const { slug, root } = await channel(); + const t = new FakeForumThread(15); // 5 pages + await t.writeTo(FIXTURES); + const blocked = path.join(FIXTURES, FAKE_THREAD_ID, "page-3.200.html"); + await writeFile(blocked, CHALLENGE_PAGE); + const waits: number[] = []; + const res = await run(slug, { + retryOnBlock: { minutes: 30, max: 12 }, + sleep: async (ms) => { + waits.push(ms); + // Two waits, then the check clears. + if (waits.length === 2) await rm(blocked); + return "slept"; + }, + }); + assert.deepEqual(waits, [30 * 60_000, 30 * 60_000]); + assert.match(res.log, /Waiting 30 min after a challenge page, try 2\/12\./); + assert.match(res.log, /Waiting 30 min after a challenge page, try 3\/12\./); + assert.equal(res.result.ok, true); + assert.equal(res.result.complete, true); + assert.equal(res.result.written, 15); + assert.deepEqual([...(await readSeenPostIds(root))].sort(), t.ids().sort()); +}); + +test("retry on a block gives up after `max` tries, never retries a captcha, and a drain during the wait ends cleanly", async () => { + const { slug } = await channel(); + const t = new FakeForumThread(6); + await t.writeTo(FIXTURES); + const p2 = path.join(FIXTURES, FAKE_THREAD_ID, "page-2.403.html"); + await writeFile(p2, "<html><body>Access denied</body></html>"); + const waits: number[] = []; + const res = await run(slug, { + retryOnBlock: { minutes: 5, max: 3 }, + sleep: async (ms) => { + waits.push(ms); + return "slept"; + }, + }); + assert.equal(waits.length, 2, "three tries in all"); + assert.equal(res.result.ok, false); + assert.equal(res.result.block, "blocked"); + assert.match(res.log, /Still refused after 3 tries; stopped\./); + + const drained = await run(slug, { retryOnBlock: { minutes: 5, max: 3 }, sleep: async () => "drained" }); + assert.equal(drained.result.ok, true); + assert.equal(drained.result.drained, true); + await rm(p2); + + // A captcha needs a person: no wait at all. + const { slug: s2 } = await channel(); + const p1 = path.join(FIXTURES, FAKE_THREAD_ID, "page-2.200.html"); + await writeFile(p1, '<html><body><div class="h-captcha"></div></body></html>'); + const none: number[] = []; + const cap = await run(s2, { retryOnBlock: { minutes: 5, max: 3 }, sleep: async (ms) => (none.push(ms), "slept") }); + assert.equal(none.length, 0); + assert.equal(cap.result.block, "captcha"); + await rm(p1); + + // Bounds are the controller's too. + const bad = await run(s2, { retryOnBlock: { minutes: 1, max: 3 } }); + assert.match(bad.result.error ?? "", /minutes/); + const older = await run(s2, { retryOnBlock: { minutes: 30, max: 3 }, older: true }); + assert.match(older.result.error ?? "", /Retry on a block/); +}); + +test("the real wait ends on a cancel or a drain", async () => { + const cancel = new AbortController(); + const p = sleepOrStop(60_000, cancel.signal); + cancel.abort(); + assert.equal(await p, "aborted"); + const drain = new AbortController(); + const q = sleepOrStop(60_000, undefined, drain.signal); + drain.abort(); + assert.equal(await q, "drained"); + assert.equal(await sleepOrStop(1), "slept"); +}); diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -25,6 +25,8 @@ import { oldestPostCreatedAt, readPostFetchState, readSeenPostIds, + readAllPosts, + upsertPosts, writePostFetchState, writePosts, type OlderBackfillPosition, @@ -34,9 +36,17 @@ import { import { handleFromAccountUrl, resolveSocialFetcher, + type PostFetchResult, type SocialFetcher, } from "../social/fetchers"; import { + deriveForumWalk, + forumWalkStartLine, + retryOnBlockProblem, + type ForumWalkState, + type RetryOnBlock, +} from "../lib/forumWalk"; +import { firstOlderWindow, isUtcDay, olderFloorDay, @@ -60,6 +70,8 @@ import { type XLoginSettings, } from "../social/xBrowserLogin"; +type ChannelConfigRead = NonNullable<Awaited<ReturnType<typeof readChannelConfig>>>; + export type FetchPostsOptions = { paths: Paths; slug: string; @@ -100,6 +112,14 @@ export type FetchPostsOptions = { // The job's Drain: the fetch stops at its next resume point and keeps it, // and the run ends as a success, not a failure. drain?: AbortSignal; + // A challenge or refusal page stops the walk; wait `minutes` and run again, + // up to `max` tries in all (the first included). A forum thread's Fetch + // posts button passes `settings.social.xenforo.retryOnBlock`. Not with + // `older`. + retryOnBlock?: RetryOnBlock; + // The retry's wait (tests pass a fake clock). Default: a real timer that a + // cancel or a drain ends. + sleep?: (ms: number, signal?: AbortSignal, drain?: AbortSignal) => Promise<"slept" | "aborted" | "drained">; }; // A Wayback pages channel (release 37) has no account to fetch: its captures @@ -111,6 +131,8 @@ export const WAYBACK_PAGES_NOT_FETCHED = // button, the ops route and this controller say the same thing. export const OLDER_FROM_REFUSAL = "A start date (\"from\") applies only to an older-posts fetch."; +export const RETRY_AND_OLDER_REFUSAL = "Retry on a block applies to a new-posts or full fetch, not an older-posts one."; + export const FULL_AND_OLDER_REFUSAL = "A full re-fetch and an older-posts fetch are different walks — run one at a time."; @@ -152,6 +174,11 @@ export type FetchPostsResult = { needsCookies?: boolean; // Stopped on the job's Drain, at a resume point the next run continues from. drained?: boolean; + // A full re-walk of a forum thread: archived posts whose newer record (an + // edit) was appended. + updated?: number; + // What stopped the last try, when the source refused or challenged it. + block?: PostFetchResult["block"]; }; export async function fetchPosts( @@ -169,6 +196,9 @@ export async function fetchPosts( return { ok: false, written: 0, skipped: 0, complete: false, error: `"${day}" is not a date (YYYY-MM-DD) for "${name}"` }; } } + if (opts.retryOnBlock && opts.older) { + return { ok: false, written: 0, skipped: 0, complete: false, error: RETRY_AND_OLDER_REFUSAL }; + } if (opts.from !== undefined && !opts.older) { return { ok: false, written: 0, skipped: 0, complete: false, error: OLDER_FROM_REFUSAL }; } @@ -254,13 +284,119 @@ export async function fetchPosts( browserCookies: xLogin?.browserSpec, }); } - // A stored cursor means the previous run stopped early (hit its limit, or was - // cancelled). Resume the backfill from there rather than applying the - // watermark, which would otherwise leave that history permanently missing. - // --full discards the cursor and re-walks from the top. - const resumeCursor = opts.full ? undefined : priorState?.cursor; + // RETRY ON A BLOCK (release 37 lane G): a challenge or a refusal stops the + // walk; the job waits `minutes` and runs again, up to `max` tries in all. + // Never sooner than `minutes` (held to RETRY_MIN_MINUTES), never on a + // captcha or a login, which need a person. + const retry = opts.retryOnBlock; + const retryProblem = retryOnBlockProblem(retry); + if (retryProblem) return { ok: false, written: 0, skipped: 0, complete: false, error: retryProblem }; + const sleep = opts.sleep ?? sleepOrStop; + let written = 0; + let skipped = 0; + let updated = 0; + for (let attempt = 1; ; attempt++) { + const r = await fetchTimeline({ + opts, + fetcher, + channelRoot, + handle, + accountUrl, + seenIds: attempt === 1 ? seenIds : await readSeenPostIds(channelRoot), + priorState: attempt === 1 ? priorState : await readPostFetchState(channelRoot), + config, + }); + written += r.written; + skipped += r.skipped; + updated += r.updated ?? 0; + const total = { ...r, written, skipped, ...(updated ? { updated } : {}) }; + if (!retry || !r.block || !RETRYABLE_BLOCKS.has(r.block) || attempt >= retry.max) { + if (retry && r.block && RETRYABLE_BLOCKS.has(r.block)) { + log(`[error] Still ${r.block === "challenge" ? "challenged" : "refused"} after ${attempt} tries; stopped.`); + } + return total; + } + if (signal?.aborted) return total; + log( + `Waiting ${retry.minutes} min after ${r.block === "challenge" ? "a challenge page" : "a refusal"}, try ${attempt + 1}/${retry.max}.`, + ); + const why = await sleep(retry.minutes * 60_000, signal, opts.drain); + if (why === "aborted") return total; + if (why === "drained") { + log("Drained while waiting out the block; the next run resumes at its saved positions."); + return { ...total, ok: true, error: undefined, drained: true }; + } + } +} + +// The blocks a wait can clear: a browser check, a 403/429 refusal. +const RETRYABLE_BLOCKS = new Set<NonNullable<PostFetchResult["block"]>>(["challenge", "blocked"]); + +// Wait `ms`, or until the job is cancelled or drained. +export function sleepOrStop( + ms: number, + signal?: AbortSignal, + drain?: AbortSignal, +): Promise<"slept" | "aborted" | "drained"> { + return new Promise((resolve) => { + if (signal?.aborted) return resolve("aborted"); + if (drain?.aborted) return resolve("drained"); + const finish = (why: "slept" | "aborted" | "drained") => { + clearTimeout(timer); + signal?.removeEventListener("abort", onAbort); + drain?.removeEventListener("abort", onDrain); + resolve(why); + }; + const onAbort = () => finish("aborted"); + const onDrain = () => finish("drained"); + const timer = setTimeout(() => finish("slept"), ms); + signal?.addEventListener("abort", onAbort, { once: true }); + drain?.addEventListener("abort", onDrain, { once: true }); + }); +} + +// The held pages of a forum thread: every archived post's page, as read. +async function heldForumPages(channelRoot: string): Promise<number[]> { + const pages: number[] = []; + for (const p of await readAllPosts(channelRoot)) { + if (p.platform === "xenforo" && typeof p.forum?.page === "number") pages.push(p.forum.page); + } + return pages; +} + +// ONE RUN of the timeline walk (a normal or full fetch): the fetcher, the +// writes, the state. +async function fetchTimeline(ctx: { + opts: FetchPostsOptions; + fetcher: SocialFetcher; + channelRoot: string; + handle: string; + accountUrl: string; + seenIds: ReadonlySet<string>; + priorState: PostFetchState | null; + config: ChannelConfigRead; +}): Promise<FetchPostsResult & { block?: PostFetchResult["block"] }> { + const { opts, fetcher, channelRoot, handle, accountUrl, seenIds, priorState, config } = ctx; + const { paths, slug, settings, signal } = opts; + const log = (line: string) => opts.onLog?.(line); + const forum = fetcher.platform === "xenforo"; + + // A FORUM THREAD keeps two positions (lib/forumWalk.ts), re-derived from the + // archived posts' pages every run; its walk needs neither a cursor nor a + // watermark. Every other fetcher: a stored cursor means the previous run + // stopped early (hit its limit, or was cancelled) — resume the backfill from + // there rather than applying the watermark, which would otherwise leave that + // history permanently missing. --full discards the cursor and re-walks from + // the top. + let forumWalk: ForumWalkState | undefined; + if (forum) { + const derived = deriveForumWalk(priorState?.forum, priorState?.cursor, await heldForumPages(channelRoot)); + forumWalk = derived.walk; + for (const note of derived.notes) log(note); + } + const resumeCursor = opts.full || forum ? undefined : priorState?.cursor; const since = - opts.full || resumeCursor + opts.full || resumeCursor || forum ? undefined : ((await latestPostCreatedAt(channelRoot)) ?? undefined); const policy = resolveCookiePolicy(settings, config); @@ -275,11 +411,15 @@ export async function fetchPosts( log( `Fetching posts for ${slug} via ${fetcher.label} (@${handle})` + - (resumeCursor - ? " — resuming an unfinished backfill" - : since - ? ` since ${since}` - : " — full history") + + (forum + ? opts.full + ? " — a full re-walk" + : ` — ${forumWalkStartLine(forumWalk ?? {})}` + : resumeCursor + ? " — resuming an unfinished backfill" + : since + ? ` since ${since}` + : " — full history") + `; ${seenIds.size} already archived.`, ); @@ -295,6 +435,21 @@ export async function fetchPosts( // The older walk's position rides along untouched: a normal fetch neither // reads it nor drops it. if (priorState?.older) state.older = priorState.older; + // A forum thread's positions are written whole every time (a run that + // fails before its first page keeps the derived ones). + if (forumWalk) state.forum = forumWalk; + + // A full re-walk of a forum thread re-reads archived posts for their edits: + // they come back with the new ones and are UPSERTED (a newer record of an + // archived post appended; readers take the last). + const upsert = forum && opts.full === true; + let updated = 0; + const write = async (posts: Post[]) => { + if (!upsert) return writePosts(channelRoot, posts); + const u = await upsertPosts(channelRoot, posts, { ignorePosition: true }); + updated += u.updated; + return u; + }; // Progress a long run saves as it goes (a fetcher that streams calls this // between pages): the posts so far, then the resume point they are safe @@ -302,14 +457,15 @@ export async function fetchPosts( let checkpointWritten = 0; let checkpointSkipped = 0; const shards = new Set<string>(); - const onCheckpoint = async (cp: { posts: Post[]; cursor: string }) => { - const w = await writePosts(channelRoot, cp.posts); + const onCheckpoint = async (cp: { posts: Post[]; cursor: string; forumWalk?: ForumWalkState }) => { + const w = await write(cp.posts); checkpointWritten += w.written; checkpointSkipped += w.skipped; for (const shard of w.shards) shards.add(shard); + if (forum && cp.forumWalk) state.forum = cp.forumWalk; await writePostFetchState(channelRoot, { ...state, - cursor: cp.cursor, + ...(forum ? {} : { cursor: cp.cursor }), lastFetchedCount: checkpointWritten, }); if (w.written > 0) { @@ -317,7 +473,7 @@ export async function fetchPosts( } }; - let result; + let result: PostFetchResult; try { result = await fetcher.fetch({ accountUrl, @@ -325,6 +481,7 @@ export async function fetchPosts( channelSlug: slug, since, cursor: resumeCursor, + ...(forumWalk ? { forumWalk } : {}), seenIds, cookies, cookieSource: xLogin?.source, @@ -347,7 +504,8 @@ export async function fetchPosts( // Whatever was checkpointed is on disk; keep the resume point that covers // it rather than dropping back to the watermark. const prior = await readPostFetchState(channelRoot); - if (prior?.cursor) state.cursor = prior.cursor; + if (!forum && prior?.cursor) state.cursor = prior.cursor; + if (forum && prior?.forum) state.forum = prior.forum; if (checkpointWritten > 0) state.lastFetchedCount = checkpointWritten; await writePostFetchState(channelRoot, state); return { @@ -359,7 +517,7 @@ export async function fetchPosts( }; } - const final = await writePosts(channelRoot, result.posts); + const final = await write(result.posts); for (const shard of final.shards) shards.add(shard); const written = { written: checkpointWritten + final.written, @@ -367,12 +525,25 @@ export async function fetchPosts( }; log( `Wrote ${written.written} new post(s), skipped ${written.skipped} already archived` + + (upsert ? `, updated ${updated} edited` : "") + (shards.size > 0 ? ` (shards: ${[...shards].join(", ")})` : "") + (result.complete ? "." : " — more history remains."), ); + if (result.notSeen?.length) { + log( + `${result.notSeen.length} archived post(s) were on no page of the thread (deleted or moved since): ` + + result.notSeen.slice(0, 20).join(", ") + + (result.notSeen.length > 20 ? ", …" : "") + + ". Kept as archived; nothing is marked.", + ); + } state.lastFetchedCount = written.written; - if (result.cursor && !result.complete) state.cursor = result.cursor; + if (forum) { + if (result.forumWalk) state.forum = result.forumWalk; + } else if (result.cursor && !result.complete) { + state.cursor = result.cursor; + } if (result.needsCookies) state.needsCookies = true; if (result.error) { log(`[error] ${result.error}`); @@ -400,6 +571,8 @@ export async function fetchPosts( complete: result.complete, needsCookies: result.needsCookies, error: result.error, + ...(upsert ? { updated } : {}), + ...(result.block ? { block: result.block } : {}), ...(result.drained ? { drained: true } : {}), }; } diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -210,6 +210,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_WORKERS", audience: "test", default: "1", readBy: "editor/playwright.config.ts (editor/e2e/servers.ts)", doc: "How many workers the editor suite runs, each with a server set of its own (editor, export dev server, Ollama stub) over its own data root (`editor/.e2e-workers/w<n>`): a number (up to 8), or `auto` — floor((MemAvailable − HEAVY_MIN_FREE_MB) / 1.5 GB), 1 to 3. Specs in `editor/e2e/serial.ts` run afterwards on one worker." }, { name: "E2E_SERIAL_LAST", audience: "test", default: "—", readBy: "editor/playwright.config.ts", doc: "Set by the editor suite's runner for its workers: `1` when the run is whole (no spec file or filter on the command line), so the @serial project runs last; `0` for a focused run, where Playwright would run a teardown project whole." }, { name: "E2E_BUILD_CHECKED", audience: "test", default: "—", readBy: "editor/playwright.config.ts, umtool/playwright.config.ts", doc: "Set by a suite's config once it has checked the start-mode build's stamp, so a worker's second load of the config does not check again." }, + { name: "FORUM_FIXTURE_DIR", audience: "test", default: "unset (the forum fetcher opens its headless browser)", readBy: "common/social/forumFixtureLoader.ts (the forum-thread fetcher), editor/package.json (dev:test, start:test)", doc: "A directory of SYNTHETIC saved thread pages (`<dir>/<threadId>/page-<N>.html`) the forum-thread fetcher reads in place of a browser, with no pause between pages — the editor e2e suite's forum channel. Set by `dev:test` / `start:test` to `<E2E_DATA_ROOT>/test-transcripts/.forum-fixture`, and by nothing else." }, { name: "E2E_QUEUE", audience: "test", default: "on", readBy: "scripts/queue-lock.mjs", doc: "`0` skips the machine-global e2e queue (the port check still runs)." }, { name: "E2E_PORT_CHECK", audience: "test", default: "on", readBy: "scripts/queue-lock.mjs", doc: "`0` skips the pre-run check that the suite's ports are free." }, { name: "E2E_QUEUE_TIMEOUT", audience: "test", default: "wait forever", readBy: "scripts/queue-lock.mjs", doc: "Seconds to wait for the queue before giving up." }, diff --git a/common/lib/forumWalk.test.ts b/common/lib/forumWalk.test.ts @@ -0,0 +1,96 @@ +// The forum walk's positions, pure (release 37 lane G). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/forumWalk.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + deriveForumWalk, + describeForumWalk, + describeRetryOnBlock, + forumWalkStartLine, + heldBand, + meanPagePauseSeconds, + parseRetryOnBlock, + retryOnBlockProblem, + roughDuration, +} from "./forumWalk"; + +const range = (a: number, b: number) => Array.from({ length: b - a + 1 }, (_, i) => a + i); + +test("the held band runs down from the newest held page; an isolated low page is not part of it", () => { + assert.equal(heldBand([]), null); + assert.deepEqual(heldBand([...range(2341, 2598), 1]), { low: 2341, high: 2598 }); + assert.deepEqual(heldBand([5, 5, 4, 2, 1]), { low: 4, high: 5 }); +}); + +test("the live bug's state migrates: an old single cursor above the held band heals to one page above its foot", () => { + // posts-state.json {"cursor": "2507"}; the archive holds pages 2341–2598. + const d = deriveForumWalk(undefined, "2507", range(2341, 2598)); + assert.equal(d.walk.historyPage, 2342); + assert.equal(d.walk.newestPage, 2598); + assert.equal(d.walk.oldestPageReached, 2341); + assert.equal(d.walk.newestPostId, undefined, "no mark yet: the first catch-up stops at any archived post"); + assert.equal(d.notes.length, 2); + // An old cursor BELOW the band (a history walk that was honest) is kept. + assert.equal(deriveForumWalk(undefined, "2340", range(2341, 2598)).walk.historyPage, 2340); +}); + +test("derive, don't trust: a stored position never above the band's foot + 1, complete only when page 1 is held", () => { + assert.equal(deriveForumWalk({ historyPage: 100 }, undefined, range(50, 200)).walk.historyPage, 51); + assert.equal(deriveForumWalk({ historyPage: 40 }, undefined, range(50, 200)).walk.historyPage, 40); + // No position at all (posts imported, never walked): from the posts. + assert.equal(deriveForumWalk(undefined, undefined, range(50, 200)).walk.historyPage, 51); + // Marked complete, but the pages stop at 50: reopened. + const reopened = deriveForumWalk({ complete: true }, undefined, range(50, 200)); + assert.equal(reopened.walk.complete, false); + assert.equal(reopened.walk.historyPage, 51); + // Every page from 1 up held: complete, whatever was stored. + const done = deriveForumWalk({ historyPage: 3 }, undefined, range(1, 200)); + assert.equal(done.walk.complete, true); + assert.equal(done.walk.historyPage, undefined); + // Nothing held: the stored positions as they are. + assert.deepEqual(deriveForumWalk({ historyPage: 7 }, undefined, []).walk, { historyPage: 7 }); + // A cursor that is not a page number is not read. + assert.deepEqual(deriveForumWalk(undefined, "abc", []).walk, {}); +}); + +test("the start line and the channel page's status line", () => { + assert.equal( + forumWalkStartLine({ newestPage: 2600, historyPage: 2338 }), + "caught up to page 2600; history resumes at page 2338", + ); + assert.equal( + forumWalkStartLine({ newestPage: 2600, catchUpPage: 2590, complete: true }), + "caught up to page 2600; an unfinished catch-up continues at page 2590; history complete", + ); + assert.equal(forumWalkStartLine({}), "nothing read yet; history from the last page"); + const pace = meanPagePauseSeconds(12, 5); + assert.equal(pace, 15); + assert.equal( + describeForumWalk({ newestPage: 2600, oldestPageReached: 2338, historyPage: 2337 }, 12.3), + "pages read 2338–2600 of 2600 · history to page 1 remaining: 2337 pages (~8 h)", + ); + assert.equal( + describeForumWalk({ newestPage: 40, oldestPageReached: 1, complete: true, catchUpPage: 38 }, pace), + "pages read 1–40 of 40 · catch-up unfinished at page 38 · history complete", + ); + assert.equal(describeForumWalk(undefined, pace), null); + assert.equal(describeForumWalk({}, pace), null); + assert.equal(roughDuration(40), "~40 s"); + assert.equal(roughDuration(25 * 60), "~25 min"); + assert.equal(roughDuration(3 * 3600 + 600), "~3.2 h"); +}); + +test("retry on a block: bounds, parsing, words", () => { + assert.equal(retryOnBlockProblem(undefined), null); + assert.equal(retryOnBlockProblem({ minutes: 30, max: 12 }), null); + assert.match(retryOnBlockProblem({ minutes: 1, max: 12 }) ?? "", /minutes/); + assert.match(retryOnBlockProblem({ minutes: 30, max: 0 }) ?? "", /max/); + assert.match(retryOnBlockProblem({ minutes: 30, max: 1.5 }) ?? "", /max/); + assert.deepEqual(parseRetryOnBlock({ minutes: 30, max: 12, extra: 1 }), { minutes: 30, max: 12 }); + assert.equal(parseRetryOnBlock({ minutes: 2, max: 12 }), undefined); + assert.equal(parseRetryOnBlock("30x12"), undefined); + assert.equal(describeRetryOnBlock({ minutes: 30, max: 12 }), "wait 30 min after a block, up to 12 tries"); + assert.equal(describeRetryOnBlock(undefined), "off"); +}); diff --git a/common/lib/forumWalk.ts b/common/lib/forumWalk.ts @@ -0,0 +1,211 @@ +// WHERE A FORUM THREAD'S WALK STANDS (release 37 lane G) — `posts-state.json`'s +// `forum`, pure: no fs, client-safe (the channel page's status line reads it). +// +// A thread is read newest first, and two walks share the pages: +// +// CATCH-UP — from the thread's last page down to the first page holding an +// archived post at or below `newestPostId` (the MARK: every post up to it is +// held, from `historyPage` up). It is what every run does first, so the +// newest posts always come first. A capped or interrupted catch-up keeps its +// own resume point (`catchUpPage`) and never touches `historyPage`. +// +// HISTORY — from `historyPage` down to page 1. Archived posts mean nothing +// here (pages shift down as posts are deleted); a page whose posts are all +// archived is stepped past without counting against a run's caps. It +// advances only `historyPage`, and ends with `complete`. +// +// One cursor used to serve both walks: a capped catch-up stored its own +// position as THE cursor and the next run re-read hundreds of held pages as +// "history". Two positions, and the posts themselves as the check on them. +// +// DERIVE, DON'T TRUST. At the start of every run `historyPage` is re-derived +// from the archived posts' pages (`ForumPostInfo.page`): it is never above one +// page past the top of the held band — the contiguous run of held pages down +// from the newest — so a lost or overwritten position heals from the posts. +// Drift only moves posts to LOWER page numbers (a deletion shifts every later +// post back), so a page number read earlier is never below where the post is +// now: starting a page or two ABOVE the band's foot re-reads held pages +// (skipped, uncounted) and can never step over an unread one. + +export type ForumWalkState = { + // The thread's last page, as the last run saw it. + newestPage?: number; + // THE MARK: the newest post of the held band. A catch-up ends at the first + // page holding an archived post at or below it. Absent before the first + // complete catch-up (a state from before release 37): then any archived post + // ends the catch-up, as it always did. + newestPostId?: string; + // An unfinished catch-up's next page: a capped or interrupted catch-up read + // the pages above it, and the band between it and the mark is still owed. + catchUpPage?: number; + // The next older page the history walk reads. Absent when `complete`. + historyPage?: number; + // The lowest page any walk has read. + oldestPageReached?: number; + // The history walk has read page 1. + complete?: boolean; +}; + +// How many pages above the held band's foot a derived history start re-reads. +export const FORUM_HISTORY_OVERLAP = 2; + +// The contiguous run of pages down from the highest one held. An isolated low +// page — an article thread's first post, shown atop every page and stored with +// page 1, or a range imported from saved pages — is not part of it. +export function heldBand(pages: Iterable<number>): { low: number; high: number } | null { + const set = new Set<number>(); + for (const p of pages) if (Number.isInteger(p) && p >= 1) set.add(p); + if (set.size === 0) return null; + const high = Math.max(...set); + let low = high; + while (set.has(low - 1)) low--; + return { low, high }; +} + +export type DerivedForumWalk = { + walk: ForumWalkState; + // What the derivation changed, as sentences for the job log. + notes: string[]; +}; + +// The positions a run starts from: the stored ones (or, for a state written +// before release 37, its single `cursor` read as the history position), +// checked against the pages the archive actually holds. +export function deriveForumWalk( + stored: ForumWalkState | undefined, + legacyCursor: string | undefined, + heldPages: Iterable<number>, +): DerivedForumWalk { + const notes: string[] = []; + const walk: ForumWalkState = { ...(stored ?? {}) }; + if (!stored && legacyCursor !== undefined) { + const n = Number(legacyCursor); + if (Number.isInteger(n) && n >= 1) { + walk.historyPage = n; + notes.push(`Read the old single resume point (page ${n}) as the history position.`); + } + } + const band = heldBand(heldPages); + if (!band) return { walk, notes }; + walk.oldestPageReached = Math.min(walk.oldestPageReached ?? band.low, band.low); + walk.newestPage = Math.max(walk.newestPage ?? band.high, band.high); + if (band.low <= 1) { + // Every page from 1 to the newest held is held: the history is done. + if (!walk.complete) notes.push("The archive holds every page from page 1 up: history complete."); + walk.complete = true; + delete walk.historyPage; + return { walk, notes }; + } + const fromPosts = band.low + FORUM_HISTORY_OVERLAP - 1; + if (walk.complete) { + // Complete, yet the held band stops above page 1: the posts win. + walk.complete = false; + walk.historyPage = fromPosts; + notes.push( + `Marked complete, but the archived pages stop at page ${band.low}: history resumes at page ${fromPosts}.`, + ); + return { walk, notes }; + } + if (walk.historyPage === undefined || walk.historyPage > fromPosts) { + if (walk.historyPage !== undefined) { + notes.push( + `The stored history position (page ${walk.historyPage}) is above the archived pages (held down to page ${band.low}): history resumes at page ${fromPosts}.`, + ); + } else { + notes.push(`No history position stored: resuming at page ${fromPosts}, from the archived pages (held down to page ${band.low}).`); + } + walk.historyPage = fromPosts; + } + return { walk, notes }; +} + +// The log line a run starts with. +export function forumWalkStartLine(walk: ForumWalkState): string { + const parts: string[] = []; + parts.push(walk.newestPage ? `caught up to page ${walk.newestPage}` : "nothing read yet"); + if (walk.catchUpPage) parts.push(`an unfinished catch-up continues at page ${walk.catchUpPage}`); + parts.push( + walk.complete + ? "history complete" + : walk.historyPage + ? `history resumes at page ${walk.historyPage}` + : "history from the last page", + ); + return parts.join("; "); +} + +// A forum walk's pause between two page loads (xenforoFetcher.ts), and the +// floor a channel's `postPagePauseSeconds` is held to. +export const FORUM_DEFAULT_PAGE_PAUSE_SECONDS = 12; +export const FORUM_MIN_PAGE_PAUSE_SECONDS = 5; + +// The mean pause a paced walk waits per page: the jitter (xenforoFetcher.ts, +// jitteredPause) spans [0.85, 1.65) of the base, so its mean is 1.25×. +export function meanPagePauseSeconds(baseSeconds: number, floorSeconds: number): number { + return Math.max(floorSeconds, baseSeconds) * 1.25; +} + +// "~8 h", "~25 min", "~40 s". +export function roughDuration(seconds: number): string { + if (seconds < 90) return `~${Math.max(1, Math.round(seconds))} s`; + if (seconds < 90 * 60) return `~${Math.round(seconds / 60)} min`; + const h = seconds / 3600; + return `~${h < 10 ? Math.round(h * 10) / 10 : Math.round(h)} h`; +} + +// The channel page's status line: "pages read 2338–2600 of 2600 · history to +// page 1 remaining: 2337 pages (~8 h)". Null before any page was read. +export function describeForumWalk( + walk: ForumWalkState | undefined, + pageSeconds: number, +): string | null { + if (!walk || (!walk.newestPage && !walk.oldestPageReached)) return null; + const top = walk.newestPage ?? walk.oldestPageReached!; + const low = walk.complete ? 1 : (walk.oldestPageReached ?? top); + const parts = [`pages read ${low}–${top} of ${top}`]; + if (walk.catchUpPage) parts.push(`catch-up unfinished at page ${walk.catchUpPage}`); + if (walk.complete) { + parts.push("history complete"); + } else if (walk.historyPage) { + parts.push( + `history to page 1 remaining: ${walk.historyPage} page${walk.historyPage === 1 ? "" : "s"} (${roughDuration(walk.historyPage * pageSeconds)})`, + ); + } + return parts.join(" · "); +} + +// --- retry on a block --------------------------------------------------------------- + +// `fetch-posts {retryOnBlock}` and `settings.social.xenforo.retryOnBlock`: a +// challenge or a refusal stops the walk, the job waits `minutes` and runs +// again, `max` tries in all (the first included). +export type RetryOnBlock = { minutes: number; max: number }; + +// The shortest wait a retry may use, the longest, and the most tries. +export const RETRY_MIN_MINUTES = 5; +export const RETRY_MAX_MINUTES = 24 * 60; +export const RETRY_MAX_TRIES = 48; + +export function retryOnBlockProblem(r: RetryOnBlock | undefined): string | null { + if (!r) return null; + if (!Number.isInteger(r.minutes) || r.minutes < RETRY_MIN_MINUTES || r.minutes > RETRY_MAX_MINUTES) { + return `retryOnBlock.minutes must be a whole number from ${RETRY_MIN_MINUTES} to ${RETRY_MAX_MINUTES}.`; + } + if (!Number.isInteger(r.max) || r.max < 1 || r.max > RETRY_MAX_TRIES) { + return `retryOnBlock.max (the tries in all, the first included) must be a whole number from 1 to ${RETRY_MAX_TRIES}.`; + } + return null; +} + +// Total over `unknown`: a valid `{minutes, max}`, else undefined. +export function parseRetryOnBlock(v: unknown): RetryOnBlock | undefined { + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + const r = v as Record<string, unknown>; + const out = { minutes: Number(r.minutes), max: Number(r.max) }; + return retryOnBlockProblem(out) ? undefined : out; +} + +// "wait 30 min, up to 12 tries" / "off". +export function describeRetryOnBlock(r: RetryOnBlock | undefined): string { + return r ? `wait ${r.minutes} min after a block, up to ${r.max} tr${r.max === 1 ? "y" : "ies"}` : "off"; +} diff --git a/common/lib/posts-server.ts b/common/lib/posts-server.ts @@ -13,6 +13,7 @@ import { writeJsonAtomic } from "./jsonFile-server"; import path from "node:path"; +import type { ForumWalkState } from "./forumWalk"; import { readdir, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { appendFile } from "node:fs/promises"; import { mergePageRecord } from "./waybackPages/toPost"; @@ -139,15 +140,17 @@ export type UpsertPostsResult = WritePostsResult & { unchanged: number; }; -// What makes two records of one post differ, for an update. -function postContentKey(p: Post): string { +// What makes two records of one post differ, for an update. `ignorePosition`: +// a forum post's "#N" alone does not (a full re-walk after deletions sees every +// later post renumbered — not an edit). +function postContentKey(p: Post, ignorePosition = false): string { return JSON.stringify([ p.text, p.author, p.links, p.media ?? null, p.forum?.editedAt ?? null, - p.forum?.position ?? null, + ignorePosition ? null : (p.forum?.position ?? null), p.forum?.threadTitle ?? null, ]); } @@ -155,8 +158,8 @@ function postContentKey(p: Post): string { // Is `incoming` a newer record of the same post than `stored`? A later edit // time wins; an older one never replaces a newer one; with no edit times to // compare (or equal ones), different content is taken as the later read. -export function supersedesPost(stored: Post, incoming: Post): boolean { - if (postContentKey(stored) === postContentKey(incoming)) return false; +export function supersedesPost(stored: Post, incoming: Post, opts: { ignorePosition?: boolean } = {}): boolean { + if (postContentKey(stored, opts.ignorePosition) === postContentKey(incoming, opts.ignorePosition)) return false; const a = stored.forum?.editedAt; const b = incoming.forum?.editedAt; if (a && b && a !== b) return b > a; @@ -172,6 +175,7 @@ export function supersedesPost(stored: Post, incoming: Post): boolean { export async function upsertPosts( channelRoot: string, posts: ReadonlyArray<Post>, + opts: { ignorePosition?: boolean } = {}, ): Promise<UpsertPostsResult> { // One record per id from the batch: the newest of them (two page records // of one item merge — lib/waybackPages/toPost.ts, mergePageRecord). @@ -198,7 +202,7 @@ export async function upsertPosts( // same capture imported again): the split-record merge decides — the // later capture's facts, the first capture kept in page.firstSeenTs. const pageMerged = old?.page && p.page ? mergePageRecord(old, p) : undefined; - if (pageMerged === null || (pageMerged === undefined && old && !supersedesPost(old, p))) { + if (pageMerged === null || (pageMerged === undefined && old && !supersedesPost(old, p, opts))) { unchanged++; continue; } @@ -491,6 +495,11 @@ export type PostFetchState = { // `cursor` so a normal fetch never resumes backwards, and carried through // every write a normal fetch makes. older?: OlderBackfillState; + // A FORUM THREAD's two walks (release 37 lane G, lib/forumWalk.ts): the + // catch-up's mark and resume point, and the history walk's position — in + // place of `cursor`, which a forum fetch no longer writes (an old one is + // read once, as the history position, and dropped). + forum?: ForumWalkState; }; // Where the older-posts backfill stands. The window is in UTC days, as X's diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -40,6 +40,7 @@ import { SOCIAL_LINK_FIELD_DOCS, SOCIAL_SETTINGS_FIELD_DOCS, X_SOCIAL_SETTINGS_FIELD_DOCS, + XENFORO_SOCIAL_SETTINGS_FIELD_DOCS, SYNC_SCHEDULER_SETTINGS_FIELD_DOCS, defaultSiteSettings, siteSettingsSchema, @@ -197,6 +198,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, // and only a chosen one is written. defaults: fromObject(d.social.x), }, + { path: "social.xenforo", docs: XENFORO_SOCIAL_SETTINGS_FIELD_DOCS }, ], socialLinks: [{ path: "socialLinks[]", docs: SOCIAL_LINK_FIELD_DOCS }], savedVideoBackup: [ diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -120,17 +120,29 @@ import { previewBranchProblem } from "./pagesDeploy"; import { sanitizeSocial, type SocialSettings, + type XenforoSocialSettings, type XSocialSettings, } from "../social/xCookieSource"; export type { Worker } from "./workers"; -export type { SocialSettings, XSocialSettings } from "../social/xCookieSource"; +export type { SocialSettings, XSocialSettings, XenforoSocialSettings } from "../social/xCookieSource"; // The `social` block (release 16 slice XL). The types and the coercion live // with the source they choose, in social/xCookieSource.ts (pure, client-safe); // the documentation lives here with every other block's. export const SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<SocialSettings> = { x: "X / Twitter. See `social.x` below.", + xenforo: "Forum threads (XenForo). See `social.xenforo` below. Absent: nothing set.", +}; + +export const XENFORO_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XenforoSocialSettings> = { + retryOnBlock: + "`{ \"minutes\": N, \"max\": M }` — what a forum thread's Fetch posts button does when the forum " + + "serves a browser check that will not clear, or refuses a page (403/429): the job waits N minutes " + + "and runs again, M tries in all (the first included; minutes 5–1440, tries 1–48). A captcha or a " + + "login wall is never retried — it needs a person. ABSENT (the default): off, the job stops at the " + + "block. Set on the forum channel page (Retry after a block); `fetch-posts` takes its own " + + "`retryOnBlock`. common/lib/forumWalk.ts.", }; export const X_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XSocialSettings> = { @@ -1763,7 +1775,7 @@ export const siteSettingsSchema = z.object({ "How yt-dlp invocations use the configured cookies (see common/lib/cookiePolicy.ts): \"always\" passes them on every invocation, \"when-required\" (default; the historical behavior) only to retry an auth/age failure, \"defer\" never in normal runs — auth-gated videos are excluded from batches and collected into the per-channel \"Needs cookies\" bucket for a manual cookie run. Per-channel override available (ChannelConfig.cookieMode).", ), social: settingsField((v): SocialSettings => sanitizeSocial(v)).describe( - "Per-platform settings of the social posts. Today two keys, both X's, both chosen in the X account session section of /settings: where the X fetchers' login comes from (`social.x.cookieSource`) and where X posts may appear (`social.x.visibility`). See common/social/xCookieSource.ts.", + "Per-platform settings of the social posts: X's two, both chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`) and where X posts may appear (`social.x.visibility`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts.", ), sleepBetweenDownloadsSeconds: settingsField((v): number => clampSleepBetweenDownloadsSeconds(v)).describe( "Pause (seconds) inserted between per-video yt-dlp invocations in managed batch downloads, and between two auto-download units on one platform (release 17; the lane ignored it before). yt-dlp's own `-t sleep` only paces requests within one invocation, so without this the managed loop hammers the source IP back-to-back. The adaptive pace above its base (see `pacing`) is added to it. 0 disables. Per-channel override available for batch downloads.", diff --git a/common/social/__fixtures__/fakeForumThread.ts b/common/social/__fixtures__/fakeForumThread.ts @@ -0,0 +1,75 @@ +// A SYNTHETIC forum thread that changes between runs (release 37 lane G): posts +// arrive at its end, posts are deleted and the pages shift down, a page is +// served as a challenge. The walk's tests read it through a loader, the +// controller's and the e2e suite's through the saved-pages directory +// FORUM_FIXTURE_DIR names (social/forumFixtureLoader.ts). Invented forum, +// members and words (xenforoPages.ts). + +import { mkdir, readdir, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { threadPage, type FakePost } from "./xenforoPages"; + +export const FAKE_THREAD_ID = "4242"; +const T0 = 1_760_000_000; + +export class FakeForumThread { + // The thread's posts as the forum shows them now, oldest first. + posts: FakePost[] = []; + private nextId: number; + + constructor( + count: number, + readonly perPage = 3, + idBase = 9000, + ) { + this.nextId = idBase + 1; + this.add(count); + } + + // `n` new posts at the thread's end. + add(n: number): void { + for (let i = 0; i < n; i++) { + const id = this.nextId++; + this.posts.push({ id, author: `Member${id % 4}`, userId: 50 + (id % 4), ts: T0 + id * 600, position: 0, body: `Words of post ${id}.` }); + } + } + + // Delete posts (by id): every later post moves back, pages shift down. + remove(ids: Iterable<number>): void { + const gone = new Set(ids); + this.posts = this.posts.filter((p) => !gone.has(p.id)); + } + + get last(): number { + return Math.max(1, Math.ceil(this.posts.length / this.perPage)); + } + + // The posts of page n (1-based), positions as the forum numbers them now. + pagePosts(n: number): FakePost[] { + const page = Math.min(Math.max(1, n), this.last); + return this.posts + .slice((page - 1) * this.perPage, page * this.perPage) + .map((p, i) => ({ ...p, position: (page - 1) * this.perPage + i + 1 })); + } + + html(n: number): string { + const page = Math.min(Math.max(1, n), this.last); + return threadPage({ page, last: this.last, posts: this.pagePosts(page) }); + } + + ids(): string[] { + return this.posts.map((p) => String(p.id)); + } + + // The thread as FORUM_FIXTURE_DIR's saved pages: `<dir>/4242/page-<N>.html`, + // pages past the end removed (block overrides are left alone). + async writeTo(dir: string): Promise<void> { + const threadDir = path.join(dir, FAKE_THREAD_ID); + await mkdir(threadDir, { recursive: true }); + for (const f of await readdir(threadDir)) { + const m = /^page-(\d+)\.html$/.exec(f); + if (m && Number(m[1]) > this.last) await rm(path.join(threadDir, f)); + } + for (let n = 1; n <= this.last; n++) await writeFile(path.join(threadDir, `page-${n}.html`), this.html(n)); + } +} diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -15,6 +15,7 @@ import type { Post, PostAvailability, PostPlatform } from "../lib/posts"; import type { OlderBackfillPosition } from "../lib/posts-server"; +import type { ForumWalkState } from "../lib/forumWalk"; import type { XCookieSource } from "./xCookieSource"; import type { PostCaptureState } from "./postCapture"; @@ -67,7 +68,11 @@ export type PostFetchInput = { // Save progress during a long run: called with posts not yet handed back and // the resume point they are safe under. Posts passed here are NOT returned // again in the result. A fetcher that pages in one shot never calls it. - onCheckpoint?: (checkpoint: { posts: Post[]; cursor: string }) => Promise<void>; + onCheckpoint?: (checkpoint: { posts: Post[]; cursor: string; forumWalk?: ForumWalkState }) => Promise<void>; + // A forum thread's walk positions (lib/forumWalk.ts), derived by the + // controller from posts-state.json and the archived posts' pages. Given, it + // replaces `cursor` and `since` for the forum walker; the others ignore it. + forumWalk?: ForumWalkState; signal: AbortSignal; // A soft stop (the job's Drain): the run ends at its next resume point — // between two pages — keeping that point, rather than walking on. `signal` @@ -92,6 +97,14 @@ export type PostFetchResult = { error?: string; // The run stopped on `drain` at a resume point (`cursor`). Not a failure. drained?: boolean; + // A forum thread's walk positions after the run (with every checkpoint's). + forumWalk?: ForumWalkState; + // What stopped the run, when the source refused or challenged it — the + // controller's retry-on-block reads it (a "challenge" or "blocked" is waited + // out and retried; a captcha or a login needs a person). + block?: "challenge" | "captcha" | "blocked" | "login" | "not-found" | "unknown"; + // A complete full re-walk: archived posts of the thread it met on no page. + notSeen?: string[]; }; // Input for the older-posts backfill (`SocialFetcher.fetchOlder`): walk the diff --git a/common/social/forumFixtureLoader.ts b/common/social/forumFixtureLoader.ts @@ -0,0 +1,44 @@ +// A forum page loader over a DIRECTORY OF SAVED PAGES, for the editor's e2e +// suite (FORUM_FIXTURE_DIR, set by `dev:test` / `start:test` only): the +// forum-thread fetcher reads `<dir>/<threadId>/page-<N>.html` instead of +// opening a browser, so the channel page's Fetch posts and Full re-walk run end +// to end with no network. A page number past the last file is the last page, +// as XenForo redirects it. `page-<N>.<status>.html` (a challenge page, a 403) +// is served in place of page N, with that status, while it exists — a test +// removes it to let the "block" clear. SYNTHETIC pages only. + +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import type { ForumPageLoader } from "./forumSession"; +import { xenforoPageUrl, type XenforoThreadUrl } from "./xenforoParse"; + +export function forumFixtureDir(env: Readonly<Record<string, string | undefined>> = process.env): string | undefined { + const dir = env.FORUM_FIXTURE_DIR; + return dir && dir.trim() ? dir : undefined; +} + +export function fixtureForumLoader(dir: string, thread: XenforoThreadUrl): ForumPageLoader { + const threadDir = path.join(dir, thread.threadId); + return { + async load(url) { + const files = await readdir(threadDir).catch(() => [] as string[]); + const pages = files + .map((f) => /^page-(\d+)\.html$/.exec(f)) + .filter((m): m is RegExpExecArray => m !== null) + .map((m) => Number(m[1])); + if (pages.length === 0) throw new Error(`Could not load ${url}: no fixture pages in ${threadDir}`); + const m = /page-(\d+)\/?$/.exec(new URL(url).pathname); + const wanted = m ? Number(m[1]) : 1; + const page = Math.min(wanted, Math.max(...pages)); + const blocked = files.map((f) => new RegExp(`^page-${page}\\.(\\d{3})\\.html$`).exec(f)).find((b) => b); + if (blocked) { + const html = await readFile(path.join(threadDir, blocked[0]), "utf8"); + return { html, status: Number(blocked[1]), url: xenforoPageUrl(thread, page) }; + } + const html = await readFile(path.join(threadDir, `page-${page}.html`), "utf8").catch(() => ""); + if (!html) throw new Error(`Could not load ${url}: no fixture page ${page}`); + return { html, status: 200, url: xenforoPageUrl(thread, page) }; + }, + async close() {}, + }; +} diff --git a/common/social/xCookieSource.ts b/common/social/xCookieSource.ts @@ -19,6 +19,8 @@ // Pure and client-safe — no node imports. The settings schema, the fetch // controller and the editor's Settings section all read it. +import { parseRetryOnBlock, type RetryOnBlock } from "../lib/forumWalk"; + export type XCookieSource = "browser" | "profile"; export const X_COOKIE_SOURCES: readonly XCookieSource[] = ["browser", "profile"]; @@ -51,8 +53,17 @@ export type XSocialSettings = { visibility?: XPostsVisibility; }; +// A forum thread's (platform "xenforo") settings (release 37 lane G). +export type XenforoSocialSettings = { + // The Fetch posts button's retry on a block: wait `minutes` after a + // challenge or refusal page and run again, `max` tries in all. Absent: off. + retryOnBlock?: RetryOnBlock; +}; + export type SocialSettings = { x: XSocialSettings; + // Absent: nothing set. + xenforo?: XenforoSocialSettings; }; // Total over `unknown`, as every settings coercion is: anything that is not a @@ -65,11 +76,16 @@ export function sanitizeSocial(value: unknown): SocialSettings { const x = (r.x && typeof r.x === "object" && !Array.isArray(r.x) ? r.x : {}) as Record<string, unknown>; + const xf = (r.xenforo && typeof r.xenforo === "object" && !Array.isArray(r.xenforo) + ? r.xenforo + : {}) as Record<string, unknown>; + const retryOnBlock = parseRetryOnBlock(xf.retryOnBlock); return { x: { ...(isXCookieSource(x.cookieSource) ? { cookieSource: x.cookieSource } : {}), ...(isXPostsVisibility(x.visibility) ? { visibility: x.visibility } : {}), }, + ...(retryOnBlock ? { xenforo: { retryOnBlock } } : {}), }; } diff --git a/common/social/xenforoFetcher.test.ts b/common/social/xenforoFetcher.test.ts @@ -10,6 +10,8 @@ import os from "node:os"; import path from "node:path"; import type { Post } from "../lib/posts"; import type { PostFetchInput } from "./fetchers"; +import { deriveForumWalk, type ForumWalkState } from "../lib/forumWalk"; +import { FakeForumThread } from "./__fixtures__/fakeForumThread"; import { loadForumPage, presentableUserAgent, type ForumPageLoader } from "./forumSession"; import type { PageLike } from "./playwrightRuntime"; import { @@ -159,15 +161,22 @@ test("resume: a run with a cursor catches up from the last page, then continues test("resume with a pages cap: the latest page is always read first, the cap spans both", async () => { const seen = new Set(["9007", "9008", "9009", "9010", "9011", "9012", "9013", "9014", "9015"]); + // The last page holds nothing new: all held, it does not count — the cap's + // one page is the history's. const one = fakeLoader(); const r1 = await walkXenforoThread(input({ cursor: "2", seenIds: seen, pages: 1 }), deps(one).deps); - assert.deepEqual(one.urls, [`${THREAD_URL}page-${LAST_PAGE_PROBE}`]); - assert.equal(r1.cursor, "2", "nothing new, and the older pages still owed"); + assert.deepEqual(one.urls, [`${THREAD_URL}page-${LAST_PAGE_PROBE}`, `${THREAD_URL}page-2`]); + assert.equal(r1.cursor, "1"); + assert.deepEqual(ids(r1.posts), [4, 5, 6]); + assert.equal(r1.forumWalk?.historyPage, 1); + assert.equal(r1.forumWalk?.newestPostId, "9015"); + // A last page with something new counts: then the cap is the catch-up's. + const fewer = new Set([...seen].filter((id) => id !== "9015")); const two = fakeLoader(); - const r2 = await walkXenforoThread(input({ cursor: "2", seenIds: seen, pages: 2 }), deps(two).deps); - assert.deepEqual(two.urls, [`${THREAD_URL}page-${LAST_PAGE_PROBE}`, `${THREAD_URL}page-2`]); - assert.equal(r2.cursor, "1"); - assert.deepEqual(ids(r2.posts), [4, 5, 6]); + const r2 = await walkXenforoThread(input({ cursor: "2", seenIds: fewer, pages: 1 }), deps(two).deps); + assert.deepEqual(two.urls, [`${THREAD_URL}page-${LAST_PAGE_PROBE}`]); + assert.deepEqual(ids(r2.posts), [15]); + assert.equal(r2.forumWalk?.historyPage, 2, "the history position is not moved by the catch-up"); }); test("incremental: stops on the page holding an already-archived post, keeping its new ones", async () => { @@ -179,22 +188,37 @@ test("incremental: stops on the page holding an already-archived post, keeping i assert.equal(loader.urls.length, 2); }); -test("a full re-walk (stopAtKnown false) does not stop at archived posts", async () => { +test("a full re-walk (stopAtKnown false) reads every page and hands archived posts back for their edits", async () => { const loader = fakeLoader(); const res = await walkXenforoThread( - input({ seenIds: new Set(["9013", "9010"]), stopAtKnown: false }), + input({ seenIds: new Set(["9013", "9010", "9999"]), stopAtKnown: false, forumWalk: { historyPage: 3, newestPostId: "9013" } }), deps(loader).deps, ); assert.equal(res.complete, true); assert.equal(loader.urls.length, 5); - assert.equal(res.posts.length, 13); + assert.equal(res.posts.length, 15, "the two archived ones too"); + assert.equal(res.forumWalk?.complete, true); + assert.equal(res.forumWalk?.historyPage, undefined); + assert.equal(res.forumWalk?.newestPostId, "9015"); + // An archived post no page shows any more: counted, not marked. + assert.deepEqual(res.notSeen, ["9999"]); }); -test("the watermark stops the walk", async () => { - const since = new Date((T0 + 10 * 600) * 1000).toISOString(); // post 10's time - const res = await walkXenforoThread(input({ since }), deps(fakeLoader()).deps); +test("the mark stops the catch-up: an archived post newer than it does not", async () => { + // Posts 13–15 were read by an earlier, capped catch-up (above the mark, + // 9010); 11 and 12 are owed; 10 is the mark. + const seen = new Set(["9001", "9002", "9003", "9004", "9005", "9006", "9007", "9008", "9009", "9010", "9013", "9014", "9015"]); + const loader = fakeLoader(); + const log: string[] = []; + const res = await walkXenforoThread( + input({ seenIds: seen, forumWalk: { newestPostId: "9010", complete: true, newestPage: 4 }, onLog: (l) => log.push(l) }), + deps(loader).deps, + ); assert.equal(res.complete, true); - assert.deepEqual(ids(res.posts), [13, 14, 15, 11, 12]); + assert.deepEqual(ids(res.posts), [11, 12]); + assert.equal(loader.urls.length, 2); + assert.equal(res.forumWalk?.newestPostId, "9015"); + assert.match(log.join("\n"), /Page 5: all held, skipping on\./); }); test("a post limit is checked after a whole page", async () => { @@ -268,12 +292,15 @@ test("a captcha on the very first load keeps no cursor; a 429 is not a session p assert.match(captcha.error ?? "", /captcha/); const limited = await walkXenforoThread( - input({ cursor: "2" }), + input({ cursor: "2", seenIds: new Set(["9015"]) }), deps(fakeLoader(() => ({ html: "<html><body>slow down</body></html>", status: 429 }))).deps, ); // Refused on the catch-up load: the stored cursor is kept, not lost. assert.equal(limited.needsCookies, undefined); assert.equal(limited.cursor, "2"); + assert.equal(limited.forumWalk?.historyPage, 2); + assert.equal(limited.block, "blocked"); + assert.equal(captcha.block, "captcha"); assert.match(limited.error ?? "", /HTTP 429/); }); @@ -284,12 +311,11 @@ test("an article thread: its first post atop every page never stops the walk, an for (let k = (page - 1) * PER_PAGE + 1; k <= page * PER_PAGE; k++) if (k > 1) posts.push(fakePost(k)); return { html: threadPage({ page, last: LAST, posts, article }) }; }; - // Incremental: the starter is archived, and old — neither ends the walk on - // the last page; the archived post 10 on page 4 does. + // Incremental: the starter is archived — it does not end the walk on the + // last page; the archived post 10 on page 4 does. const seen = new Set(["9001", "9010"]); - const since = new Date((T0 + 10 * 600) * 1000).toISOString(); const res = await walkXenforoThread( - input({ seenIds: seen, since }), + input({ seenIds: seen }), deps(fakeLoader((_url, page) => withArticle(page))).deps, ); assert.equal(res.complete, true); @@ -348,6 +374,116 @@ test("the fetcher claims thread URLs only, and probes offline", async () => { }); }); +// --- two positions over a thread that changes (release 37 lane G) ----------------- + +function threadLoader(t: FakeForumThread): FakeLoader { + const loader: FakeLoader = { + urls: [], + closed: 0, + async load(url) { + loader.urls.push(url); + const m = /page-(\d+)$/.exec(url); + const page = Math.min(m ? Number(m[1]) : 1, t.last); + return { html: t.html(page), status: 200, url: `${THREAD_URL}${page > 1 ? `page-${page}` : ""}` }; + }, + async close() { + loader.closed++; + }, + }; + return loader; +} + +const pageUrls = (loader: FakeLoader) => + loader.urls.map((u) => (u === THREAD_URL ? 1 : Number(/page-(\d+)$/.exec(u)![1]))).map((n) => (n === LAST_PAGE_PROBE ? "last" : n)); + +// One run, as the controller drives it: the archive grows by what it hands +// back, and the positions are the run's last. +async function runOnce( + t: FakeForumThread, + held: Set<string>, + walk: ForumWalkState | undefined, + over: Partial<PostFetchInput> = {}, +) { + const loader = threadLoader(t); + const log: string[] = []; + const res = await walkXenforoThread( + input({ seenIds: new Set(held), ...(walk ? { forumWalk: walk } : {}), onLog: (l) => log.push(l), ...over }), + deps(loader).deps, + ); + for (const p of res.posts) held.add(p.id); + return { res, loader, log, walk: res.forumWalk }; +} + +test("a capped catch-up keeps the history position; the next run jumps below what it read", async () => { + const t = new FakeForumThread(30); // 10 pages + const held = new Set<string>(); + // An earlier history walk read pages 10–6. + const first = await runOnce(t, held, undefined, { pages: 5 }); + assert.deepEqual(first.walk, { newestPage: 10, oldestPageReached: 6, historyPage: 5, newestPostId: "9030" }); + // Nine new posts: pages 11–13. A run capped at 2 pages reads 13 and 12. + t.add(9); + const capped = await runOnce(t, held, first.walk, { pages: 2 }); + assert.deepEqual(pageUrls(capped.loader), ["last", 12]); + assert.equal(capped.walk?.historyPage, 5, "the catch-up never touches the history position"); + assert.equal(capped.walk?.catchUpPage, 11); + assert.equal(capped.walk?.newestPostId, "9030", "the mark moves only when a catch-up completes"); + // The next run: page 13 is all held, jump to 11, meet the mark on 10, then + // the history at 5 — never re-reading 12, nor 9–6. + const next = await runOnce(t, held, capped.walk, { pages: 2 }); + assert.deepEqual(pageUrls(next.loader), ["last", 11, 10, 5]); + assert.match(next.log.join("\n"), /an earlier catch-up read down to page 12; continuing there/); + assert.match(next.log.join("\n"), /Caught up to page 13; history resumes at page 5\./); + assert.equal(next.walk?.catchUpPage, undefined); + assert.equal(next.walk?.newestPostId, "9039"); + assert.equal(next.walk?.historyPage, 4); + // And on to page 1: every post of the thread, once. + const rest = await runOnce(t, held, next.walk); + assert.deepEqual(pageUrls(rest.loader), ["last", 4, 3, 2, 1]); + assert.equal(rest.res.complete, true); + assert.equal(rest.walk?.complete, true); + assert.deepEqual([...held].sort(), t.ids().sort()); +}); + +test("drift: posts deleted below the read pages shift every page down, and the history still reaches page 1 with no gap", async () => { + const t = new FakeForumThread(30); + const held = new Set<string>(); + const first = await runOnce(t, held, undefined, { pages: 4 }); // pages 10–7: posts 19–30 + assert.equal(first.walk?.historyPage, 6); + // Six early posts deleted: the thread is 8 pages; 19–30 now sit on 5–8. + t.remove([9001, 9002, 9003, 9004, 9005, 9006]); + const second = await runOnce(t, held, first.walk); + assert.deepEqual(pageUrls(second.loader), ["last", 6, 5, 4, 3, 2, 1]); + assert.match(second.log.join("\n"), /Page 6: all held, skipping on\./); + assert.equal(second.res.complete, true); + assert.deepEqual([...held].sort(), t.ids().sort(), "every surviving post, none skipped"); +}); + +test("all-held pages in the history are stepped past without counting against the caps", async () => { + const t = new FakeForumThread(30); + const held = new Set(t.ids().slice(9)); // posts 10–30: pages 4–10 held + const res = await runOnce(t, held, { historyPage: 9, newestPostId: "9030" }, { pages: 1, limit: 1 }); + // Page 10 meets the mark, then 9…4 are all held — none counted — and page + // 3 is the first with new posts: the one page the cap allows. + assert.deepEqual(pageUrls(res.loader), ["last", 9, 8, 7, 6, 5, 4, 3]); + assert.deepEqual(ids(res.res.posts), [7, 8, 9]); + assert.equal(res.walk?.historyPage, 2); + assert.match(res.log.join("\n"), /Page 5: all held, skipping on\./); +}); + +test("a lost history position heals from the archived pages (deriveForumWalk), and the walk fills the gap", async () => { + const t = new FakeForumThread(30); + // Pages 10–5 are held (posts 13–30); the stored position was overwritten + // by a catch-up's (page 9). + const held = new Set(t.ids().slice(12)); + const pagesHeld = [10, 10, 10, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 5, 5, 5, 1]; + const derived = deriveForumWalk({ historyPage: 9, newestPostId: "9030", newestPage: 10 }, undefined, pagesHeld); + assert.equal(derived.walk.historyPage, 6, "one page above the held band's foot (5), never the stored 9"); + assert.match(derived.notes.join("\n"), /above the archived pages/); + const run = await runOnce(t, held, derived.walk); + assert.deepEqual(pageUrls(run.loader), ["last", 6, 5, 4, 3, 2, 1]); + assert.deepEqual([...held].sort(), t.ids().sort()); +}); + // --- the page loader --------------------------------------------------------------- function fakePage(script: { status?: number; htmls: string[]; href?: string }) { diff --git a/common/social/xenforoFetcher.ts b/common/social/xenforoFetcher.ts @@ -4,15 +4,16 @@ // // THE WALK, NEWEST FIRST. A thread grows at its end, so a run starts on the // last page (asked for with a page number past the end, which XenForo -// redirects to the last page) and steps back a page at a time. It stops at the -// first page holding an already-archived post (the incremental case), at the -// watermark, at page 1, or at a cap — `pages` ("the latest N pages") or -// `limit` (posts), checked after a whole page so a page is never half-read. -// The cursor is the next page to read, so a capped or drained run resumes -// there — after catching up from the last page first, so a run always starts -// with the newest posts; past the cursor the walk goes on to page 1 (pages -// shift as posts are deleted, so meeting an archived post there does not end -// it). +// redirects to the last page) and steps back a page at a time. Two walks share +// the pages, each with its own position (lib/forumWalk.ts, posts-state.json's +// `forum`): the CATCH-UP, from the last page down to the first page holding an +// archived post at or below the mark, then the HISTORY, from its own page down +// to page 1 (pages shift as posts are deleted, so meeting an archived post +// there does not end it). A capped catch-up keeps its own resume point and +// never moves the history's. A page whose posts are all archived is stepped +// past without counting against `pages` ("the latest N pages") or `limit` +// (posts), which are checked after a whole page so a page is never half-read. +// A full re-walk reads every page from the last to page 1. // // PACED, SERIAL, ONE BROWSER. One page at a time with a jittered pause between // loads (about 10–20 s by default; `pagePauseMs` from the channel), in one @@ -22,8 +23,10 @@ // A BROWSER CHECK (KiwiFlare's proof of work and the like) is waited out by the // loader, up to a minute; the profile keeps the clearance for later pages and // runs. A check that does not clear, a captcha, a login wall, a ban or a -// 403/429 STOPS the run with a typed failure and keeps the cursor — never a -// retry loop, never an attempt at a captcha. `needsCookies` is set where +// 403/429 STOPS the run with a typed failure (`block`) and keeps its +// positions — never a retry loop here, never an attempt at a captcha. The +// controller's retry-on-block waits a challenge or a refusal out (minutes, not +// seconds) and runs again. `needsCookies` is set where // Connect (a headed window on the same profile) is the way through. // // One parser for everything: xenforoParse.ts reads the live page here and the @@ -32,6 +35,11 @@ import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { getPaths } from "../lib/paths"; +import { + FORUM_DEFAULT_PAGE_PAUSE_SECONDS, + FORUM_MIN_PAGE_PAUSE_SECONDS, + type ForumWalkState, +} from "../lib/forumWalk"; import type { Post, PostMedia } from "../lib/posts"; import { registerSocialFetcher, @@ -61,6 +69,7 @@ import { type PostCaptureRecord, type PostCaptureState, } from "./postCapture"; +import { fixtureForumLoader, forumFixtureDir } from "./forumFixtureLoader"; import type { PageLike } from "./playwrightRuntime"; import { classifyForumPage, @@ -76,9 +85,9 @@ import { // page, which saves reading page 1 just to learn where the end is. export const LAST_PAGE_PROBE = 1_000_000; -export const DEFAULT_PAGE_PAUSE_MS = 12_000; +export const DEFAULT_PAGE_PAUSE_MS = FORUM_DEFAULT_PAGE_PAUSE_SECONDS * 1000; // The floor a configured pause is held to. -export const MIN_PAGE_PAUSE_MS = 5_000; +export const MIN_PAGE_PAUSE_MS = FORUM_MIN_PAGE_PAUSE_SECONDS * 1000; // The pause before a load: `base` jittered to [0.85, 1.65) of itself — 12 s // gives 10.2–19.8 s. @@ -147,15 +156,27 @@ export type ThreadWalkDeps = { sleep: (ms: number, signal: AbortSignal) => Promise<void>; }; +type WalkMode = "catch-up" | "history" | "full"; + // THE WALK. Pure over its deps: the loader hands back HTML, the parser reads it. // -// Two modes. "new": from the last page down, stopping at the first archived -// post (or the watermark) — what a run is for. "backfill": from a stored -// cursor down to page 1, where an archived post means nothing (pages shift as -// posts are deleted). A run with a cursor does both, newest first: it catches -// up from the last page, then continues the older pages at the cursor — so -// "the latest N pages" are always the newest, and an unfinished history is -// never forgotten. +// Three modes, every one from the thread's last page (lib/forumWalk.ts): +// +// "catch-up" — down to the first page holding an archived post at or below +// the mark (`forumWalk.newestPostId`; with no mark, any archived post), +// then on to the history walk at `forumWalk.historyPage`, never re-reading +// the band in between. A capped or interrupted catch-up keeps its place in +// `catchUpPage`; the next one, meeting the pages it read, jumps there. +// "history" — down to page 1, where an archived post means nothing (pages +// shift as posts are deleted). A first run (nothing archived) is one +// history walk from the last page. +// "full" — every page from the last to page 1 (`stopAtKnown: false`), every +// post handed back, archived or not, for the controller to update edits. +// +// A page whose posts are all archived never counts against `pages` or +// `limit` (except in a full re-walk, where every page is the point): the walk +// steps on down. Caps are checked after a whole page, so a page is never +// half-read. Every page's checkpoint carries the positions it leaves. export async function walkXenforoThread( input: PostFetchInput, deps: ThreadWalkDeps, @@ -165,85 +186,103 @@ export async function walkXenforoThread( if (!thread) { return { posts: [], complete: false, error: `${input.accountUrl} is not a XenForo thread URL (…/threads/<title>.<id>/).` }; } - let resumeAt: number | undefined; - if (input.cursor) { - resumeAt = Number(input.cursor); - if (!Number.isInteger(resumeAt) || resumeAt < 1) { + // The positions. A caller that derives none (a direct call with an old + // cursor) gets its cursor read as the history position. + let start: ForumWalkState; + if (input.forumWalk) { + start = input.forumWalk; + } else if (input.cursor) { + const n = Number(input.cursor); + if (!Number.isInteger(n) || n < 1) { return { posts: [], complete: false, error: `The stored resume point "${input.cursor}" is not a page number.` }; } + start = { historyPage: n }; + } else { + start = {}; } - const stopAtKnown = input.stopAtKnown ?? true; - // A full re-walk (stopAtKnown false) reads every page from the end; a - // cursor means nothing to it. - if (!stopAtKnown) resumeAt = undefined; - const watermark = input.since; + const full = input.stopAtKnown === false; + // Nothing archived: whatever positions were stored mean nothing. + const firstRun = !full && seenIds.size === 0; + const w: ForumWalkState = firstRun ? {} : { ...start }; + if (firstRun && (start.historyPage || start.newestPostId || start.complete)) { + onLog?.("Nothing is archived: the stored positions are dropped and the thread is read from its last page."); + } + const markId = w.newestPostId !== undefined ? Number(w.newestPostId) : undefined; + let mode: WalkMode = full ? "full" : firstRun ? "history" : "catch-up"; + const posts: Post[] = []; const taken = new Set<string>(); + const metOnPages = new Set<string>(); let returnedCount = 0; let loads = 0; - let pagesRead = 0; + let pagesCounted = 0; + let runTopId: number | undefined; + let runLast = 0; const fetchPage = async (url: string) => { if (loads++ > 0) await deps.sleep(deps.pauseMs(), signal); return deps.loader.load(url, signal); }; + // The resume point a stop leaves, for the log and for a caller that reads + // only the cursor. + const resumeCursor = (): string | undefined => { + if (w.catchUpPage) return String(w.catchUpPage); + if (!w.complete && w.historyPage) return String(w.historyPage); + return undefined; + }; + const stop = (extra: Partial<PostFetchResult> = {}): PostFetchResult => { + const cursor = resumeCursor(); + return { posts, complete: false, ...(cursor ? { cursor } : {}), forumWalk: { ...w }, ...extra }; + }; + const done = (): PostFetchResult => { + const missing = full && w.complete ? [...seenIds].filter((id) => !metOnPages.has(id)) : []; + return { + posts, + complete: !w.catchUpPage && (w.complete === true || w.historyPage === undefined), + forumWalk: { ...w }, + ...(missing.length > 0 ? { notSeen: missing } : {}), + }; + }; + + if (mode === "full") onLog?.("A full re-walk: every page from the last to page 1, archived posts re-read for edits."); - let mode: "new" | "backfill" = "new"; let page = LAST_PAGE_PROBE; - if (resumeAt) onLog?.(`An earlier run stopped at page ${resumeAt}: catching up from the last page first, then continuing there.`); - let lastPage: number | undefined; const visited = new Set<number>(); - const cursorOf = (n: number) => (n === LAST_PAGE_PROBE ? (resumeAt ? String(resumeAt) : undefined) : String(n)); - try { for (;;) { - if (signal.aborted) { - const cursor = cursorOf(page); - return { posts, complete: false, ...(cursor ? { cursor } : {}) }; - } + if (signal.aborted) return stop(); const url = xenforoPageUrl(thread, page); let load; try { load = await fetchPage(url); } catch (err) { - const cursor = cursorOf(page); - return { posts, complete: false, ...(cursor ? { cursor } : {}), error: (err as Error).message }; - } - if (signal.aborted) { - const cursor = cursorOf(page); - return { posts, complete: false, ...(cursor ? { cursor } : {}) }; + return stop({ error: (err as Error).message }); } + if (signal.aborted) return stop(); const block = classifyForumPage(load.html, load.status); if (block) { const why = forumBlockFailure(block, thread.host); - const cursor = cursorOf(page); onLog?.(`Page ${page === LAST_PAGE_PROBE ? "(last)" : page}: ${block.kind} — ${block.detail}.`); - return { - posts, - complete: false, - ...(cursor ? { cursor } : {}), + return stop({ error: why.error, + block: block.kind, ...(why.needsCookies ? { needsCookies: true } : {}), - }; + }); } const parsed = parseXenforoThreadPage(load.html, { channelSlug, pageUrl: load.url }); if (visited.has(parsed.page)) { - return { - posts, - complete: false, - ...(cursorOf(page) ? { cursor: cursorOf(page) } : {}), - error: `Asked for page ${page} and was shown page ${parsed.page} again; stopped rather than loop.`, - }; + return stop({ error: `Asked for page ${page} and was shown page ${parsed.page} again; stopped rather than loop.` }); } visited.add(parsed.page); page = parsed.page; - lastPage = Math.max(lastPage ?? 0, parsed.lastPage); - pagesRead++; - // Catching up has reached the pages the backfill has yet to read. - if (mode === "new" && resumeAt && page <= resumeAt) mode = "backfill"; - - let sawKnown = false; - let sawOld = false; + // The thread's last page as THIS run sees it (deletions can lower it). + runLast = Math.max(runLast, parsed.lastPage); + w.newestPage = runLast; + w.oldestPageReached = Math.min(w.oldestPageReached ?? page, page); + + let held = 0; + let own = 0; + let reachedMark = false; const fresh: Post[] = []; // Newest first within the page too, so the stops read in time order. for (const post of [...parsed.posts].reverse()) { @@ -258,12 +297,18 @@ export async function walkXenforoThread( } continue; } + own++; + metOnPages.add(post.id); + const idNum = Number(post.id); + if (runTopId === undefined || idNum > runTopId) runTopId = idNum; if (seenIds.has(post.id)) { - if (mode === "new" && stopAtKnown) sawKnown = true; - continue; - } - if (mode === "new" && watermark && post.createdAt <= watermark) { - sawOld = true; + held++; + if (mode === "catch-up" && (markId === undefined || idNum <= markId)) reachedMark = true; + // A full re-walk hands archived posts back, for their edits. + if (mode === "full" && !taken.has(post.id)) { + taken.add(post.id); + fresh.push(post); + } continue; } if (taken.has(post.id)) continue; @@ -271,54 +316,88 @@ export async function walkXenforoThread( fresh.push(post); } fresh.reverse(); + const newCount = fresh.filter((p) => !seenIds.has(p.id)).length; + const allHeld = mode !== "full" && own > 0 && held === own && newCount === 0; onLog?.( - `Page ${page}/${lastPage}: ${parsed.posts.length} post(s) parsed, ${fresh.length} new` + + `Page ${page}/${parsed.lastPage}: ${parsed.posts.length} post(s) parsed, ${newCount} new` + (load.challengeMs !== undefined ? ` (browser check cleared in ${Math.round(load.challengeMs / 1000)} s)` : "") + - (sawKnown ? ", reached already-archived posts" : "") + - (sawOld ? ", reached the watermark" : "") + + (reachedMark ? ", reached already-archived posts" : "") + ".", ); if (parsed.posts.length === 0 && page > 1) { // A thread page with no posts in it is not a page to step past // silently: it is most likely markup this parser does not know. - return { - posts, - complete: false, - cursor: String(page), - error: `Page ${page} of the thread parsed to no posts; stopped rather than walking on.`, - }; + return stop({ error: `Page ${page} of the thread parsed to no posts; stopped rather than walking on.` }); + } + if (!allHeld) { + pagesCounted++; + returnedCount += newCount; } let next = page - 1; - if (sawKnown || sawOld) { - if (!resumeAt) { - if (input.onCheckpoint && fresh.length > 0) await input.onCheckpoint({ posts: fresh, cursor: String(Math.max(1, next)) }); - else posts.push(...fresh); - return { posts, complete: true }; + let finished = false; + if (mode === "catch-up") { + if (reachedMark || next < 1) { + // Caught up: every post from here to the top is held. + if (runTopId !== undefined) w.newestPostId = String(Math.max(runTopId, markId ?? 0)); + delete w.catchUpPage; + if (next < 1) { + w.complete = true; + delete w.historyPage; + } + if (w.complete || w.historyPage === undefined) { + onLog?.(`Caught up to page ${w.newestPage}; ${w.complete ? "history complete" : "no older pages owed"}.`); + finished = true; + } else { + mode = "history"; + next = Math.min(w.historyPage, next); + onLog?.(`Caught up to page ${w.newestPage}; history resumes at page ${next}.`); + } + } else if (allHeld) { + // The pages an earlier, unfinished catch-up read: jump below them. + if (w.catchUpPage && w.catchUpPage < next) { + onLog?.(`Page ${page}: all held — an earlier catch-up read down to page ${w.catchUpPage + 1}; continuing there.`); + next = w.catchUpPage; + } else { + onLog?.(`Page ${page}: all held, skipping on.`); + } } - // Caught up: on to the older pages an earlier run left. - mode = "backfill"; - next = Math.min(resumeAt, next); - onLog?.(`Caught up with the archive; continuing the older pages at page ${next}.`); + if (!finished && mode === "catch-up") w.catchUpPage = next; + } else if (mode === "history") { + if (runTopId !== undefined && firstRun) w.newestPostId = String(runTopId); + if (allHeld) onLog?.(`Page ${page}: all held, skipping on.`); + } else { + // A full re-walk: everything from here to the top is now read. + if (runTopId !== undefined) w.newestPostId = String(Math.max(runTopId, markId ?? 0)); + delete w.catchUpPage; } - returnedCount += fresh.length; - if (input.onCheckpoint && fresh.length > 0) { - await input.onCheckpoint({ posts: fresh, cursor: String(Math.max(1, next)) }); + if (mode === "history" || mode === "full") { + if (next < 1) { + w.complete = true; + delete w.historyPage; + finished = true; + } else if (!w.complete) { + w.historyPage = w.historyPage === undefined || mode === "history" ? next : Math.min(w.historyPage, next); + } + } + + if (input.onCheckpoint) { + await input.onCheckpoint({ posts: fresh, cursor: String(Math.max(1, next)), forumWalk: { ...w } }); } else { posts.push(...fresh); } - if (next < 1) return { posts, complete: true }; - if (input.pages && pagesRead >= input.pages) { - onLog?.(`Read ${pagesRead} page(s), the cap for this run; the next run continues at page ${next}.`); - return { posts, complete: false, cursor: String(next) }; + if (finished) return done(); + if (input.pages && pagesCounted >= input.pages && !allHeld) { + onLog?.(`Read ${pagesCounted} page(s), the cap for this run; the next run continues at page ${next}.`); + return stop(); } - if (input.limit && returnedCount >= input.limit) { - return { posts, complete: false, cursor: String(next) }; + if (input.limit && returnedCount >= input.limit && !allHeld) { + return stop(); } if (input.drain?.aborted) { onLog?.(`Drained; the next run continues at page ${next}.`); - return { posts, complete: false, cursor: String(next), drained: true }; + return stop({ drained: true }); } page = next; } @@ -659,6 +738,11 @@ export const xenforoFetcher: SocialFetcher = { async fetch(input: PostFetchInput): Promise<PostFetchResult> { const thread = threadOrThrow(input.accountUrl); + // The e2e suite's saved pages (forumFixtureLoader.ts): no browser, no pause. + const fixtures = forumFixtureDir(); + if (fixtures) { + return walkXenforoThread(input, { loader: fixtureForumLoader(fixtures, thread), pauseMs: () => 0, sleep: async () => {} }); + } const loader = browserForumLoader(forumProfileDir(getPaths(), thread.host), { onLog: input.onLog }); return walkXenforoThread(input, { loader, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A forum thread's fetch resumes where it stopped instead of reading the thread again.** A forum channel now keeps two places: how far it has caught up with the newest posts, and where its walk back through the older pages stands. **Fetch posts** reads from the last page down to the newest post it already holds, then jumps straight to the older pages it has yet to read — a run capped at a few pages ("Latest N pages") no longer loses the older place, and a page whose posts are all held is stepped past without counting against the cap. Pages that shifted because posts were deleted are still read without a gap. **Full re-walk** (it replaces "Re-fetch full history" on a forum channel) asks first, with the page count and how long it takes at the channel's pace, then reads every page from the last to page 1: edited posts are updated, and posts no page shows any more are counted in the log and kept. The panel's status line says where both stand — "pages read 2338–2600 of 2600 · history to page 1 remaining: 2337 pages (~9.7 h)". The older place is checked against the pages the archive holds at every run, so a channel whose place was overwritten by the old single resume point heals on its next fetch. **Retry after a block** (the Forum session section) makes Fetch posts wait out a browser check that will not clear or a refused page — 30 minutes, then try again, up to 12 tries, say — and never retries a captcha or a login; `pnpm ops fetch-posts` takes `"retryOnBlock": {"minutes": 30, "max": 12}` (or `true` for the saved setting). Needs a restart of the editor. - **Wayback Machine captures of pages are records of their own.** A capture of a page that is not a video — an old blog post, a group's site, a channel's About page, a document taken down — goes into a **Wayback pages** channel: on the New channel form, paste a Wayback URL of such a page (`web.archive.org/web/*/example.com/blog*` scopes every capture under that path, `*.example.com` a whole domain, one capture's URL that page) or choose **Wayback pages** as the platform, and edit its targets (a URL, how it matches, optional dates). The channel page's **Import a capture** takes a capture's URL, or the page's own URL and a date for the capture nearest it, and imports it as one job at archive.org's pace: the page as captured is kept, its readable text, title, author, date, links and images become a record — searchable, in the MCP and on a built site like any post — dated by the page's own date when it gives one. A later capture of the same page is kept as a version of the first. **Re-extract** reads every kept capture again with no request. A capture of a video is still Import video's, and is refused here with a sentence saying so. An x.com or twitter.com capture is private exactly as X posts are. From a terminal: `pnpm ops import-page` (`dryRun` says what it would fetch) and `pnpm ops reextract-pages`; `pnpm archilyzer wayback pages import|reextract` run without the editor. Needs a restart of the editor. - **Scan a Wayback pages channel, then choose what to import.** A channel whose config names `wayback.targets` (a page, a prefix, a host or a domain, with optional dates) has a **Captures** tab: **Scan now** lists what the Wayback Machine holds of them — one row per distinct version of each page, with when it was first and last seen — without fetching a single page, at archive.org's pace, at most 50,000 rows a run; **Continue scan** picks up where a run stopped, and a later scan marks what is **new**. Filter by year, path and text, then **Import selected** or **Import all in range** (asked to confirm above 50): one import job per capture, one at a time. Rows already imported are marked and skipped. The same over HTTP: `pnpm ops wayback-scan --json '{"slug":"<slug>"}'` and `pnpm ops wayback-import --json '{"slug":"<slug>","year":"2014"}'` (both take `dryRun`); offline, `pnpm archilyzer wayback scan <slug>`. With `wayback.auto: true` the download lane imports the captures later scans add, at the same pace; it is off unless a channel turns it on. - **Wayback captures of Tumblr, Twitter, forums, Google Docs and YouTube About pages are read as their posts.** A Tumblr blog's post, index, tagged or archive page becomes one record per post (its date, tags, images and what it reblogged), and the same post seen on an index and on its own page is one record. An old Twitter profile or status page becomes one record per tweet — replies, retweets and quotes pointing at the tweets they answer, and the profile's bio, website and counts as one more — and a capture of X's later JavaScript app says it holds no posts. A captured XenForo thread page gives the same posts, with the same ids, that a forum channel of the thread holds. A Google Doc's mobilebasic or published page gives the document's text with its headings; its edit page says it holds no text and names the mobilebasic address to look for. A YouTube channel's About page gives how the channel described itself at that capture: description, links, joined date and counts. Nothing calls a model. diff --git a/editor/app/api/ops/fetch-posts/route.ts b/editor/app/api/ops/fetch-posts/route.ts @@ -2,18 +2,36 @@ import { fetchPostsAction } from "../../../channels/[slug]/socialActions"; import { jobResponse, ops, + OpsInputError, optBool, optPositiveInt, optString, reqSlug, + type OpsBody, } from "../_lib"; +import type { RetryOnBlock } from "yt-dlp-transcript-common/lib/forumWalk"; + +// `retryOnBlock`: `{ "minutes": N, "max": M }`, or `true` for the forum +// default in settings (`social.xenforo.retryOnBlock`; nothing when unset). +function optRetryOnBlock(body: OpsBody): RetryOnBlock | "settings" | undefined { + const v = body.retryOnBlock; + if (v === undefined || v === null || v === false) return undefined; + if (v === true) return "settings"; + if (typeof v === "object" && !Array.isArray(v)) { + const r = v as Record<string, unknown>; + if (typeof r.minutes === "number" && typeof r.max === "number") return { minutes: r.minutes, max: r.max }; + } + throw new OpsInputError('"retryOnBlock" must be { "minutes": N, "max": M } or true.'); +} export const dynamic = "force-dynamic"; -// POST { slug, full?, older?, floor?, from?, force?, limit?, pages?, queueKey? } -> { ok: true, jobId } +// POST { slug, full?, older?, floor?, from?, force?, limit?, pages?, retryOnBlock?, queueKey? } -> { ok: true, jobId } // // `pages` caps how many pages a run reads, for a channel read page by page (a -// forum thread: its latest N pages). +// forum thread: its latest N pages). `retryOnBlock` ({minutes, max}, or true +// for the forum default in settings) waits out a challenge or refusal page and +// runs again, max tries in all — never on a captcha or a login. // // A social channel's "Fetch posts" button, over HTTP — and its "Re-fetch full // history" (`full`) and "Fetch older posts" (`older`, with an optional `floor` @@ -29,7 +47,7 @@ export const dynamic = "force-dynamic"; export async function POST(request: Request) { return ops( request, - ["slug", "full", "older", "floor", "from", "force", "limit", "pages", "queueKey"], + ["slug", "full", "older", "floor", "from", "force", "limit", "pages", "retryOnBlock", "queueKey"], async (body) => { const slug = reqSlug(body, "slug"); return jobResponse( @@ -43,6 +61,7 @@ export async function POST(request: Request) { optBool(body, "force"), optPositiveInt(body, "pages"), optString(body, "from"), + optRetryOnBlock(body), ), ); }, diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx @@ -12,9 +12,15 @@ import { connectForumSessionAction, fetchPostsAction, importForumPagesAction, + setForumRetryOnBlockAction, setPostFetcherAction, } from "../socialActions"; import type { ForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession"; +import { + describeRetryOnBlock, + roughDuration, + type RetryOnBlock, +} from "yt-dlp-transcript-common/lib/forumWalk"; import { SocialPostTools } from "./SocialPostTools"; export type SocialChannelState = { @@ -42,6 +48,15 @@ export type SocialChannelState = { platform?: string; // A forum thread's browser session (its host's profile), when it is one. forumSession?: ForumSessionStatus; + // A forum thread's two walks (lib/forumWalk.ts): the status line, the + // thread's last page as last seen, the mean seconds a page takes at the + // channel's pace, and the Fetch posts button's retry after a block. + forumWalk?: { + status: string | null; + lastPage: number | null; + pageSeconds: number; + retryOnBlock: RetryOnBlock | null; + }; }; export function SocialChannelPanel({ @@ -112,8 +127,13 @@ export function SocialChannelPanel({ } }); + const [fetchNote, setFetchNote] = useState<string | null>(null); + const [fetchErr, setFetchErr] = useState<string | null>(null); const run = (full: boolean, older = false) => startTransition(async () => { + setFetchNote(null); + setFetchErr(null); + setConfirmRewalk(false); const n = Number(pages); const res = await fetchPostsAction( slug, @@ -123,11 +143,45 @@ export function SocialChannelPanel({ older || undefined, undefined, undefined, - forum && pages.trim() && Number.isInteger(n) && n > 0 ? n : undefined, + forum && !full && pages.trim() && Number.isInteger(n) && n > 0 ? n : undefined, + undefined, + // A forum thread's Fetch posts waits out a block as settings say. + forum && !full ? "settings" : undefined, ); // The job streams to the jobs page; nothing to consume here, but the // stream must be released or its buffered chunks leak. - if (res.ok) void res.stream.cancel(); + if (res.ok) { + void res.stream.cancel(); + if (forum) setFetchNote(full ? "Full re-walk queued — its log is on the jobs page." : "Fetch queued — its log is on the jobs page."); + } else if (forum) { + setFetchErr(res.error); + } + }); + + // FULL RE-WALK (a forum thread): every page from the last to page 1, asked + // for twice — it is hours of paced loads. + const [confirmRewalk, setConfirmRewalk] = useState(false); + const walk = state.forumWalk; + const rewalkPages = walk?.lastPage ?? null; + const rewalkTime = rewalkPages && walk ? roughDuration(rewalkPages * walk.pageSeconds) : null; + + // RETRY AFTER A BLOCK: settings.social.xenforo.retryOnBlock. + const [retry, setRetry] = useState<RetryOnBlock | null>(walk?.retryOnBlock ?? null); + const [retryMinutes, setRetryMinutes] = useState(String(walk?.retryOnBlock?.minutes ?? 30)); + const [retryMax, setRetryMax] = useState(String(walk?.retryOnBlock?.max ?? 12)); + const saveRetry = (on: boolean) => + startTransition(async () => { + setForumNote(null); + setForumErr(null); + const res = await setForumRetryOnBlockAction( + on ? { minutes: Number(retryMinutes), max: Number(retryMax) } : null, + ); + if (res.ok) { + setRetry(res.retryOnBlock); + setForumNote(res.retryOnBlock ? "Retry after a block saved." : "Retry after a block turned off."); + } else { + setForumErr(res.error); + } }); return ( @@ -249,16 +303,29 @@ export function SocialChannelPanel({ > Check deleted posts </button> - <button - type="button" - onClick={() => run(true)} - disabled={pending} - aria-label="refetch full history" - title="Re-walk the account's whole history. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates." - className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" - > - Re-fetch full history - </button> + {forum ? ( + <button + type="button" + onClick={() => setConfirmRewalk(true)} + disabled={pending || confirmRewalk} + aria-label="full re-walk" + title="Re-read every page from the last to page 1: new posts added, edited ones updated, posts no page shows any more counted in the log." + className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" + > + Full re-walk + </button> + ) : ( + <button + type="button" + onClick={() => run(true)} + disabled={pending} + aria-label="refetch full history" + title="Re-walk the account's whole history. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates." + className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" + > + Re-fetch full history + </button> + )} {state.canFetchOlder && ( <button type="button" @@ -273,6 +340,52 @@ export function SocialChannelPanel({ )} </div> + {forum && confirmRewalk && ( + <div + role="alertdialog" + aria-label="confirm full re-walk" + className="mt-3 flex flex-wrap items-center gap-2 rounded border border-warning/40 bg-warning-soft px-3 py-2 text-xs" + > + <span> + {rewalkPages + ? `Re-read all ${rewalkPages} pages, from the last to page 1 — ${rewalkTime} at this channel's pace.` + : "Re-read every page, from the last to page 1, at this channel's pace."} + </span> + <button + type="button" + onClick={() => run(true)} + disabled={pending} + aria-label="start full re-walk" + className="rounded-md bg-primary px-2 py-0.5 font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50" + > + Start full re-walk + </button> + <button + type="button" + onClick={() => setConfirmRewalk(false)} + aria-label="cancel full re-walk" + className="rounded-md border border-border px-2 py-0.5 hover:bg-muted" + > + Cancel + </button> + </div> + )} + {forum && walk?.status && ( + <p aria-label="forum walk" className="mt-3 text-xs text-muted-foreground"> + {walk.status} + </p> + )} + {fetchNote && ( + <p role="status" className="mt-2 text-xs text-success"> + {fetchNote} + </p> + )} + {fetchErr && ( + <p role="alert" className="mt-2 text-xs text-destructive"> + {fetchErr} + </p> + )} + {/* The two failure surfaces a social channel actually has. */} {state.needsCookies && ( <p @@ -345,6 +458,60 @@ export function SocialChannelPanel({ </button> </div> + <div className="flex flex-col gap-1 border-t border-border pt-3 text-sm"> + <span className="font-medium">Retry after a block</span> + <span aria-label="retry after a block" className="text-xs text-muted-foreground"> + Fetch posts: {describeRetryOnBlock(retry ?? undefined)} (a captcha or a login is never retried) + </span> + <div className="flex flex-wrap items-center gap-2"> + <label className="flex items-center gap-1"> + <span>Wait</span> + <input + type="number" + min={5} + inputMode="numeric" + value={retryMinutes} + onChange={(e) => setRetryMinutes(e.target.value)} + aria-label="retry minutes" + className="w-20 rounded border border-border bg-card px-2 py-1 text-sm" + /> + <span>min, up to</span> + </label> + <label className="flex items-center gap-1"> + <input + type="number" + min={1} + inputMode="numeric" + value={retryMax} + onChange={(e) => setRetryMax(e.target.value)} + aria-label="retry tries" + className="w-16 rounded border border-border bg-card px-2 py-1 text-sm" + /> + <span>tries</span> + </label> + <button + type="button" + onClick={() => saveRetry(true)} + disabled={pending} + aria-label="save retry after a block" + className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" + > + Save + </button> + {retry && ( + <button + type="button" + onClick={() => saveRetry(false)} + disabled={pending} + aria-label="turn off retry after a block" + className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" + > + Turn off + </button> + )} + </div> + </div> + <div className="border-t border-border pt-3"> <label className="flex flex-col gap-1 text-sm"> <span className="font-medium">Import saved pages</span> diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -20,6 +20,13 @@ import "yt-dlp-transcript-common/social/xNitterFetcher"; import "yt-dlp-transcript-common/social/xenforoFetcher"; import { readForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession"; import { parseXenforoThreadUrl } from "yt-dlp-transcript-common/social/xenforoParse"; +import { + deriveForumWalk, + describeForumWalk, + FORUM_DEFAULT_PAGE_PAUSE_SECONDS, + FORUM_MIN_PAGE_PAUSE_SECONDS, + meanPagePauseSeconds, +} from "yt-dlp-transcript-common/lib/forumWalk"; import { SocialChannelPanel } from "./components/SocialChannelPanel"; import { WaybackPagesPanel } from "./components/WaybackPagesPanel"; import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; @@ -184,6 +191,22 @@ export default async function ChannelDetailPage({ const forumSession = forumThread ? await readForumSessionStatus(paths, forumThread.host) : undefined; + // A forum thread's two walks (release 37 lane G): the positions the next + // run starts from — derived from the archived posts' pages exactly as the + // fetch derives them, so a healed position shows before the run. + const forumPageSeconds = meanPagePauseSeconds( + config.postPagePauseSeconds ?? FORUM_DEFAULT_PAGE_PAUSE_SECONDS, + FORUM_MIN_PAGE_PAUSE_SECONDS, + ); + const forumDerived = forumThread + ? deriveForumWalk( + fetchState?.forum, + fetchState?.cursor, + (await readAllPosts(channelRoot)).flatMap((p) => + p.platform === "xenforo" && typeof p.forum?.page === "number" ? [p.forum.page] : [], + ), + ).walk + : null; // A WAYBACK PAGES channel (release 37): its captures, its scope, Import a // capture — no fetcher, nothing to fetch. const wayback = isWaybackPagesChannel(config) @@ -243,6 +266,16 @@ export default async function ChannelDetailPage({ accountUrl: config.url, platform: config.platform, ...(forumSession ? { forumSession } : {}), + ...(forumDerived + ? { + forumWalk: { + status: describeForumWalk(forumDerived, forumPageSeconds), + lastPage: forumDerived.newestPage ?? null, + pageSeconds: forumPageSeconds, + retryOnBlock: getSettings().social.xenforo?.retryOnBlock ?? null, + }, + } + : {}), }} /> )} diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -27,7 +27,13 @@ import { fetchPosts, FULL_AND_OLDER_REFUSAL, OLDER_FROM_REFUSAL, olderPostsProblem, + RETRY_AND_OLDER_REFUSAL, } from "yt-dlp-transcript-common/controller/fetchPosts"; +import { + retryOnBlockProblem, + type RetryOnBlock, +} from "yt-dlp-transcript-common/lib/forumWalk"; +import { saveSettings } from "../../settings/saveSettings"; import { isUtcDay } from "yt-dlp-transcript-common/social/olderBackfill"; import { checkPostAvailability, @@ -170,8 +176,17 @@ export async function fetchPostsAction( pages?: number, // The older walk's fresh start date (FetchPostsOptions.from). from?: string, + // Wait out a challenge or refusal page and run again (release 37 lane G): + // `{minutes, max}`, or "settings" for `settings.social.xenforo.retryOnBlock` + // (a forum thread's Fetch posts button; nothing when it is unset). + retryOnBlock?: RetryOnBlock | "settings", ): Promise<StreamActionResult> { if (full && older) return { ok: false, error: FULL_AND_OLDER_REFUSAL }; + if (retryOnBlock && older) return { ok: false, error: RETRY_AND_OLDER_REFUSAL }; + const retry = + retryOnBlock === "settings" ? getSettings().social.xenforo?.retryOnBlock : retryOnBlock; + const retryProblem = retryOnBlockProblem(retry); + if (retryProblem) return { ok: false, error: retryProblem }; if (pages !== undefined && !(Number.isInteger(pages) && pages > 0)) { return { ok: false, error: "Pages must be a whole number above 0." }; } @@ -226,7 +241,17 @@ export async function fetchPostsAction( spec: { kind: "fetch-posts", slug, - params: { queueKey, full, limit, older, floor, force, ...(pages ? { pages } : {}), ...(from ? { from } : {}) }, + params: { + queueKey, + full, + limit, + older, + floor, + force, + ...(pages ? { pages } : {}), + ...(from ? { from } : {}), + ...(retry ? { retryOnBlock: retry } : {}), + }, }, fn: async (onLog, signal, _progress, ctx) => { const result = await fetchPosts({ @@ -240,6 +265,7 @@ export async function fetchPostsAction( force, limit, pages, + ...(retry ? { retryOnBlock: retry } : {}), onLog, signal, // A drained fetch keeps its resume point and returns ok: the job @@ -398,3 +424,25 @@ export async function importForumPagesAction( }, }); } + +// RETRY AFTER A BLOCK — `settings.social.xenforo.retryOnBlock`, the forum +// Fetch posts button's default (release 37 lane G). Null turns it off (the key +// is removed). The rest of `social` is carried as it is: saveSettings merges +// one level deep. +export async function setForumRetryOnBlockAction( + retry: RetryOnBlock | null, +): Promise<{ ok: true; retryOnBlock: RetryOnBlock | null } | { ok: false; error: string }> { + const problem = retry ? retryOnBlockProblem(retry) : null; + if (problem) return { ok: false, error: problem }; + const social = getSettings().social; + const { retryOnBlock: _was, ...restXf } = social.xenforo ?? {}; + const xenforo = retry ? { ...restXf, retryOnBlock: retry } : restXf; + const { xenforo: _old, ...rest } = social; + try { + await saveSettings({ social: { ...rest, ...(Object.keys(xenforo).length > 0 ? { xenforo } : {}) } }); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + revalidatePath("/channels"); + return { ok: true, retryOnBlock: getSettings().social.xenforo?.retryOnBlock ?? null }; +} diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -400,6 +400,10 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { bool(p.force), num(p.pages), str(p.from), + // The retry the job was queued with, resolved (never "settings"). + p.retryOnBlock && typeof p.retryOnBlock === "object" + ? (p.retryOnBlock as { minutes: number; max: number }) + : undefined, ); }, // The ids are the spec's own (a capture is OF specific posts, unlike a diff --git a/editor/app/settings/xSessionActions.ts b/editor/app/settings/xSessionActions.ts @@ -39,14 +39,16 @@ import { import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility"; import { saveSettings } from "./saveSettings"; -// `social.x` is ONE value to saveSettings, whose merge is one level deep: a -// patch naming `social: { x }` replaces the whole X block. So each X choice is +// `social` is ONE value to saveSettings, whose merge is one level deep: a +// patch naming `social: { x }` replaces the whole social block. So each X choice is // written over the block as it is now, with only its own key changed — the // login source keeps the visibility, and the visibility keeps the source. function socialXPatch( change: (x: XSocialSettings) => XSocialSettings, ): { social: { x: XSocialSettings } } { - return { social: { x: change({ ...getSettings().social.x }) } }; + // The rest of the block (a forum thread's `xenforo`) is carried as it is. + const social = getSettings().social; + return { social: { ...social, x: change({ ...social.x }) } }; } // Every session action returns the source in use beside the profile's status: diff --git a/editor/e2e/forum-resume.spec.ts b/editor/e2e/forum-resume.spec.ts @@ -0,0 +1,148 @@ +// A FORUM THREAD's two buttons (release 37 lane G): Fetch posts catches up +// and then continues the history where it stopped — never re-reading the band +// between — and Full re-walk re-reads every page, behind a confirm with the +// page count and the time at the channel's pace. Plus the status line and the +// retry after a block. +// +// The forum is invented and never contacted: the test server's forum fetcher +// reads SYNTHETIC saved pages from FORUM_FIXTURE_DIR (`dev:test` / `start:test` +// set it to <data root>/test-transcripts/.forum-fixture; see +// common/social/forumFixtureLoader.ts), written here from a FakeForumThread. + +import { test, expect, type Page } from "@playwright/test"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { baseUrl } from "./baseUrl"; +import { pathExists, readJson, resetData, testPaths } from "./helpers"; +import { THREAD_URL } from "yt-dlp-transcript-common/social/__fixtures__/xenforoPages"; +import { FakeForumThread } from "yt-dlp-transcript-common/social/__fixtures__/fakeForumThread"; + +const SLUG = "teapot-thread"; + +type ForumState = { + forum?: { + newestPage?: number; + newestPostId?: string; + catchUpPage?: number; + historyPage?: number; + oldestPageReached?: number; + complete?: boolean; + }; + cursor?: string; +}; + +const channelRoot = () => path.join(testPaths().transcriptsDir, "channels", SLUG); +const fixtureDir = () => path.join(testPaths().transcriptsDir, ".forum-fixture"); + +async function state(): Promise<ForumState | null> { + const file = path.join(channelRoot(), "posts-state.json"); + return (await pathExists(file)) ? await readJson<ForumState>(file) : null; +} + +async function archived(): Promise<string[]> { + const file = path.join(channelRoot(), "posts-archive"); + if (!(await pathExists(file))) return []; + return (await readFile(file, "utf8")).split("\n").filter(Boolean).map((l) => l.split(" ")[1]).sort(); +} + +// A fetch's LAST write is the channel's lastSyncedAt (after posts-state.json): +// a new stamp means the job is done and its state final. +const lastSynced = async () => + (await readJson<{ lastSyncedAt?: string }>(path.join(channelRoot(), "config.json"))).lastSyncedAt; + +async function untilDone(before: string | undefined) { + await expect.poll(lastSynced, { timeout: 30_000 }).not.toBe(before); +} + +async function fetchOnce(page: Page, pages: string) { + await page.getByLabel("pages to fetch").fill(pages); + const before = await lastSynced(); + await page.getByRole("button", { name: "fetch posts" }).click(); + await expect(page.getByRole("status").filter({ hasText: "Fetch queued" })).toBeVisible(); + await untilDone(before); +} + +test("a forum thread: Fetch posts resumes the history, Full re-walk asks first, the retry is a setting", async ({ page }) => { + await resetData("empty"); + await mkdir(channelRoot(), { recursive: true }); + await writeFile( + path.join(channelRoot(), "config.json"), + JSON.stringify({ + handling: "transcribe", + sourceKind: "social", + platform: "xenforo", + postFetcher: "xenforo-thread", + socialHandle: "the-teapot-collectors-thread.4242", + name: "Teapot thread", + url: THREAD_URL, + }), + ); + const thread = new FakeForumThread(30); // 10 pages + await thread.writeTo(fixtureDir()); + await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); + + await page.goto(`/channels/${SLUG}`); + await expect(page.getByRole("button", { name: "fetch posts" })).toBeVisible(); + await expect(page.getByRole("button", { name: "full re-walk" })).toBeVisible(); + await expect(page.getByRole("button", { name: "refetch full history" })).toHaveCount(0); + await expect(page.getByLabel("forum walk")).toHaveCount(0); + + // The latest 4 pages (10–7): the history stops at 6. + await fetchOnce(page, "4"); + expect((await state())?.forum).toEqual({ newestPage: 10, oldestPageReached: 7, historyPage: 6, newestPostId: "9030" }); + expect((await state())?.cursor).toBeUndefined(); + + // Six new posts (pages 11–12); a 1-page run catches up page 12 only — the + // history position stays where it was. + thread.add(6); + await thread.writeTo(fixtureDir()); + await page.reload(); + await expect(page.getByLabel("forum walk")).toHaveText( + "pages read 7–10 of 10 · history to page 1 remaining: 6 pages (~2 min)", + ); + await fetchOnce(page, "1"); + expect((await state())?.forum).toMatchObject({ newestPage: 12, catchUpPage: 11, historyPage: 6, newestPostId: "9030" }); + await page.reload(); + await expect(page.getByLabel("forum walk")).toHaveText( + "pages read 7–12 of 12 · catch-up unfinished at page 11 · history to page 1 remaining: 6 pages (~2 min)", + ); + + // No cap: the rest of the catch-up (11), then the history from 6 to 1. + await fetchOnce(page, ""); + expect((await state())?.forum).toMatchObject({ newestPage: 12, newestPostId: "9036", complete: true }); + expect(await archived()).toEqual(thread.ids().sort()); + await page.reload(); + await expect(page.getByLabel("forum walk")).toHaveText("pages read 1–12 of 12 · history complete"); + + // FULL RE-WALK asks first: every page, and the time at the channel's pace. + await page.getByRole("button", { name: "full re-walk" }).click(); + const confirm = page.getByRole("alertdialog", { name: "confirm full re-walk" }); + await expect(confirm).toContainText("Re-read all 12 pages, from the last to page 1 — ~3 min at this channel's pace."); + await page.getByRole("button", { name: "cancel full re-walk" }).click(); + await expect(confirm).toHaveCount(0); + const before = await lastSynced(); + await page.getByRole("button", { name: "full re-walk" }).click(); + await page.getByRole("button", { name: "start full re-walk" }).click(); + await expect(page.getByRole("status").filter({ hasText: "Full re-walk queued" })).toBeVisible(); + await untilDone(before); + expect((await state())?.forum).toMatchObject({ complete: true, newestPostId: "9036" }); + expect(await archived()).toEqual(thread.ids().sort()); + + // RETRY AFTER A BLOCK: off until set; saved to settings.social.xenforo. + await expect(page.getByLabel("retry after a block")).toContainText("Fetch posts: off"); + await page.getByLabel("retry minutes").fill("30"); + await page.getByLabel("retry tries").fill("12"); + await page.getByRole("button", { name: "save retry after a block" }).click(); + await expect(page.getByLabel("retry after a block")).toContainText("wait 30 min after a block, up to 12 tries"); + await expect + .poll(async () => (await readJson<{ social?: { xenforo?: unknown } }>(testPaths().settingsFile)).social?.xenforo) + .toEqual({ retryOnBlock: { minutes: 30, max: 12 } }); + await page.getByLabel("retry minutes").fill("2"); + await page.getByRole("button", { name: "save retry after a block" }).click(); + await expect(page.getByRole("alert").filter({ hasText: "minutes must be a whole number from 5" })).toBeVisible(); + await page.getByRole("button", { name: "turn off retry after a block" }).click(); + await expect(page.getByLabel("retry after a block")).toContainText("Fetch posts: off"); + await expect + .poll(async () => (await readJson<{ social?: { xenforo?: unknown } }>(testPaths().settingsFile)).social?.xenforo) + .toBeUndefined(); +}); diff --git a/editor/package.json b/editor/package.json @@ -5,8 +5,8 @@ "type": "module", "scripts": { "dev": "next dev --port ${EDITOR_PORT:-3001}", - "dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}", - "start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}", + "dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs FORUM_FIXTURE_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.forum-fixture next dev --port ${PORT:-3011}", + "start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs FORUM_FIXTURE_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.forum-fixture next start --port ${PORT:-3011}", "build": "next build", "start": "UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next start --port ${EDITOR_PORT:-3001}", "test": "tsx --test \"app/**/*.test.ts\" \"e2e/*.unit.ts\"", diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1232,7 +1232,12 @@ export function usage() { ' "YYYY-MM-DD" starts the walk afresh there, replacing its saved place', ' (and a "complete") — for a gap above one surviving old post. "limit": N caps', ' the posts one run reads; "pages": N caps the pages (a forum thread: its', - ' latest N pages). "full" and "older" together are refused. An', + ' latest N pages). A forum thread keeps two positions: a run catches up', + ' from the last page, then continues the history where it stopped;', + ' "full": true is its full re-walk (every page, edits updated).', + ' "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default', + ' in settings) waits out a challenge or refusal page and runs again, max', + ' tries in all. "full" and "older" together are refused. An', ' older walk over an account that shows no posts (nothing archived, and', ' the last timeline fetch read none) is refused unless "force": true. A', " drained fetch stops at its next resume point and the next run resumes.",