Archilyzer · Source

archilyzer

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

commit e4228d5638b5423e5cc460364b9709b6273c300f
parent 0cd0e3fa249950c9b6222d3c339d2040cb752e8e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 17 Nov 2026 21:20:48 -0500

x-trending review 1 (SHOULD 3-7, nits): a read never hangs, never loses its capture, and leaves X alone after a 429

Reader (social/xTrendingRead.ts):
- every page call is raced against a deadline and the job's cancel: the load 75 s; a
  scroll, the address and the screenshot 20 s each; closing the browser 10 s (then
  killed where the runtime names its browser); the whole read 6 minutes. Past any of
  them the read ends "deadline" with a sentence, the capture kept.
- a GraphQL 403 stops the read at once ("forbidden"); beside a login page it is the
  login wall's, beside a 429 the rate limit's.
- nothing is appended to responses.jsonl once the read has returned; a throw while
  reading one answer costs that answer (no unhandled rejection).
- a context whose first page cannot be made is closed, headless or headed.

Controller (controller/readXTrending.ts):
- read.json is written when the read starts and again when it ends, whatever the
  parse did; a parse that throws is the read's "error" with its sentence, and the
  capture is parsed again offline. A read dir with its answers and no record is
  reparsed once "url" names the page.
- a 429 sets a 15-minute cooldown on the twitter platform entry (the existing
  platformBackoff, through a new recordPlatformCooldown), which the read's enqueue
  and start both refuse on; the failure sentence says until when. A clean read
  settles it.
- a 403 fails with its own sentence and raises no login alert.
- the plan validates the slug itself.

Store: trending/reads/.gitignore ("*") is written whenever the reads directory is
made; a reparse updates the topic's per-read posts and added. Parser: media kinds by
own key only.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/controller/readXTrending.test.ts | 173+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/controller/readXTrending.ts | 194+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/jobs/downloadBackoff.ts | 22++++++++++++++++++++++
Mcommon/lib/xTrending/store.test.ts | 2+-
Mcommon/lib/xTrending/store.ts | 33+++++++++++++++++++++++++++++----
Mcommon/social/xTrendingParse.test.ts | 5+++++
Mcommon/social/xTrendingParse.ts | 5+++--
Mcommon/social/xTrendingRead.test.ts | 202++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/social/xTrendingRead.ts | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
9 files changed, 745 insertions(+), 55 deletions(-)

diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts @@ -45,26 +45,33 @@ function corpus(name: string): Paths { return { transcriptsDir, channelsDir } as unknown as Paths; } -const withProfile = { hasProfile: async () => true }; +const withProfile = { hasProfile: async () => true, held: async () => null }; async function run( paths: Paths, trending: FakeTrendingPage, ask: Partial<ReadXTrendingAsk> = {}, - over: { readId?: string; at?: string; profileBusy?: () => string | null } = {}, -): Promise<{ result: ReadXTrendingResult; notes: Array<Record<string, unknown>>; log: string[] }> { + over: { readId?: string; at?: string; profileBusy?: () => string | null; held?: () => Promise<string | null>; ingest?: never; openPage?: never } = {}, +): Promise<{ result: ReadXTrendingResult; notes: Array<Record<string, unknown>>; log: string[]; limited: number; cleaned: number }> { const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL, ...ask }, withProfile); assert.ok(planned.ok, planned.ok ? "" : planned.error); assert.equal(planned.plan.mode, "read"); const notes: Array<Record<string, unknown>> = []; const log: string[] = []; + let limited = 0; + let cleaned = 0; + const at = Date.parse(over.at ?? "2026-11-17T10:00:00.000Z"); const page = fakeTrendingPage(() => ({ trending })); const result = await runXTrendingRead({ paths, plan: planned.plan as never, onLog: (l) => log.push(l), deps: { - openPage: async () => ({ page, close: async () => {} }), + openPage: over.openPage ?? (async () => ({ page, close: async () => {} })), + held: over.held ?? (async () => null), + noteRateLimit: async () => (limited++, at + 15 * 60_000), + noteClean: async () => void cleaned++, + ...(over.ingest ? { ingest: over.ingest } : {}), pauseMs: () => 0, pause: async () => {}, now: () => Date.parse(over.at ?? "2026-11-17T10:00:00.000Z"), @@ -76,7 +83,7 @@ async function run( }, }, }); - return { result, notes, log }; + return { result, notes, log, limited, cleaned }; } const root = (paths: Paths) => path.join(paths.channelsDir, "trending"); @@ -93,7 +100,7 @@ test("every refusal before a job is a sentence", async () => { assert.equal(await error(planReadXTrending(paths, { slug: "nope", url: FIXTURE_TREND_URL }, withProfile)), "No such channel: nope"); assert.match(await error(planReadXTrending(paths, { slug: "account-x", url: FIXTURE_TREND_URL }, withProfile)), /account-x is not an X trending library/); assert.match(await error(plan({})), /Give "url" .* or "reparse"/); - assert.match(await error(plan({ url: FIXTURE_TREND_URL, reparse: READ_1 })), /one of them/); + assert.match(await error(plan({ url: FIXTURE_TREND_URL, reparse: READ_1 })), /holds no saved read/); assert.match(await error(plan({ url: "https://x.com/example/status/1" })), /not a trending page URL/); assert.match(await error(plan({ url: FIXTURE_TREND_URL, scrolls: 21 })), /"scrolls" is a whole number, 1–20/); assert.match(await error(plan({ url: FIXTURE_TREND_URL, posts: 201 })), /"posts" is a whole number, 1–200/); @@ -240,16 +247,19 @@ test("a login wall fails with its sentence, writes no post and raises the X aler test("a 429 fails with its sentence, keeps what was read, and raises no alert", async () => { const paths = corpus("limited"); const f = fixtureTrendingResponses(); - const { result, notes } = await run(paths, { + const { result, notes, limited, cleaned } = await run(paths, { load: [f.load[1], { url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 429, text: "" }], scrolls: f.scrolls, }); + // X is left alone for 15 minutes, and the sentence says until when. + assert.equal(limited, 1); + assert.equal(cleaned, 0); + assert.match(result.sentence, /No trending read starts before 10:15 UTC \(15 min\); nothing retries by itself\./); assert.equal(result.ok, false); assert.equal(result.outcome, "rate-limit"); assert.equal(result.scrolls, 0); assert.match(result.sentence, /^X answered 429 \(rate limit\)/); assert.match(result.sentence, /3 posts read before it were kept \(3 new\)\./); - assert.match(result.sentence, /nothing retries by itself/); assert.deepEqual(notes, []); assert.equal((await readXTrendingPosts(root(paths))).length, 3); }); @@ -278,3 +288,150 @@ test("a Connect or Refresh in flight refuses the read at its start: no browser o assert.equal(result.sentence, "X's connect is already running."); assert.equal(existsSync(path.join(root(paths), "trending")), false); }); + +// --- review 1 --------------------------------------------------------------- + +test("a slug is checked by the plan itself, before it becomes a path", async () => { + const paths = corpus("slug"); + for (const slug of ["../trending", "a/b", "", ".hidden"]) { + const r = await planReadXTrending(paths, { slug, url: FIXTURE_TREND_URL }, withProfile); + assert.equal(r.ok, false); + assert.match(r.ok ? "" : r.error, /is not a valid channel slug/); + } +}); + +test("X cooling down after a rate limit refuses a read at enqueue and at its start: no browser opens", async () => { + const paths = corpus("held"); + const sentence = "X answered a rate limit (429) a short while ago: no trending read starts before 10:15 UTC (12 min from now). Ask again then; nothing retries by itself."; + const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL }, { hasProfile: async () => true, held: async () => sentence }); + assert.deepEqual(planned, { ok: false, error: sentence }); + // Queued before the rate limit, started after it. + let opened = 0; + const { result } = await run(paths, fixtureTrendingResponses(), {}, { + held: async () => sentence, + openPage: (async () => { + opened++; + throw new Error("must not open"); + }) as never, + }); + assert.equal(result.ok, false); + assert.equal(result.outcome, "rate-limit"); + assert.equal(result.sentence, sentence); + assert.equal(opened, 0); + assert.equal(existsSync(path.join(root(paths), "trending")), false); +}); + +test("a clean read settles X's cooldown; the real cooldown is 15 minutes on the twitter platform entry", async () => { + const paths = corpus("clean"); + const { cleaned, limited } = await run(paths, fixtureTrendingResponses()); + assert.equal(cleaned, 1); + assert.equal(limited, 0); + const { X_RATE_LIMIT_HOLD_MS } = await import("./readXTrending"); + assert.equal(X_RATE_LIMIT_HOLD_MS, 15 * 60_000); +}); + +test("a 403 fails with its own sentence, keeps what was read, and raises no login alert", async () => { + const paths = corpus("forbidden"); + const f = fixtureTrendingResponses(); + const { result, notes, limited } = await run(paths, { + load: [f.load[1], { url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 403, body: { errors: [{ code: 200 }] } }], + scrolls: f.scrolls, + }); + assert.equal(result.ok, false); + assert.equal(result.outcome, "forbidden"); + assert.equal(result.scrolls, 0); + assert.match(result.sentence, /^X answered 403 \(forbidden\) to the page's own request: the read stopped at once/); + assert.match(result.sentence, /3 posts read before it were kept \(3 new\)\./); + assert.match(result.sentence, /not taken for a lost login and no alert was raised/); + assert.deepEqual(notes, []); + assert.equal(limited, 0); + assert.equal((await readXTrendingPosts(root(paths))).length, 3); +}); + +test("a page that stops answering fails with a sentence, the capture kept", async () => { + const paths = corpus("hung"); + const base = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); + const page = { ...base, evaluate: (fn: string) => (fn.includes("scrollTo") ? Promise.reject(Object.assign(new Error("the page did not answer within 20 s (scrolling)"), { name: "PageDeadlineError" })) : base.evaluate(fn)) }; + const { PageDeadlineError } = await import("../social/xTrendingRead"); + const hung = { ...base, evaluate: (fn: string) => (fn.includes("scrollTo") ? Promise.reject(new PageDeadlineError("scrolling", 20_000)) : base.evaluate(fn)) }; + void page; + const { result } = await run(paths, fixtureTrendingResponses(), {}, { openPage: (async () => ({ page: hung, close: async () => {} })) as never }); + assert.equal(result.ok, false); + assert.equal(result.outcome, "error"); + assert.equal(result.stop, "deadline"); + assert.match(result.sentence, /^The trending page stopped answering: the page did not answer within 20 s \(scrolling\)\. The browser was closed\. 3 posts read before it were kept \(3 new\)\./); +}); + +test("the record is written when the read starts, and a parse that fails still leaves one: the capture is parsed again offline", async () => { + const paths = corpus("ingest"); + // While the page is being opened, read.json is already there. + let early: unknown = null; + const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); + const failing = await run(paths, fixtureTrendingResponses(), { topic: "Kettles" }, { + openPage: (async () => { + early = await readXTrendingReadRecord(root(paths), READ_1); + return { page, close: async () => {} }; + }) as never, + ingest: (async () => { + throw new Error("EACCES: permission denied, open 'posts'\n at somewhere"); + }) as never, + }); + assert.equal((early as { stop?: string } | null)?.stop, "started"); + assert.equal((early as { outcome?: string } | null)?.outcome, "error"); + assert.equal(failing.result.ok, false); + assert.equal(failing.result.outcome, "error"); + assert.match( + failing.result.sentence, + /^The page was read and saved \(4 answers\), but its posts could not be written: EACCES: permission denied, open 'posts'\. The capture is kept/, + ); + const record = await readXTrendingReadRecord(root(paths), READ_1); + assert.equal(record?.outcome, "error"); + assert.equal(record?.stop, "idle"); + assert.equal((await readXTrendingPosts(root(paths))).length, 0); + // The offline reparse finds the record and writes the posts. + const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1, topic: "Kettles" }); + assert.ok(planned.ok && planned.plan.mode === "reparse", planned.ok ? "" : planned.error); + const reparsed = await reparseXTrendingRead({ plan: planned.plan as never }); + assert.deepEqual(reparsed.posts, { onPage: 4, added: 4 }); + assert.equal((await readXTrendingReadRecord(root(paths), READ_1))?.outcome, "read"); +}); + +test("a read left with its answers and no record is parsed again once the page is named", async () => { + const paths = corpus("recordless"); + await run(paths, fixtureTrendingResponses(), { probe: true }); + rmSync(path.join(root(paths), "trending", "reads", READ_1, "read.json")); + const bare = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); + assert.equal(bare.ok, false); + assert.match(bare.ok ? "" : bare.error, /has its answers but no record of which page it read: give "url"/); + const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1, url: FIXTURE_TREND_URL }); + assert.ok(planned.ok && planned.plan.mode === "reparse", planned.ok ? "" : planned.error); + const reparsed = await reparseXTrendingRead({ plan: planned.plan as never }); + assert.equal(reparsed.ok, true); + assert.deepEqual(reparsed.posts, { onPage: 4, added: 4 }); + assert.equal(reparsed.trendId, FIXTURE_TREND_ID); + assert.equal((await readXTrendingReadRecord(root(paths), READ_1))?.outcome, "read"); + // A read WITH its record takes no url beside reparse. + const both = await planReadXTrending(paths, { slug: "trending", reparse: READ_1, url: FIXTURE_TREND_URL }); + assert.match(both.ok ? "" : both.error, /one of them/); +}); + +test("a reparse updates the topic's record of the read: what the capture holds, and what was added in all", async () => { + const paths = corpus("recount"); + await run(paths, fixtureTrendingResponses(), { probe: true }); + const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); + assert.ok(planned.ok && planned.plan.mode === "reparse"); + await reparseXTrendingRead({ plan: planned.plan as never }); + await reparseXTrendingRead({ plan: planned.plan as never }); + const { readXTrendingTopics } = await import("../lib/xTrending/store"); + const [topic] = await readXTrendingTopics(root(paths)); + assert.deepEqual(topic.sources[0].reads, [{ id: READ_1, at: "2026-11-17T10:00:00.000Z", posts: 4, added: 4 }]); +}); + +test("the captures are never committed: the reads directory ignores everything under it", async () => { + const paths = corpus("gitignore"); + await run(paths, fixtureTrendingResponses()); + const ignore = readFileSync(path.join(root(paths), "trending", "reads", ".gitignore"), "utf8"); + assert.match(ignore, /^\*$/m); + // And it is not taken for a read. + assert.deepEqual((await listXTrending(root(paths))).reads, [READ_1]); +}); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -22,14 +22,27 @@ // `reparse-x-trending`: no request, so no jar is asked of it). // // EVERY FAILURE IS ONE SENTENCE AND NOTHING RETRIES: a login wall (which -// raises the X alert, stopping every X job), a 429 (pacing, never cookies: -// no alert), a page X no longer has, a page that did not load. What was read -// before the failure is kept. +// raises the X alert, stopping every X job), a 429 (pacing, never cookies: no +// alert — and X is left alone for X_RATE_LIMIT_HOLD_MS, 15 minutes, a +// cooldown the next read's enqueue and start both refuse on), a 403 (its own +// sentence, no alert), a page X no longer has, a page that did not load or +// stopped answering. What was read before the failure is kept. +// +// read.json IS ALWAYS THERE (review 1): it is written when the read starts +// (as a read that did not finish), and again when it ends, whatever the +// parse did — so a capture can always be parsed again offline. import path from "node:path"; import type { Paths } from "../lib/paths"; +import { stat } from "node:fs/promises"; import { noteXServiceOutcome } from "../lib/serviceCookies-server"; import { + heldPlatformRefusal, + platformCooldownRemainingMs, + recordPlatformClean, + recordPlatformCooldown, +} from "../jobs/downloadBackoff"; +import { isXTrendingChannel, NOT_A_TRENDING_URL, NOT_AN_X_TRENDING_LIBRARY, @@ -39,6 +52,7 @@ import { type XTrendingRef, } from "../lib/xTrending/config"; import { + ensureXTrendingReadsDir, isXTrendingReadId, readXTrendingReadRecord, recordXTrendingRead, @@ -64,7 +78,7 @@ import { type TrendingPageRead, type TrendingPageSession, } from "../social/xTrendingRead"; -import { readChannelConfig } from "./channels"; +import { isValidChannelSlug, readChannelConfig } from "./channels"; export { READ_X_TRENDING_KIND, @@ -74,6 +88,28 @@ export { } from "../lib/xTrending/config"; export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending "; +// How long X is left alone after it answered a read with 429: X's own +// rate-limit window. Written as the `twitter` platform cooldown +// (jobs/downloadBackoff.ts recordPlatformCooldown — the cooldown import-post +// already respects), read by this job's enqueue and start. +export const X_RATE_LIMIT_HOLD_MS = 15 * 60_000; +const X_PLATFORM = "twitter"; + +const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); + +// Why no trending read may start now — X is cooling down after a rate limit, +// or held — or null. +export async function xTrendingHeld(paths: Paths, now: number = Date.now()): Promise<string | null> { + const held = await heldPlatformRefusal(X_PLATFORM, "This trending read", paths, now).catch(() => null); + if (held) return held; + const ms = await platformCooldownRemainingMs(X_PLATFORM, paths).catch(() => 0); + if (ms <= 0) return null; + return ( + `X answered a rate limit (429) a short while ago: no trending read starts before ${hhmm(now + ms)} UTC ` + + `(${Math.ceil(ms / 60_000)} min from now). Ask again then; nothing retries by itself.` + ); +} + export const NO_X_PROFILE_FOR_TRENDING = "Reading a trending page needs the connected X profile (the browser that stays logged in): " + "connect an X account on /cookies, then read it again."; @@ -107,20 +143,51 @@ export type ReadXTrendingPlan = } | { mode: "reparse"; slug: string; channelRoot: string; record: XTrendingReadRecord; topic?: string }; +// A read left with its answers and no record (a crash before any record was +// written, a library from before review 1): the record a reparse starts from. +function recordlessRead(readId: string, ref: XTrendingRef, at: string): XTrendingReadRecord { + return { + version: 1, + id: readId, + trendId: ref.trendId, + url: ref.url, + startedAt: at, + endedAt: at, + probe: false, + headed: false, + limits: { scrolls: 0, posts: 0 }, + scrolls: 0, + stop: "unknown", + outcome: "error", + responses: 0, + saved: 0, + bytes: 0, + statuses: {}, + operations: [], + posts: { onPage: 0, added: 0 }, + shot: false, + sentence: "This read left its answers and no record.", + }; +} + // Everything checked before a job exists: the plan, or the refusal's sentence. export async function planReadXTrending( paths: Paths, ask: ReadXTrendingAsk, - deps: { hasProfile?: () => Promise<boolean> } = {}, + deps: { hasProfile?: () => Promise<boolean>; held?: () => Promise<string | null> } = {}, ): Promise<{ ok: true; plan: ReadXTrendingPlan } | { ok: false; error: string }> { const fail = (error: string) => ({ ok: false as const, error }); + // The slug becomes a path below: checked here, whoever the caller is. + if (!isValidChannelSlug(ask.slug)) { + return fail(`"${String(ask.slug)}" is not a valid channel slug (letters, digits, ".", "_", "-"; must start with a letter or digit)`); + } const config = await readChannelConfig(paths, ask.slug); if (!config) return fail(`No such channel: ${ask.slug}`); if (!isXTrendingChannel(config)) return fail(NOT_AN_X_TRENDING_LIBRARY(ask.slug)); const channelRoot = path.join(paths.channelsDir, ask.slug); const hasUrl = ask.url !== undefined && ask.url !== ""; const hasReparse = ask.reparse !== undefined && ask.reparse !== ""; - if (hasUrl === hasReparse) { + if (!hasUrl && !hasReparse) { return fail(`Give "url" (a trending page to read) or "reparse" (a saved read's id), one of them.`); } if (ask.topic !== undefined) { @@ -133,16 +200,39 @@ export async function planReadXTrending( return fail(`"probe", "headed", "scrolls" and "posts" apply to a read of a page, not to "reparse" (which asks X nothing).`); } if (!isXTrendingReadId(ask.reparse)) return fail(`"${String(ask.reparse)}" is not a trending read id (tr-…)`); - const record = await readXTrendingReadRecord(channelRoot, ask.reparse); - if (!record) return fail(`${ask.slug} holds no saved read ${ask.reparse} (pnpm ops get trending ${ask.slug} lists them).`); + let record = await readXTrendingReadRecord(channelRoot, ask.reparse); + if (record && hasUrl) { + return fail(`Give "url" (a trending page to read) or "reparse" (a saved read's id), one of them.`); + } + if (!record) { + // Its answers without its record: parsed all the same, once the caller + // says which page it was (the record is what knew). + const capture = path.join(trendingReadDir(channelRoot, ask.reparse), TRENDING_RESPONSES_FILENAME); + const saved = await stat(capture).catch(() => null); + if (!saved?.isFile()) { + return fail(`${ask.slug} holds no saved read ${ask.reparse} (pnpm ops get trending ${ask.slug} lists them).`); + } + const ref = hasUrl ? parseXTrendingUrl(ask.url) : null; + if (!ref) { + return fail( + `Saved read ${ask.reparse} has its answers but no record of which page it read: ` + + `give "url" (that trending page, https://x.com/i/trending/<number>) with "reparse".`, + ); + } + record = recordlessRead(ask.reparse, ref, saved.mtime.toISOString()); + } return { ok: true, plan: { mode: "reparse", slug: ask.slug, channelRoot, record, ...(topic ? { topic } : {}) } }; } + if (hasReparse) return fail(`Give "url" (a trending page to read) or "reparse" (a saved read's id), one of them.`); const ref = parseXTrendingUrl(ask.url); if (!ref) return fail(NOT_A_TRENDING_URL); const limits = xTrendingLimits(config.xTrending, { scrolls: ask.scrolls, posts: ask.posts }); if (!limits.ok) return fail(limits.error); const hasProfile = deps.hasProfile ?? (async () => (await readXSessionStatus(paths)).hasProfile); if (!(await hasProfile())) return fail(NO_X_PROFILE_FOR_TRENDING); + // X cooling down after a rate limit: refused before a job exists. + const held = await (deps.held ?? (() => xTrendingHeld(paths)))(); + if (held) return fail(held); return { ok: true, plan: { @@ -242,6 +332,13 @@ export type ReadXTrendingDeps = { // Why the profile cannot be opened now (a Connect or Refresh in flight), or null. profileBusy?: () => string | null; noteOutcome?: typeof noteXServiceOutcome; + // X's cooldown: why no read may start now; a rate limit recorded (answers + // when it ends, ms since the epoch); a clean read settling it. + held?: () => Promise<string | null>; + noteRateLimit?: () => Promise<number>; + noteClean?: () => Promise<void>; + // For tests: the capture → library step (default: ingestCapture). + ingest?: typeof ingestCapture; }; export async function runXTrendingRead(o: { @@ -270,8 +367,38 @@ export async function runXTrendingRead(o: { // A Connect or a Refresh holds the profile: asked again here, at the start. const busy = deps.profileBusy?.() ?? null; if (busy) return { ...base, ...none, ok: false, outcome: "error", sentence: busy, error: busy }; + // And X's cooldown, asked again here: a read queued before a rate limit + // does not navigate X when its turn comes. + const held = await (deps.held ?? (() => xTrendingHeld(paths, now())))(); + if (held) return { ...base, ...none, ok: false, outcome: "rate-limit", sentence: held, error: held }; const startedAt = new Date(now()).toISOString(); + // The record exists from the first moment: a read that dies anywhere below + // leaves a capture that can still be parsed again. + await ensureXTrendingReadsDir(plan.channelRoot); + const started: XTrendingReadRecord = { + version: 1, + id: readId, + trendId: plan.ref.trendId, + url: plan.ref.url, + startedAt, + endedAt: startedAt, + probe: plan.probe, + headed: plan.headed, + limits: plan.limits, + scrolls: 0, + stop: "started", + outcome: "error", + responses: 0, + saved: 0, + bytes: 0, + statuses: {}, + operations: [], + posts: { onPage: 0, added: 0 }, + shot: false, + sentence: `This read did not finish. Whatever it captured is kept (${captureAt(readId)}); read-x-trending {"reparse": "${readId}"} parses it without asking X.`, + }; + await writeXTrendingReadRecord(plan.channelRoot, started); log( `Reading ${plan.ref.url} for ${plan.slug} (${plan.headed ? "in a window" : "headless"}; ` + `at most ${plural(plan.limits.scrolls, "scroll")}, ${plural(plan.limits.posts, "post")})` + @@ -300,15 +427,23 @@ export async function runXTrendingRead(o: { // What was read is kept whatever stopped it — except behind a login wall, // where the page shown was not the trending page. const walled = page.stop === "login-wall"; - const ingested = await ingestCapture({ - channelRoot: plan.channelRoot, - slug: plan.slug, - readId, - at: startedAt, - ref: plan.ref, - ...(plan.topic ? { topic: plan.topic } : {}), - write: !plan.probe && !walled, - }); + // The parse may fail (a shape it chokes on, a disk that refuses): the read's + // record is written all the same, and the capture is there for a reparse. + let ingested: Ingested = { operations: [], responses: page.responses, onPage: 0, added: 0 }; + let ingestError: string | undefined; + try { + ingested = await (deps.ingest ?? ingestCapture)({ + channelRoot: plan.channelRoot, + slug: plan.slug, + readId, + at: startedAt, + ref: plan.ref, + ...(plan.topic ? { topic: plan.topic } : {}), + write: !plan.probe && !walled, + }); + } catch (err) { + ingestError = ((err as Error)?.message ?? String(err)).split("\n")[0]; + } const kept = captureAt(readId); const gone = ingested.onPage === 0 && (page.statuses["404"] ?? 0) > 0; const readSoFar = ingested.added > 0 || ingested.onPage > 0 @@ -328,12 +463,33 @@ export async function runXTrendingRead(o: { url: plan.ref.url, channel: plan.slug, }); + } else if (ingestError !== undefined) { + outcome = "error"; + sentence = + `The page was read and saved (${plural(page.responses, "answer")}), but its posts could not be written: ${ingestError}. ` + + `The capture is kept (${kept}); read-x-trending {"reparse": "${readId}"} parses it again without asking X.`; } else if (page.stop === "rate-limit") { outcome = "rate-limit"; + const until = await (deps.noteRateLimit ?? (() => recordPlatformCooldown(X_PLATFORM, X_RATE_LIMIT_HOLD_MS, paths, now())))().catch( + () => now() + X_RATE_LIMIT_HOLD_MS, + ); sentence = "X answered 429 (rate limit) to the page's own request: the read stopped at once and asked nothing more." + readSoFar + - ` Read it again later; nothing retries by itself. The capture is kept (${kept}).`; + ` No trending read starts before ${hhmm(until)} UTC (${Math.ceil((until - now()) / 60_000)} min); nothing retries by itself. The capture is kept (${kept}).`; + } else if (page.stop === "forbidden") { + outcome = "forbidden"; + sentence = + "X answered 403 (forbidden) to the page's own request: the read stopped at once and asked nothing more." + + readSoFar + + " The page did not show the login wall, so this is not taken for a lost login and no alert was raised; " + + `if it happens again, Check login on /cookies. The capture is kept (${kept}).`; + } else if (page.stop === "deadline") { + outcome = "error"; + sentence = + `The trending page stopped answering: ${page.error ?? "the read ran past its deadline"}. The browser was closed.` + + readSoFar + + ` The capture is kept (${kept}).`; } else if (page.stop === "error") { outcome = "error"; sentence = `The trending page could not be loaded: ${page.error ?? "unknown error"}.` + readSoFar + ` The capture is kept (${kept}).`; @@ -360,6 +516,8 @@ export async function runXTrendingRead(o: { // A clean request: a raised X alert it would clear is cleared. const cleared = await note(paths, { url: plan.ref.url, channel: plan.slug }); if (cleared) log(cleared); + // And X's cooldown, when an earlier rate limit left one behind. + await (deps.noteClean ?? (async () => void (await recordPlatformClean(X_PLATFORM, paths))))().catch(() => {}); } const ok = outcome === "read" || outcome === "probe" || outcome === "nothing-recognised"; const record: XTrendingReadRecord = { diff --git a/common/jobs/downloadBackoff.ts b/common/jobs/downloadBackoff.ts @@ -116,6 +116,28 @@ export async function recordDownloadBackoff( }); } +// A COOLDOWN OF A STATED LENGTH on a platform (lane x-trending, review 1): a +// reader that met the platform's rate limit itself and knows how long to stay +// away — an X trending read answered 429 — sets the same `platformBackoff` +// entry the exponential one above writes, so every reader of it +// (platformCooldownRemainingMs: import-post, the trending read's own enqueue +// and start checks) sees one cooldown. `until` only ever moves later; the +// failure count climbs by one. Returns when it ends (ms since the epoch). +export async function recordPlatformCooldown( + platform: string, + ms: number, + paths: Paths = getPaths(), + now: number = Date.now(), +): Promise<number> { + return mutateDownloadState(paths, (state) => { + prunePlatformPacing(state.download, now); + const prev = state.download.platformBackoff[platform]; + const next = mergeBackoffEntry(prev, { until: now + ms, fails: (prev?.fails ?? 0) + 1 }); + state.download.platformBackoff[platform] = next; + return next.until; + }); +} + // Record a SUBTITLE 429 against one video (release 17, slice RL): the count // climbs and the batch subtitle fetch leaves it alone for 6 h, or for 7 days // from the third. The platform's backoff, hold and pace are not touched. diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts @@ -112,7 +112,7 @@ test("the first read of a page makes a topic named for it; a re-read adds posts, // 102 was not on the page the second time: it stays. assert.deepEqual(members["102"].seen.map((s) => s.read), [READ_A]); // The same read recorded twice changes nothing. - await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["103", "101"], added: 1 }); + await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["103", "101"], added: 0 }); assert.equal((await readXTrendingTopics(dir))[0].sources[0].reads.length, 2); assert.equal((await readXTrendingMembership(dir))["101"].seen.length, 2); }); diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -38,9 +38,9 @@ // SERVER-ONLY (node:fs). import path from "node:path"; -import { readdir } from "node:fs/promises"; +import { mkdir, readFile, readdir } from "node:fs/promises"; import { POSTS_MEDIA_DIRNAME, SHOT_FILENAME } from "../../social/postCapture"; -import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-server"; +import { readJsonFile, withJsonFileLock, writeFileAtomic, writeJsonAtomic } from "../jsonFile-server"; import { readAllPosts, readSeenPostIds, writePosts, type WritePostsResult } from "../posts-server"; import type { Post } from "../posts"; import type { XTrendingRef } from "./config"; @@ -86,6 +86,21 @@ export function isXTrendingReadId(id: unknown): id is string { return typeof id === "string" && READ_ID.test(id); } +// THE CAPTURES ARE NEVER COMMITTED (review 1). The corpus is its own git +// repo, and a capture holds other people's data and fields bound to the +// reading session: `trending/reads/.gitignore` ignores everything under it +// (itself included), written whenever the reads directory is made. +export const TRENDING_READS_GITIGNORE = "# Raw captures of X pages: private, never committed.\n*\n"; + +export async function ensureXTrendingReadsDir(channelRoot: string): Promise<string> { + const dir = path.join(trendingDir(channelRoot), TRENDING_READS_DIRNAME); + await mkdir(dir, { recursive: true }); + const ignore = path.join(dir, ".gitignore"); + const have = await readFile(ignore, "utf8").catch(() => null); + if (have !== TRENDING_READS_GITIGNORE) await writeFileAtomic(ignore, TRENDING_READS_GITIGNORE); + return dir; +} + // One read's directory. The id is checked here, where it becomes a path. export function trendingReadDir(channelRoot: string, readId: string): string { if (!isXTrendingReadId(readId)) throw new Error(`"${readId}" is not a trending read id`); @@ -337,8 +352,14 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead source = { trendId: input.ref.trendId, url: input.ref.url, reads: [] }; found.sources.push(source); } - if (!source.reads.some((r) => r.id === input.readId)) { + const read = source.reads.find((r) => r.id === input.readId); + if (!read) { source.reads.push({ id: input.readId, at: input.at, posts: input.postIds.length, added: input.added }); + } else { + // The same read recorded again (a reparse): what the capture is now + // read to hold, and whatever this pass added on top of the last. + read.posts = input.postIds.length; + read.added += input.added; } await writeJsonAtomic(topicsPath(channelRoot), { version: 1, topics } satisfies TopicsFile, { mkdir: true }); return { id: found.id, title: found.title, created }; @@ -380,13 +401,16 @@ export type XTrendingReadOperation = { // read posts were written // probe the capture was saved and summarised; no post written // nothing-recognised the capture held no post the parser knows (kept) -// login-wall | rate-limit | gone | error the read failed, said in `sentence` +// login-wall | rate-limit | forbidden | gone | error +// the read failed, said in `sentence` ("error" is also +// what a read that never finished is left as) export type XTrendingReadOutcome = | "read" | "probe" | "nothing-recognised" | "login-wall" | "rate-limit" + | "forbidden" | "gone" | "error"; @@ -423,6 +447,7 @@ function readRecordPath(channelRoot: string, readId: string): string { } export async function writeXTrendingReadRecord(channelRoot: string, record: XTrendingReadRecord): Promise<void> { + await ensureXTrendingReadsDir(channelRoot); await writeJsonAtomic(readRecordPath(channelRoot, record.id), record, { mkdir: true }); } diff --git a/common/social/xTrendingParse.test.ts b/common/social/xTrendingParse.test.ts @@ -54,6 +54,11 @@ test("media is counted by kind from the answer", () => { assert.deepEqual(mediaSummaryOf(first), { count: 2, kinds: ["image"] }); assert.deepEqual(mediaSummaryOf(video), { count: 1, kinds: ["video"] }); assert.equal(mediaSummaryOf({ full_text: "no media" }), undefined); + // A type that is a property of every object is no kind. + assert.deepEqual( + mediaSummaryOf({ extended_entities: { media: [{ type: "constructor" }, { type: "toString" }, { type: "photo" }] } }), + { count: 3, kinds: ["image"] }, + ); }); test("a capture parses to posts, their media and the operations' names and sizes", () => { diff --git a/common/social/xTrendingParse.ts b/common/social/xTrendingParse.ts @@ -136,8 +136,9 @@ export function mediaSummaryOf(raw: XTweetRaw): TrendingMediaSummary | undefined if (!Array.isArray(media) || media.length === 0) return undefined; const kinds = new Set<TrendingMediaKind>(); for (const m of media) { - const kind = MEDIA_KIND[String(obj(m)?.type ?? "")]; - if (kind) kinds.add(kind); + // An own key only: a `type` of "constructor" or "toString" is no kind. + const type = String(obj(m)?.type ?? ""); + if (Object.hasOwn(MEDIA_KIND, type)) kinds.add(MEDIA_KIND[type]); } return { count: media.length, kinds: [...kinds].sort() }; } diff --git a/common/social/xTrendingRead.test.ts b/common/social/xTrendingRead.test.ts @@ -17,7 +17,7 @@ import { fixtureTimelineBody, fixtureTrendingResponses, } from "./__fixtures__/xTrendingCapture"; -import type { BrowserContextLike, ChromiumLike } from "./playwrightRuntime"; +import type { BrowserContextLike, ChromiumLike, PageLike } from "./playwrightRuntime"; import type { Paths } from "../lib/paths"; const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-read-")); @@ -153,6 +153,178 @@ test("an answer that is not JSON is counted and not kept", async () => { assert.equal(line.body, undefined); }); +// --- review 1: caps, a 403, a 401 mid-scroll, deadlines, the closed file ------ + +async function readWith( + page: PageLike, + over: Partial<Parameters<typeof readXTrendingPage>[0]> & { close?: () => Promise<void>; kill?: () => Promise<void> } = {}, +) { + const dir = path.join(TMP, `read-${++dirs}`); + const log: string[] = []; + const { close, kill, ...rest } = over; + const result = await readXTrendingPage({ + url: FIXTURE_TREND_URL, + dir, + openPage: async () => ({ page, close: close ?? (async () => {}), ...(kill ? { kill } : {}) }), + limits: { scrolls: 8, posts: 60 }, + pauseMs: () => 0, + pause: async () => {}, + signal: new AbortController().signal, + onLog: (l) => log.push(l), + ...rest, + }); + return { result, dir, log }; +} + +test("the byte caps: an answer too large, and answers past the read's cap, are counted and not kept", async () => { + const big = fixtureTimelineBody(Array.from({ length: 6 }, (_, i) => tweet(i))); + const small = fixtureTimelineBody([tweet(7)]); + const smallBytes = Buffer.byteLength(JSON.stringify(small)); + const page = fakeTrendingPage(() => ({ + trending: { + load: [ + { url: timelineUrl(0), status: 200, body: big }, + { url: timelineUrl(1), status: 200, body: small }, + { url: timelineUrl(2), status: 200, body: small }, + ], + scrolls: [[], []], + }, + })); + const { result, dir } = await readWith(page, { maxResponseBytes: smallBytes + 10, maxReadBytes: smallBytes + 10 }); + assert.equal(result.responses, 3); + assert.equal(result.saved, 1); + assert.equal(result.bytes, smallBytes); + assert.equal(result.tweets, 1); + const lines = await readCaptureLines(path.join(dir, "responses.jsonl")); + assert.deepEqual(lines.map((l) => [l.n, l.skipped ?? "kept", l.body === undefined]), [ + [1, "too-large", true], + [2, "kept", false], + [3, "over-cap", true], + ]); + assert.ok(lines[0].bytes > smallBytes + 10); +}); + +test("a 403 stops the read at once: no scroll follows, and it is not a login wall", async () => { + const first = await read({ + load: [ + { url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }, + { url: timelineUrl(1), status: 403, body: { errors: [{ code: 200 }] } }, + ], + scrolls: [[{ url: timelineUrl(2), status: 200, body: fixtureTimelineBody([tweet(2)]) }]], + }); + assert.equal(first.result.stop, "forbidden"); + assert.equal(first.result.scrolls, 0); + assert.equal(first.result.tweets, 1); + // On X's login page a 403 is the login wall's. + const walled = await read({ href: "https://x.com/i/flow/login", load: [{ url: timelineUrl(0), status: 403, text: "" }] }); + assert.equal(walled.result.stop, "login-wall"); + // And a rate limit beside a 403 is the rate limit. + const both = await read({ load: [{ url: timelineUrl(0), status: 403, text: "" }, { url: timelineUrl(1), status: 429, text: "" }] }); + assert.equal(both.result.stop, "rate-limit"); +}); + +test("a 401 on a scroll ends the read there, as a login wall", async () => { + const { result } = await read({ + load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], + scrolls: [ + [{ url: timelineUrl(1), status: 200, body: fixtureTimelineBody([tweet(1)]) }], + [{ url: timelineUrl(2), status: 401, body: { errors: [{ code: 32 }] } }], + [{ url: timelineUrl(3), status: 200, body: fixtureTimelineBody([tweet(3)]) }], + ], + }); + assert.equal(result.stop, "login-wall"); + assert.equal(result.scrolls, 2); + assert.equal(result.tweets, 2); +}); + +const never = <T>() => new Promise<T>(() => {}); + +test("a page that stops answering ends the read with a sentence; the browser is closed, and killed when closing hangs too", async () => { + // The scroll never answers. + const base = fakeTrendingPage(() => ({ trending: { load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], scrolls: [[]] } })); + let closed = 0; + const hungScroll = { ...base, evaluate: (fn: string) => (fn.includes("scrollTo") ? never<unknown>() : base.evaluate(fn)) } as PageLike; + const scroll = await readWith(hungScroll, { timeouts: { call: 40 }, close: async () => void closed++ }); + assert.equal(scroll.result.stop, "deadline"); + assert.equal(scroll.result.error, "the page did not answer within 0 s (scrolling)"); + assert.equal(scroll.result.tweets, 1); + assert.equal(closed, 1); + assert.equal((await readCaptureLines(path.join(scroll.dir, "responses.jsonl"))).length, 1); + + // The load never answers. + const hungLoad = { ...base, goto: () => never<unknown>() } as PageLike; + const load = await readWith(hungLoad, { timeouts: { load: 40 } }); + assert.equal(load.result.stop, "deadline"); + assert.match(load.result.error ?? "", /did not answer within 0 s \(loading the page\)/); + + // Closing never answers: the browser is killed, and the read still returns. + let killed = 0; + const stuck = await readWith(fakeTrendingPage(() => ({ trending: { load: [], scrolls: [[], []] } })), { + timeouts: { close: 40 }, + close: () => never<void>(), + kill: async () => void killed++, + }); + assert.equal(stuck.result.stop, "idle"); + assert.equal(killed, 1); + assert.ok(stuck.log.some((l) => /The browser did not close .*; killing it\./.test(l))); +}); + +test("the whole read has a deadline: past it the read stops where it is, what was captured kept", async () => { + const pages = { + load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], + scrolls: Array.from({ length: 20 }, (_, i) => [{ url: timelineUrl(i + 1), status: 200, body: fixtureTimelineBody([tweet(i + 1)]) }]), + }; + const { result, dir } = await readWith(fakeTrendingPage(() => ({ trending: pages })), { + limits: { scrolls: 20, posts: 200 }, + // Each wait is 30 ms of real time; the read may take 100. + pauseMs: () => 30, + pause: undefined, + timeouts: { read: 100 }, + }); + assert.equal(result.stop, "deadline"); + assert.ok(result.scrolls >= 1 && result.scrolls < 20, String(result.scrolls)); + assert.equal((await readCaptureLines(path.join(dir, "responses.jsonl"))).length, result.responses); +}); + +test("once the read has returned, a late answer is not appended to the capture", async () => { + const handlers: Array<(res: unknown) => void> = []; + const base = fakeTrendingPage(() => ({ trending: { load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], scrolls: [[], []] } })); + const page = { + ...base, + on: (event: string, cb: (arg: never) => void) => { + if (event === "response") handlers.push(cb as (res: unknown) => void); + base.on(event, cb); + }, + } as PageLike; + const { result, dir } = await readWith(page); + const before = readFileSync(path.join(dir, "responses.jsonl"), "utf8"); + for (const h of handlers) { + h({ url: () => timelineUrl(9), status: () => 200, text: async () => JSON.stringify(fixtureTimelineBody([tweet(9)])) }); + } + await new Promise((r) => setTimeout(r, 30)); + assert.equal(readFileSync(path.join(dir, "responses.jsonl"), "utf8"), before); + assert.equal(result.responses, 1); +}); + +test("an answer whose body cannot be read costs that answer, not the read", async () => { + const handlers: Array<(res: unknown) => void> = []; + const page = { + ...fakeTrendingPage(() => ({ trending: { load: [], scrolls: [[], []] } })), + on: (event: string, cb: (arg: never) => void) => void (event === "response" && handlers.push(cb as (res: unknown) => void)), + goto: async () => { + for (const h of handlers) { + h({ url: () => timelineUrl(0), status: () => 200, text: () => Promise.reject(new Error("the body is gone")) }); + h({ url: () => { throw new Error("no url"); }, status: () => 200, text: async () => "{}" }); + } + return null; + }, + } as PageLike; + const { result, dir } = await readWith(page); + assert.equal(result.stop, "idle"); + assert.equal(result.responses, 1); + assert.equal((await readCaptureLines(path.join(dir, "responses.jsonl")))[0].skipped, "unread"); +}); + // --- which browser opens --------------------------------------------------- function stubChromium(extra: Partial<ChromiumLike> = {}) { @@ -211,3 +383,31 @@ test("a read opens the connected profile headless; \"headed\" opens it in a wind ); assert.equal(none.launches.length, 0); }); + +test("a context whose first page cannot be made is closed, not left holding the profile", async () => { + for (const headed of [false, true]) { + let closed = 0; + const context: BrowserContextLike = { + newPage: async () => { + throw new Error("Target page, context or browser has been closed"); + }, + pages: () => [], + cookies: async () => [], + addCookies: async () => {}, + close: async () => void closed++, + on: () => {}, + }; + const chromium: ChromiumLike = { + opensNoWindow: true, + launch: async () => { + throw new Error("not used"); + }, + launchPersistentContext: async () => context, + }; + await assert.rejects( + openXTrendingPage(paths(`newpage-${headed}`), { headed, chromium, env: { PATH: "" } }), + /Target page, context or browser has been closed/, + ); + assert.equal(closed, 1, headed ? "headed" : "headless"); + } +}); diff --git a/common/social/xTrendingRead.ts b/common/social/xTrendingRead.ts @@ -16,7 +16,17 @@ // of what has loaded (that is what makes the page ask for more), then waits // the X request gap (4–10 s, xGalleryDlFetcher.ts xRequestPauseMs). It stops // at the scroll cap, at the post cap, after two scrolls in a row that brought -// no new post, and AT ONCE on a 429, a 401 or a login page. It never retries. +// no new post, and AT ONCE on a 429, a 403, a 401 or a login page. It never +// retries. +// +// NOTHING HERE WAITS FOREVER (review 1). Every call into the page is raced +// against a deadline — the load 75 s, a scroll, a look at the address or a +// screenshot 20 s each, closing the browser 10 s — and against the job's +// cancel; and the whole read against READ_DEADLINE_MS (6 minutes: twenty +// scrolls at the longest gap, twice over). A page that stops answering ends +// the read with a sentence, what was captured kept, and the browser is closed +// (killed, when closing does not answer) so the profile is free again. Once +// the read returns, nothing more is appended to responses.jsonl. // // The caller (controller/readXTrending.ts) is one editor job on X's queue; // this module knows nothing of queues, alerts or the store. @@ -46,13 +56,22 @@ import { export const TRENDING_RESPONSE_MAX_BYTES = 8 * 1024 * 1024; export const TRENDING_READ_MAX_BYTES = 64 * 1024 * 1024; +// The deadlines (ms): the page's load, any other call into the page, closing +// the browser, and one whole read. +export const PAGE_LOAD_TIMEOUT_MS = 75_000; +export const PAGE_CALL_TIMEOUT_MS = 20_000; +export const PAGE_CLOSE_TIMEOUT_MS = 10_000; +export const READ_DEADLINE_MS = 6 * 60_000; + // Why a read stopped scrolling. // idle two scrolls in a row brought no new post: the page's end // scroll-cap the read's scroll cap // post-cap the read's post cap // cancelled the job was cancelled or drained // rate-limit the page's own request was answered 429 +// forbidden the page's own request was answered 403 // login-wall X showed its login page, or answered 401 +// deadline the page stopped answering, or the read ran past its deadline // error the page did not load export type TrendingReadStop = | "idle" @@ -60,7 +79,9 @@ export type TrendingReadStop = | "post-cap" | "cancelled" | "rate-limit" + | "forbidden" | "login-wall" + | "deadline" | "error"; export type TrendingPageRead = { @@ -79,7 +100,38 @@ export type TrendingPageRead = { error?: string; }; -export type TrendingPageSession = { page: PageLike; close: () => Promise<void> }; +// `kill` ends the browser when `close` does not answer (optional: a fake has none). +export type TrendingPageSession = { page: PageLike; close: () => Promise<void>; kill?: () => Promise<void> }; + +export class PageDeadlineError extends Error { + constructor(what: string, ms: number) { + super(`the page did not answer within ${Math.round(ms / 1000)} s (${what})`); + this.name = "PageDeadlineError"; + } +} + +// `p`, or a PageDeadlineError after `ms`, or an abort — whichever is first. +// The loser is left to settle by itself (its rejection swallowed). +export function bounded<T>(what: string, p: Promise<T>, ms: number, signal?: AbortSignal): Promise<T> { + return new Promise<T>((resolve, reject) => { + let done = false; + const finish = (fn: () => void) => { + if (done) return; + done = true; + clearTimeout(timer); + signal?.removeEventListener("abort", onAbort); + fn(); + }; + const onAbort = () => finish(() => reject(new Error("cancelled"))); + const timer = setTimeout(() => finish(() => reject(new PageDeadlineError(what, ms))), ms); + if (signal?.aborted) return onAbort(); + signal?.addEventListener("abort", onAbort); + p.then( + (v) => finish(() => resolve(v)), + (e) => finish(() => reject(e)), + ); + }); +} type ResponseLike = { url: () => string; status: () => number; text: () => Promise<string> }; @@ -125,10 +177,33 @@ export async function readXTrendingPage(o: { signal: AbortSignal; onLog?: (line: string) => void; now?: () => number; + // The byte caps and the deadlines, for tests (defaults: the constants above). + maxResponseBytes?: number; + maxReadBytes?: number; + timeouts?: { load?: number; call?: number; close?: number; read?: number }; }): Promise<TrendingPageRead> { const log = o.onLog ?? (() => {}); const pause = o.pause ?? abortablePause; const now = o.now ?? Date.now; + const maxResponse = o.maxResponseBytes ?? TRENDING_RESPONSE_MAX_BYTES; + const maxRead = o.maxReadBytes ?? TRENDING_READ_MAX_BYTES; + const t = { + load: o.timeouts?.load ?? PAGE_LOAD_TIMEOUT_MS, + call: o.timeouts?.call ?? PAGE_CALL_TIMEOUT_MS, + close: o.timeouts?.close ?? PAGE_CLOSE_TIMEOUT_MS, + read: o.timeouts?.read ?? READ_DEADLINE_MS, + }; + // The read's own clock: fired at its deadline, and by the job's cancel. + const clock = new AbortController(); + let pastDeadline = false; + const deadline = setTimeout(() => { + pastDeadline = true; + clock.abort(); + }, t.read); + const onCancel = () => clock.abort(); + if (o.signal.aborted) clock.abort(); + else o.signal.addEventListener("abort", onCancel); + const signal = clock.signal; await mkdir(o.dir, { recursive: true }); const file = path.join(o.dir, TRENDING_RESPONSES_FILENAME); await writeFile(file, ""); @@ -146,15 +221,21 @@ export async function readXTrendingPage(o: { const seen = new Set<string>(); let rateLimited = false; let unauthorized = false; + let forbidden = false; let n = 0; let writes: Promise<void> = Promise.resolve(); + // Closed when the read returns: an answer that arrives later is not written. + let closed = false; const pending = new Set<Promise<void>>(); const keep = (line: TrendingCaptureLine) => { + if (closed) return; + // What was queued before the close is still written; nothing is queued after it. writes = writes.then(() => appendFile(file, JSON.stringify(line) + "\n")).catch(() => {}); }; const onResponse = (res: ResponseLike) => { + if (closed) return; let url: string; let status: number; try { @@ -169,6 +250,7 @@ export async function readXTrendingPage(o: { out.statuses[String(status)] = (out.statuses[String(status)] ?? 0) + 1; if (status === 429) rateLimited = true; if (status === 401) unauthorized = true; + if (status === 403) forbidden = true; const base = { n: ++n, at: new Date(now()).toISOString(), op, status, url }; const task = (async () => { let text: string; @@ -179,8 +261,8 @@ export async function readXTrendingPage(o: { return; } const bytes = Buffer.byteLength(text); - if (bytes > TRENDING_RESPONSE_MAX_BYTES) return keep({ ...base, bytes, skipped: "too-large" }); - if (out.bytes + bytes > TRENDING_READ_MAX_BYTES) return keep({ ...base, bytes, skipped: "over-cap" }); + if (bytes > maxResponse) return keep({ ...base, bytes, skipped: "too-large" }); + if (out.bytes + bytes > maxRead) return keep({ ...base, bytes, skipped: "over-cap" }); let body: unknown; try { body = JSON.parse(text); @@ -196,9 +278,11 @@ export async function readXTrendingPage(o: { if (id) seen.add(id); } } - })(); + })().catch(() => { + /* a throw while reading one answer costs that answer, never the read */ + }); pending.add(task); - void task.finally(() => pending.delete(task)); + void task.finally(() => pending.delete(task)).catch(() => {}); }; // The answers in flight, read to their end (at most 15 s). @@ -206,24 +290,31 @@ export async function readXTrendingPage(o: { const all = Promise.allSettled([...pending]); await Promise.race([all, new Promise((r) => setTimeout(r, 15_000))]); }; - const blocked = (): TrendingReadStop | null => (unauthorized ? "login-wall" : rateLimited ? "rate-limit" : null); + // A login wall first (it is what the other statuses would mean too), then + // the rate limit, then a plain refusal. + const blocked = (): TrendingReadStop | null => + unauthorized ? "login-wall" : rateLimited ? "rate-limit" : forbidden ? "forbidden" : null; let session: TrendingPageSession | undefined; try { - session = await o.openPage(); + session = await bounded("opening the browser", o.openPage(), t.load, signal); const { page } = session; page.on("response", onResponse as (arg: never) => void); - await page.goto(o.url, { waitUntil: "domcontentloaded", timeout: 60_000 }); + await bounded("loading the page", page.goto(o.url, { waitUntil: "domcontentloaded", timeout: 60_000 }), t.load, signal); // The page settles: its first requests go out and come back. - await pause(o.pauseMs(), o.signal); + await pause(o.pauseMs(), signal); await settle(); - const href = await page.evaluate("location.href").catch(() => null); + const href = await bounded("reading its address", page.evaluate("location.href"), t.call, signal).catch((err) => { + if (err instanceof PageDeadlineError) throw err; + return null; + }); if (isXLoginHref(href)) unauthorized = true; try { - const png = await page.screenshot({ type: "png" }); + const png = await bounded("the screenshot", page.screenshot({ type: "png" }), t.call, signal); await writeFile(path.join(o.dir, TRENDING_PAGE_SHOT_FILENAME), png); out.shot = true; } catch (err) { + if (err instanceof PageDeadlineError) throw err; log(`No screenshot of the page: ${firstLine(err)}`); } log(`The page loaded: ${out.responses} answer(s), ${seen.size} post(s) so far.`); @@ -231,14 +322,14 @@ export async function readXTrendingPage(o: { let idle = 0; let stop: TrendingReadStop | null = blocked(); while (!stop) { - if (o.signal.aborted) stop = "cancelled"; + if (signal.aborted) stop = pastDeadline ? "deadline" : "cancelled"; else if (seen.size >= o.limits.posts) stop = "post-cap"; else if (out.scrolls >= o.limits.scrolls) stop = "scroll-cap"; if (stop) break; const before = seen.size; - await page.evaluate(SCROLL_TO_BOTTOM); + await bounded("scrolling", page.evaluate(SCROLL_TO_BOTTOM), t.call, signal); out.scrolls++; - await pause(o.pauseMs(), o.signal); + await pause(o.pauseMs(), signal); await settle(); stop = blocked(); if (stop) break; @@ -251,13 +342,29 @@ export async function readXTrendingPage(o: { } out.stop = stop ?? "idle"; } catch (err) { - out.stop = blocked() ?? (o.signal.aborted ? "cancelled" : "error"); - out.error = firstLine(err); + const hung = err instanceof PageDeadlineError || pastDeadline; + out.stop = blocked() ?? (hung ? "deadline" : o.signal.aborted ? "cancelled" : "error"); + out.error = pastDeadline && !(err instanceof PageDeadlineError) + ? `the read ran past its ${Math.round(t.read / 1000)} s deadline` + : firstLine(err); } finally { - await settle(); + clearTimeout(deadline); + o.signal.removeEventListener("abort", onCancel); + // The answers already in flight, briefly; then the file is closed. + await Promise.race([Promise.allSettled([...pending]), new Promise((r) => setTimeout(r, Math.min(t.call, 15_000)))]); + closed = true; await writes; - await session?.close().catch(() => {}); + // The browser is closed whatever happened; one that does not answer is + // killed, so the profile is never left held by a dead page. + if (session) { + const s = session; + await bounded("closing the browser", s.close(), t.close).catch(async (err) => { + log(`The browser did not close (${firstLine(err)})${s.kill ? "; killing it." : "."}`); + if (s.kill) await bounded("killing the browser", s.kill(), t.close).catch(() => {}); + }); + } } + if (out.stop === "idle" && pastDeadline) out.stop = "deadline"; out.tweets = seen.size; return out; } @@ -291,6 +398,21 @@ export async function openXTrendingPage( } else { context = await launchXProfile(paths, { onLog: log, ...(o.chromium ? { chromium: o.chromium } : {}) }); } - const page = context.pages()[0] ?? (await context.newPage()); - return { page, close: () => context.close() }; + // A context that opened holds the profile: it is closed on every way out, + // a failed newPage included (review 1). + let page: PageLike; + try { + page = context.pages()[0] ?? (await context.newPage()); + } catch (err) { + await context.close().catch(() => {}); + throw err; + } + // The browser behind a persistent context, when the runtime names it: what + // `kill` closes if the context itself stops answering. + const browser = (context as { browser?: () => { close?: () => Promise<void> } | null }).browser?.() ?? null; + return { + page, + close: () => context.close(), + ...(browser?.close ? { kill: () => browser.close!() } : {}), + }; }