// ONE READ OF ONE X TRENDING PAGE (lane x-trending, slice 1), through the // connected X profile's browser — the profile capture-posts shoots with // (xSessionBroker.ts launchXProfile), headless unless the read asks for a // window (headedDisplay.ts launchHeadedContext). // // gallery-dl has no extractor for x.com/i/trending/ (1.32.9: no pattern, // no endpoint), so the page is opened as a person would open it and what the // PAGE ITSELF fetches is kept: every GraphQL JSON answer // (x.com/i/api/graphql//) is written raw, one per line, to // `responses.jsonl`, with a screenshot of the loaded page beside it. Nothing // here asks X for anything the page did not ask: no request is built, no // query id is known, no header is read or stored — ONLY response bodies. // // WHAT ONE READ COSTS: one navigation, the page's own first requests, and at // most one more page of its timeline per scroll. A scroll moves to the bottom // 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 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 its deadline (readDeadlineMs: two // minutes, and twelve seconds — the longest gap and a page call — for every // scroll each tab may make). 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. // // TWO TABS, ONE READ (lane x-followups, R3). A trending page has tabs — "Top", // which it opens on, and "Latest" — each its own timeline. After the opening // tab is read to its stop, the read PRESSES THE PAGE'S OWN TAB: the element // with the tab's role and the label the page's own answer gave for it, found // as a person finds it. It builds no request: it waits for the page's request // for that tab's timeline (the timeline id the page's answer named) and then // scrolls under the same caps. Each tab has the full scroll and post caps. // A tab that is not found, or whose press brings no timeline answer within // the wait, is "not read" with its reason: not a failure, and never retried. // A 429, a 403, a 401 or a login page on either tab stops the whole read. // // The caller (controller/readXTrending.ts) is one editor job on X's queue; // this module knows nothing of queues, alerts or the store. // A browser that will not close is killed (`session.kill`, by a checked pid: // profileBrowserPid.ts): the guard every module that kills a process installs // (lib/childKillGuard.test.ts). import "../lib/childKillGuard"; import { appendFile, mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { X_TRENDING_IDLE_SCROLLS, type XTrendingLimits } from "../lib/xTrending/config"; import { TRENDING_PAGE_SHOT_FILENAME, TRENDING_RESPONSES_FILENAME, TRENDING_TAB_SHOT_FILENAME, } from "../lib/xTrending/store"; import { importPlaywright, type ChromiumLike, type PageLike } from "./playwrightRuntime"; import { launchHeadedContext, type HeadedDisplayLaunchDeps } from "./headedDisplay"; import { findXBrowser } from "./xBrowser"; import { killProfileBrowser, type ProfileBrowserPidDeps } from "./profileBrowserPid"; import { launchXProfile, xProfileDir } from "./xSessionBroker"; import { xIdOf } from "./xNormalize"; import { collectTimelineTweets, graphqlOpOf, requestVariablesOf, trendPageOf, X_TRENDING_IGNORED_OPS, type TrendingCaptureLine, type TrendingPageInfo, } from "./xTrendingParse"; // One answer is kept up to this size, a read's answers up to this in all: // past either, the answer is counted (its operation and size) and not kept. 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; // How long the read waits, after pressing a tab, for the page's request for // that tab's timeline. export const TAB_WAIT_MS = 20_000; // One whole read: two minutes for the load, the screenshots and the tab // press, and twelve seconds (the longest gap, 10 s, and a page call) for // every scroll each tab may make. One tab at 20 scrolls: 6 minutes (what a // read always had). Both tabs at the default 20 scrolls: 10 minutes. Both at // the maximum 40: 18 minutes. export const READ_DEADLINE_BASE_MS = 2 * 60_000; export const READ_DEADLINE_PER_SCROLL_MS = 12_000; export function readDeadlineMs(limits: Pick, tabs: number): number { return READ_DEADLINE_BASE_MS + Math.max(1, tabs) * limits.scrolls * READ_DEADLINE_PER_SCROLL_MS; } export const READ_DEADLINE_MS = readDeadlineMs({ scrolls: 20 }, 1); // The tabs a read may be asked for, and in the order it reads them: the tab // the page opens on, then the other. export type TrendingTabAsk = "top" | "latest"; export const TRENDING_TAB_ASKS: readonly TrendingTabAsk[] = ["top", "latest"]; // WHY A TAB WAS NOT READ when the press took the page off the trending page // (review 2 S1). Said in read.json; the controller reads it to ingest only the // page's own timelines from such a read (review 3 S8). export const TRENDING_PAGE_CHANGED = "the page changed"; export const TRENDING_TAB_LABEL: Readonly> = { top: "Top", latest: "Latest" }; // One tab of a read: what was asked, the page's own label and timeline for it // (when the page's answer named one), how it went. // stop why its scrolling stopped (TrendingReadStop), or // "not-read": the tab was asked for and could not be opened — // `why` says so — or "not-asked": the page loaded it (the tab it // opens on) and the read was asked for the other only. export type TrendingTabRead = { asked: TrendingTabAsk; tab?: string; timelineId?: string; scrolls: number; posts: number; stop: TrendingReadStop | "not-read" | "not-asked"; why?: string; }; // 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" | "scroll-cap" | "post-cap" | "cancelled" | "rate-limit" | "forbidden" | "login-wall" | "deadline" | "error"; export type TrendingPageRead = { stop: TrendingReadStop; scrolls: number; // GraphQL answers seen, and how many of them were kept whole. responses: number; saved: number; bytes: number; // Answers by HTTP status ("200": 4, "404": 1). statuses: Record; // Distinct posts the walk found while reading (the stop conditions' count). tweets: number; // page.png was written. shot: boolean; error?: string; // The FIRST answer that stopped the read — a 429, a 403 or a 401 — by its // operation and status, so a read's record says which request it was. stoppedBy?: { op: string; status: number }; // Tab by tab, in the order they were read. `stop` and `scrolls` above are // the whole read's: the stop of the last tab that was scrolled (or the // answer that stopped everything), and every scroll. tabs: TrendingTabRead[]; // page-latest.png was written (the page after the second tab was pressed, // or after the press was tried). tabShot?: boolean; }; // `kill` ends the browser when `close` does not answer: the process itself, // by its checked pid (openXTrendingPage). Optional: a test's page has none. export type TrendingPageSession = { page: PageLike; close: () => Promise; kill?: () => Promise }; 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(what: string, p: Promise, ms: number, signal?: AbortSignal): Promise { return new Promise((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); // The handlers go on `p` FIRST (review 2 N3): were the aborted check to // return before them, a call still in flight would reject with nobody // listening when the context closes under it. p.then( (v) => finish(() => resolve(v)), (e) => finish(() => reject(e)), ); if (signal?.aborted) return onAbort(); signal?.addEventListener("abort", onAbort); }); } type ResponseLike = { url: () => string; status: () => number; text: () => Promise }; const LOGIN_HREF = /\/i\/flow\/login|\/login(?:[/?#]|$)|\/account\/access/; export function isXLoginHref(href: unknown): boolean { if (typeof href !== "string") return false; try { return LOGIN_HREF.test(new URL(href).pathname); } catch { return false; } } function firstLine(err: unknown): string { return ((err as Error)?.message ?? String(err)).split("\n")[0]; } // An abortable wait: resolves early when the signal fires. export function abortablePause(ms: number, signal: AbortSignal): Promise { return new Promise((resolve) => { if (signal.aborted || ms <= 0) return resolve(); const done = () => { clearTimeout(timer); signal.removeEventListener("abort", done); resolve(); }; const timer = setTimeout(done, ms); signal.addEventListener("abort", done); }); } const SCROLL_TO_BOTTOM = "window.scrollTo(0, document.documentElement.scrollHeight)"; // Whether the page is still the trending page the read opened (review 2 S1): // the same host and path. Its query may change (a tab may say itself there). export function sameTrendingPage(href: unknown, opened: string): boolean { if (typeof href !== "string") return false; try { const a = new URL(href); const b = new URL(opened); return a.hostname.replace(/^www\./, "") === b.hostname.replace(/^www\./, "") && a.pathname.replace(/\/+$/, "") === b.pathname.replace(/\/+$/, ""); } catch { return false; } } // A page's path, for a log line: never its query (it may carry a search). function safePath(href: string): string { try { return new URL(href).pathname; } catch { return "an address that cannot be read"; } } export async function readXTrendingPage(o: { url: string; // The read's directory (`trending/reads/`), made here. dir: string; openPage: () => Promise; limits: XTrendingLimits; // The tabs to read (default: both), read in the page's order. tabs?: ReadonlyArray; pauseMs: () => number; pause?: (ms: number, signal: AbortSignal) => Promise; 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; tab?: number }; }): Promise { 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 ?? readDeadlineMs(o.limits, (o.tabs ?? TRENDING_TAB_ASKS).length), tab: o.timeouts?.tab ?? TAB_WAIT_MS, }; const wanted = TRENDING_TAB_ASKS.filter((t) => (o.tabs ?? TRENDING_TAB_ASKS).includes(t)); // 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, ""); const out: TrendingPageRead = { stop: "idle", scrolls: 0, responses: 0, saved: 0, bytes: 0, statuses: {}, tweets: 0, shot: false, tabs: [], }; const seen = new Set(); // Per timeline the page asked for ("" for a request that named none): the // posts it listed, and how many answers it has had. const seenBy = new Map>(); const answersBy = new Map(); // What the page said of itself: its tabs' labels and timelines. let pageInfo: TrendingPageInfo | undefined; // The first timeline the page asked for: the tab it opens on, whether or // not the page's own answer (which names the tabs) was among what it fetched. let firstTimeline: string | undefined; let rateLimited = false; // The read's deadline fell inside the second tab (review 2 S2). let latestCut = false; let unauthorized = false; let forbidden = false; let n = 0; let writes: Promise = Promise.resolve(); // Closed when the read returns: an answer that arrives later is not written. let closed = false; const pending = new Set>(); 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 { url = res.url(); status = res.status(); } catch { return; } const op = graphqlOpOf(url); if (!op) return; out.responses++; 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; if ((status === 429 || status === 401 || status === 403) && !out.stoppedBy) out.stoppedBy = { op, status }; const base = { n: ++n, at: new Date(now()).toISOString(), op, status, url }; const task = (async () => { let text: string; try { text = await res.text(); } catch { keep({ ...base, bytes: 0, skipped: "unread" }); return; } const bytes = Buffer.byteLength(text); 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); } catch { return keep({ ...base, bytes, skipped: "not-json" }); } out.bytes += bytes; out.saved++; keep({ ...base, bytes, body }); if (status >= 200 && status < 300 && !X_TRENDING_IGNORED_OPS.includes(op)) { pageInfo ??= trendPageOf(body); const timeline = requestVariablesOf(url).timelineId ?? ""; const found = collectTimelineTweets(body); if (timeline || found.length) answersBy.set(timeline, (answersBy.get(timeline) ?? 0) + 1); if (timeline && found.length) firstTimeline ??= timeline; const own = seenBy.get(timeline) ?? new Set(); seenBy.set(timeline, own); for (const raw of found) { const id = xIdOf(raw); if (!id) continue; seen.add(id); own.add(id); } } })().catch(() => { /* a throw while reading one answer costs that answer, never the read */ }); pending.add(task); void task.finally(() => pending.delete(task)).catch(() => {}); }; // The answers in flight, read to their end (at most 15 s). const settle = async () => { const all = Promise.allSettled([...pending]); await Promise.race([all, new Promise((r) => setTimeout(r, 15_000))]); }; // 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; // The launch itself, kept (review 2 N1): when the deadline or a cancel wins // the race below, the browser may still open afterwards, holding the // profile — it is closed the moment it does. let opening: Promise | undefined; try { // A read cancelled before it began asks for no browser at all. if (signal.aborted) throw new Error("cancelled"); opening = o.openPage(); session = await bounded("opening the browser", opening, t.load, signal); const { page } = session; page.on("response", onResponse as (arg: never) => void); 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(), signal); await settle(); 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 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.`); // THE PAGE'S TABS, as its own answer named them. The tab it opens on is // "Top"; with no such answer the opening tab is whatever the page lists. const tabOf = (ask: TrendingTabAsk) => pageInfo?.tabs.find((t) => t.label.trim().toLowerCase() === TRENDING_TAB_LABEL[ask].toLowerCase()); // The posts one tab has listed so far: its own timeline's, else (a page // that named no tabs) every post seen. const countOf = (timelineId: string | undefined) => (timelineId ? (seenBy.get(timelineId)?.size ?? 0) : seen.size); // One tab scrolled to its stop, under the read's caps. const scrollTab = async (timelineId: string | undefined): Promise<{ stop: TrendingReadStop; scrolls: number }> => { let idle = 0; let scrolls = 0; let stop: TrendingReadStop | null = blocked(); while (!stop) { if (signal.aborted) stop = pastDeadline ? "deadline" : "cancelled"; else if (countOf(timelineId) >= o.limits.posts) stop = "post-cap"; else if (scrolls >= o.limits.scrolls) stop = "scroll-cap"; if (stop) break; const before = countOf(timelineId); await bounded("scrolling", page.evaluate(SCROLL_TO_BOTTOM), t.call, signal); scrolls++; out.scrolls++; await pause(o.pauseMs(), signal); await settle(); stop = blocked(); if (stop) break; if (countOf(timelineId) === before) { if (++idle >= X_TRENDING_IDLE_SCROLLS) stop = "idle"; } else { idle = 0; } log(`Scroll ${out.scrolls}: ${countOf(timelineId)} post(s) on this tab, ${out.responses} answer(s).`); } return { stop: stop ?? "idle", scrolls }; }; // A stop that ends the whole read, not one tab's scrolling. const ends = (stop: TrendingReadStop) => stop !== "idle" && stop !== "scroll-cap" && stop !== "post-cap"; // THE TAB THE PAGE OPENS ON. const named = tabOf("top"); const top = named ?? (firstTimeline ? { label: undefined, timelineId: firstTimeline } : undefined); const openingTab: TrendingTabRead = { asked: "top", ...(top?.label ? { tab: top.label } : {}), ...(top ? { timelineId: top.timelineId } : {}), scrolls: 0, posts: 0, stop: "not-asked", }; out.tabs.push(openingTab); let stop: TrendingReadStop = blocked() ?? "idle"; if (wanted.includes("top") || blocked()) { const r = await scrollTab(top?.timelineId); openingTab.stop = r.stop; openingTab.scrolls = r.scrolls; stop = r.stop; } openingTab.posts = countOf(top?.timelineId); // THE OTHER TAB: pressed, never asked for. WHATEVER HAPPENS HERE, THE // OPENING TAB'S READ STANDS (review 2 S2): a press that fails is "not // read", and the read's deadline falling inside it stops this tab only. // `abandoned`: the page left the trending page — nothing more is done // with it (S1); `hung`: a page call did not answer (no screenshot). let abandoned = false; let hung = false; if (wanted.includes("latest") && !ends(stop)) { const latest = tabOf("latest"); const second: TrendingTabRead = { asked: "latest", ...(latest ? { tab: latest.label, timelineId: latest.timelineId } : {}), scrolls: 0, posts: 0, stop: "not-read", }; out.tabs.push(second); const label = latest?.label ?? TRENDING_TAB_LABEL.latest; // The read's own deadline (or a page that stopped answering) inside // this tab: it stops here, with what it had; the read is the opening // tab's. A cancel is the whole read's. const cutHere = (err: unknown): boolean => { if (err instanceof PageDeadlineError) hung = true; if (o.signal.aborted) return false; return pastDeadline || err instanceof PageDeadlineError; }; if (!latest) { second.why = pageInfo ? `the page's own answer names no "${label}" tab (it names: ${pageInfo.tabs.map((x) => `"${x.label}"`).join(", ") || "none"})` : "the page's own answer, which names its tabs and their timelines, was not among what it fetched"; } else if (!page.getByRole) { second.why = "this page cannot be pressed"; } else { // THE PAGE'S OWN TAB (S1): a control of role "tab", INSIDE the page's // tab list, with exactly the name the page's own answer gave. Never a // link or a button of that name: those go elsewhere. const had = answersBy.get(latest.timelineId) ?? 0; let pressed = false; try { const list = page.getByRole("tablist"); const found = list.getByRole?.("tab", { name: latest.label, exact: true }); const count = found ? await bounded(`looking for the "${label}" tab`, found.count(), t.call, signal) : 0; if (!found || !count) { second.why = `the page shows no tab named "${label}" in its tab list`; } else { await bounded(`pressing the "${label}" tab`, found.first().click({ timeout: Math.min(t.call, 15_000) }), t.call, signal); pressed = true; log(`Pressed the page's "${label}" tab.`); } } catch (err) { if (o.signal.aborted) throw err; second.why = `pressing "${label}" failed: ${firstLine(err)}`; if (err instanceof PageDeadlineError) hung = true; } // STILL THE SAME PAGE (S1): a press that took the page anywhere else // stops the read at once — nothing more is read, pressed or shot. if (pressed) { const href = await bounded("reading its address", page.evaluate("location.href"), t.call, signal).catch(() => null); if (!sameTrendingPage(href, o.url)) { second.why = TRENDING_PAGE_CHANGED; abandoned = true; pressed = false; log(`After pressing "${label}" the page is no longer the trending page${typeof href === "string" ? ` (${safePath(href)})` : ""}: the read stops here.`); } } if (pressed) { // The page's own request for that tab's timeline: waited for, in // short steps, on ITS OWN 20 s WALL CLOCK (S3) — each step's settle // counted, not only the steps. const waitFrom = now(); for (let waited = 0; waited < t.tab && now() - waitFrom < t.tab && (answersBy.get(latest.timelineId) ?? 0) <= had && !signal.aborted && !blocked(); waited += 500) { await pause(500, signal); await settle(); } if (blocked()) { second.stop = blocked()!; stop = second.stop; } else if (signal.aborted) { if (o.signal.aborted) { second.stop = "cancelled"; stop = "cancelled"; } else { second.stop = "deadline"; } } else if ((answersBy.get(latest.timelineId) ?? 0) <= had) { second.why = `pressing "${label}" brought no answer for its timeline within ${Math.round(t.tab / 1000)} s`; } else { const scrollsBefore = out.scrolls; try { await pause(o.pauseMs(), signal); await settle(); const r = await scrollTab(latest.timelineId); second.stop = r.stop; // The deadline inside Latest is Latest's stop, not the read's. if (r.stop !== "deadline") stop = r.stop; } catch (err) { if (!cutHere(err)) throw err; second.stop = "deadline"; } second.scrolls = out.scrolls - scrollsBefore; } } } second.posts = countOf(latest?.timelineId); if (second.stop === "deadline") log(`The "${label}" tab stopped at the read's deadline, with ${second.posts} post(s).`); // The page as it stood after the press (or the try): beside page.png. if (!abandoned && !hung && !signal.aborted) { try { const png = await bounded("the second screenshot", page.screenshot({ type: "png" }), t.call, signal); await writeFile(path.join(o.dir, TRENDING_TAB_SHOT_FILENAME), png); out.tabShot = true; } catch { /* the screenshot is a courtesy: its failure costs nothing */ } } if (second.stop === "not-read") log(`The "${label}" tab was not read: ${second.why}.`); } // The deadline fell inside the second tab: the read is the first's. if (out.tabs[1]?.stop === "deadline") latestCut = true; out.stop = stop; } catch (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 { 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; // 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 && opening) { void opening .then(async (s) => { log("The browser opened after the read had ended: closing it."); await bounded("closing the browser", s.close(), t.close).catch(() => (s.kill ? s.kill() : undefined)); }) .catch(() => {}); } 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 && !latestCut) out.stop = "deadline"; out.tweets = seen.size; return out; } // THE PROFILE'S PAGE. Headless: the bundled build on the connected profile, // as a post capture opens it. Headed: a window on the editor's desktop, found // at this read as a Connect finds it (refused with its sentence when there is // no desktop). `chromium` is injectable (the e2e suite's fake, tests' stubs). export async function openXTrendingPage( paths: Paths, o: { headed?: boolean; chromium?: ChromiumLike; onLog?: (line: string) => void; env?: Record; display?: HeadedDisplayLaunchDeps; // For tests: how the browser's pid is found and signalled. killDeps?: ProfileBrowserPidDeps; } = {}, ): Promise { const log = o.onLog ?? (() => {}); let context; if (o.headed) { const chromium = o.chromium ?? (await importPlaywright()).chromium; ({ context } = await launchHeadedContext({ chromium, profileDir: xProfileDir(paths), browser: findXBrowser({ env: o.env }), onLog: log, env: o.env, display: o.display, })); } else { context = await launchXProfile(paths, { onLog: log, ...(o.chromium ? { chromium: o.chromium } : {}) }); } // 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; } // A BROWSER THAT DOES NOT CLOSE IS KILLED, BY PID (lane x-trending-2; // profileBrowserPid.ts): the process Chromium's own lock in the profile // names, and only when its command line names this exact profile directory. // Off Linux, or when that check does not hold, nothing is killed: the // context is closed again instead, and the log says which it was. const profileDir = xProfileDir(paths); return { page, close: () => context.close(), kill: async () => { const r = await killProfileBrowser(profileDir, o.killDeps); if (r.killed) { log(`Killed the browser that held the X profile (pid ${r.pid}): the profile is free again.`); return; } log(`The browser was not killed (${r.why}); closing it again instead.`); await context.close(); }, }; }