commit d477716f5c1c713c00c022246df779a728abe35e
parent e0d3ceb9af18cd4365c43d11eb9a0b789cfb681f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 03:59:29 -0500
x-trending review 1 (M4, S3, S5, S8, S9, nits): still kept at the login, a CDN that refuses, an index that cannot be read
M4: the logged-in download asks, immediately before it, whether the post is still kept. S3: the wait for an answer's headers is its own timer, cleared when they arrive, and a body nobody will read is cancelled. S5: a library's capture takes no queue override. S8: a media index that is there and cannot be read throws, naming the file, and is never written over. S9: three refusals in a row (a 403, or no answer) end a job's media half, the rest owed. The store compares sizes before linking onto a blob and sweeps link temps; removing a capture refuses while a capture of the library is in flight. The pid check also asks the lock's host, a Chromium binary and the browser process.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
13 files changed, 484 insertions(+), 52 deletions(-)
diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts
@@ -614,3 +614,59 @@ test("an X trending library's media comes from the CDN addresses in its saved ca
assert.equal(Object.keys((await readXTrendingMediaIndex(root)).blobs).length, 2);
assert.match(await readFile(path.join(root, "trending", ".gitignore"), "utf8"), /^posts-media\/$/m);
});
+
+// Review 1 M4: the still-kept check reaches the media half.
+test("an X trending library's logged-in fallback asks, per post and at that moment, whether it may", async () => {
+ const { recordXTrendingRead, writeXTrendingPosts } = await import("../lib/xTrending/store");
+ const root = path.join(channelsDir, "demo-library-kept");
+ await mkdir(path.join(root, "trending"), { recursive: true });
+ await writeFile(
+ path.join(root, "config.json"),
+ JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", postFetcher: "test-capture-x", name: "Library", xTrending: {} }),
+ );
+ const post = (id: string) => ({
+ id, slug: `demo-library-kept/${id}`, channelSlug: "demo-library-kept", author: "a", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116",
+ text: "t", url: `https://x.com/a/status/${id}`, platform: "twitter" as const, isReply: false, isRepost: false, links: [],
+ });
+ await writeXTrendingPosts(root, [post("8001"), post("8002")]);
+ // Media the saved captures name no address for: only a login could fetch it.
+ await recordXTrendingRead(root, {
+ readId: "tr-01JA0000000000000000000000", at: "2026-11-18T10:00:00.000Z",
+ ref: { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" },
+ topic: "T", postIds: ["8001", "8002"], added: 2,
+ media: { "8001": { count: 1, kinds: ["video"] }, "8002": { count: 1, kinds: ["video"] } },
+ });
+ const { getSocialFetcher } = await import("../social/fetchers");
+ const fake = getSocialFetcher("test-capture-x")!;
+ const original = fake.captureByIds!;
+ const logins: string[] = [];
+ const results: Record<string, { ok: boolean }> = {};
+ fake.captureByIds = async (input) => {
+ for (const id of input.ids) {
+ results[id] = await input.downloadMedia!({ id, dir: path.join(input.outDir, id), signal: new AbortController().signal }, async () => {
+ logins.push(id);
+ return { ok: true, files: [] };
+ });
+ }
+ return { outcomes: [] };
+ };
+ const asked: string[] = [];
+ try {
+ const res = await run("demo-library-kept", ["8001", "8002"], {
+ shots: false, articles: false, context: false,
+ libraryMedia: {
+ fallback: "login",
+ maxVideoBytes: null,
+ // 8002 was dropped after the job was queued.
+ mayLogin: async (id: string) => (asked.push(id), id === "8001"),
+ deps: { cooldownMs: async () => 0, pause: async () => {} },
+ },
+ });
+ assert.equal(res.ok, true, res.error);
+ } finally {
+ fake.captureByIds = original;
+ }
+ assert.deepEqual(asked, ["8001", "8002"]);
+ assert.deepEqual(logins, ["8001"]);
+ assert.deepEqual([results["8001"].ok, results["8002"].ok], [true, false]);
+});
diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts
@@ -140,8 +140,11 @@ export type CapturePostsOptions = {
// maxVideoBytes a file over this is owed, not kept; null = no cap (a
// kept post). Default: the library's `maxVideoMb`.
// deps tests and the e2e test server: the fetch and the waits.
+ // mayLogin asked immediately before each logged-in download:
+ // whether the post is STILL marked keep (review 1 M4).
libraryMedia?: {
fallback?: "login" | "none";
+ mayLogin?: (id: string) => Promise<boolean>;
maxVideoBytes?: number | null;
deps?: Partial<LibraryMediaDeps>;
};
@@ -544,6 +547,7 @@ async function libraryMediaDownloader(
expected,
maxVideoBytes: asked?.maxVideoBytes === undefined ? xTrendingMaxVideoBytes(config) : asked.maxVideoBytes,
fallback: asked?.fallback ?? "none",
+ ...(asked?.mayLogin ? { mayLogin: asked.mayLogin } : {}),
deps: {
fetch: (url, init) => fetch(url, init) as unknown as ReturnType<MediaFetch>,
pauseMs: () => libraryMediaPauseMs(),
diff --git a/common/lib/xTrending/mediaStore.test.ts b/common/lib/xTrending/mediaStore.test.ts
@@ -6,7 +6,10 @@ import { tmpdir } from "node:os";
import path from "node:path";
import {
adoptXTrendingMedia,
+ CAPTURE_IN_FLIGHT,
ensureXTrendingMediaIgnore,
+ noteXTrendingOversize,
+ xTrendingMediaIndexPath,
linkXTrendingMedia,
readXTrendingMediaIndex,
removeXTrendingPostCapture,
@@ -17,6 +20,8 @@ import {
const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-media-"));
after(() => rmSync(TMP, { recursive: true, force: true }));
+// No capture of the library is queued or running.
+const IDLE = { captureInFlight: () => false };
const sha = (s: string) => createHash("sha256").update(s).digest("hex");
const root = (name: string) => path.join(TMP, name);
const postDir = (dir: string, id: string) => path.join(dir, "trending", "posts-media", id);
@@ -105,7 +110,7 @@ test("deleting a post never deletes media another post still uses", async () =>
const only = blobOf(dir, "ONLY-621", "jpg");
assert.equal(statSync(shared).nlink, 3);
- const removed = await removeXTrendingPostCapture(dir, "621");
+ const removed = await removeXTrendingPostCapture(dir, "621", IDLE);
assert.deepEqual(removed, { files: 4, blobsFreed: 1, bytesFreed: 8, blobsKept: 1 });
assert.equal(existsSync(postDir(dir, "621")), false);
// 622's picture is whole, and so is the store's copy of it.
@@ -117,11 +122,11 @@ test("deleting a post never deletes media another post still uses", async () =>
assert.deepEqual(index.blobs[sha("SHARED")].posts, { "622": ["622_1.jpg"] });
// The last post that carries it takes the blob with it.
- assert.deepEqual(await removeXTrendingPostCapture(dir, "622"), { files: 1, blobsFreed: 1, bytesFreed: 6, blobsKept: 0 });
+ assert.deepEqual(await removeXTrendingPostCapture(dir, "622", IDLE), { files: 1, blobsFreed: 1, bytesFreed: 6, blobsKept: 0 });
assert.equal(existsSync(shared), false);
assert.deepEqual((await readXTrendingMediaIndex(dir)).blobs, {});
// A post with no capture: nothing to remove, nothing thrown.
- assert.deepEqual(await removeXTrendingPostCapture(dir, "629"), { files: 0, blobsFreed: 0, bytesFreed: 0, blobsKept: 0 });
+ assert.deepEqual(await removeXTrendingPostCapture(dir, "629", IDLE), { files: 0, blobsFreed: 0, bytesFreed: 0, blobsKept: 0 });
});
test("a blob something else still links to is kept, even when the index names no post for it", async () => {
@@ -132,7 +137,7 @@ test("a blob something else still links to is kept, even when the index names no
const { linkSync } = await import("node:fs");
mkdirSync(postDir(dir, "632"), { recursive: true });
linkSync(blobOf(dir, "KEPT-ELSEWHERE", "jpg"), path.join(postDir(dir, "632"), "632_1.jpg"));
- const removed = await removeXTrendingPostCapture(dir, "631");
+ const removed = await removeXTrendingPostCapture(dir, "631", IDLE);
assert.equal(removed.blobsFreed, 0);
assert.equal(removed.blobsKept, 1);
assert.equal(readFileSync(path.join(postDir(dir, "632"), "632_1.jpg"), "utf8"), "KEPT-ELSEWHERE");
@@ -144,9 +149,63 @@ test("ids and names are checked where they become paths; the media is ignored by
await assert.rejects(adoptXTrendingMedia(dir, { postId: "../x", name: "a.jpg" }), /not a post id/);
await assert.rejects(adoptXTrendingMedia(dir, { postId: "1", name: "../a.jpg" }), /not a media file's name/);
await assert.rejects(adoptXTrendingMedia(dir, { postId: "1", name: ".hidden" }), /not a media file's name/);
- await assert.rejects(removeXTrendingPostCapture(dir, "_avatars"), /not a post id/);
+ await assert.rejects(removeXTrendingPostCapture(dir, "_avatars", IDLE), /not a post id/);
await ensureXTrendingMediaIgnore(dir);
const ignore = readFileSync(path.join(dir, "trending", ".gitignore"), "utf8");
assert.match(ignore, /^posts-media\/$/m);
assert.match(ignore, /^media-store\/$/m);
});
+
+// Review 1 S8.
+test("S8: a media index that is there and cannot be read is never taken for an empty one: nothing is written over it", async () => {
+ const dir = root("broken-index");
+ put(dir, "641", "641_1.jpg", "FIRST");
+ await adoptXTrendingMedia(dir, { postId: "641", name: "641_1.jpg" });
+ const file = xTrendingMediaIndexPath(dir);
+ // No file at all IS an empty index.
+ assert.deepEqual((await readXTrendingMediaIndex(root("no-index-yet"))).blobs, {});
+ for (const broken of ['{"version":1,"blobs":{"ab', "[]", ""]) {
+ writeFileSync(file, broken);
+ await assert.rejects(readXTrendingMediaIndex(dir), (e: Error) => {
+ assert.match(e.message, /The library's media index \(.*media-index\.json\) is not (JSON|a media index)/);
+ assert.match(e.message, /Nothing was written/);
+ return true;
+ });
+ put(dir, "642", "642_1.jpg", "SECOND");
+ await assert.rejects(adoptXTrendingMedia(dir, { postId: "642", name: "642_1.jpg" }), /media index/);
+ await assert.rejects(linkXTrendingMedia(dir, { postId: "643", name: "643_1.jpg", sha256: sha("FIRST") }), /media index/);
+ await assert.rejects(noteXTrendingOversize(dir, { url: "https://video.twimg.com/v.mp4", bytes: 9 }), /media index/);
+ await assert.rejects(removeXTrendingPostCapture(dir, "641", IDLE), /media index/);
+ assert.equal(readFileSync(path.join(postDir(dir, "641"), "641_1.jpg"), "utf8"), "FIRST");
+ // The broken file is as it was: not replaced by a one-entry index.
+ assert.equal(readFileSync(file, "utf8"), broken);
+ }
+});
+
+test("a blob that is not the size of the bytes it is named for is never linked onto; link temps a crash left are swept", async () => {
+ const dir = root("size");
+ put(dir, "651", "651_1.jpg", "WHOLE-PICTURE");
+ await adoptXTrendingMedia(dir, { postId: "651", name: "651_1.jpg", url: "https://pbs.twimg.com/media/W.jpg" });
+ // The store's copy is cut short under it (and no longer shares the post's bytes).
+ const blob = blobOf(dir, "WHOLE-PICTURE", "jpg");
+ rmSync(blob);
+ writeFileSync(blob, "WHOLE");
+ const b = put(dir, "652", "652_1.jpg", "WHOLE-PICTURE");
+ // A crash's leftover link temp beside it.
+ writeFileSync(path.join(postDir(dir, "652"), ".652_1.jpg.link-99999"), "x");
+ const got = await adoptXTrendingMedia(dir, { postId: "652", name: "652_1.jpg" });
+ assert.deepEqual([got.deduped, got.linked], [false, false]);
+ assert.equal(readFileSync(b, "utf8"), "WHOLE-PICTURE");
+ assert.deepEqual(readdirSync(postDir(dir, "652")), ["652_1.jpg"]);
+ // Nor is a known address linked from a blob of the wrong size.
+ assert.equal(await linkXTrendingMedia(dir, { postId: "653", name: "653_1.jpg", sha256: sha("WHOLE-PICTURE") }), null);
+});
+
+test("a post's capture is not removed while a capture of the library is queued or running", async () => {
+ const dir = root("in-flight");
+ put(dir, "661", "661_1.jpg", "BYTES");
+ await adoptXTrendingMedia(dir, { postId: "661", name: "661_1.jpg" });
+ await assert.rejects(removeXTrendingPostCapture(dir, "661", { captureInFlight: async () => true }), (e: Error) => e.message === CAPTURE_IN_FLIGHT);
+ assert.equal(existsSync(path.join(postDir(dir, "661"), "661_1.jpg")), true);
+ assert.equal((await removeXTrendingPostCapture(dir, "661", IDLE)).files, 1);
+});
diff --git a/common/lib/xTrending/mediaStore.ts b/common/lib/xTrending/mediaStore.ts
@@ -121,9 +121,33 @@ function parseIndex(raw: unknown): XTrendingMediaIndex {
return out;
}
+// The index exists and cannot be read as one.
+export class XTrendingMediaIndexError extends Error {
+ constructor(file: string, why: string) {
+ super(
+ `The library's media index (${file}) ${why}. Nothing was written: an index read as empty would be written back over the record of ` +
+ "every file the library holds. Repair the file, or move it away (the store's files stay; captures made after that are indexed afresh).",
+ );
+ this.name = "XTrendingMediaIndexError";
+ }
+}
+
+// The index — an EMPTY one only when there is no file yet. A file that is
+// there and cannot be read or parsed THROWS (review 1 S8): every writer here
+// reads, changes and writes back, and "unreadable" taken for "empty" would
+// replace the whole record with the one entry being added. The capture job
+// fails with the sentence, naming the file.
export async function readXTrendingMediaIndex(channelRoot: string): Promise<XTrendingMediaIndex> {
- const read = await readJsonFile(xTrendingMediaIndexPath(channelRoot));
- return read.ok ? parseIndex(read.value) : { version: 1, blobs: {}, oversize: {} };
+ const file = xTrendingMediaIndexPath(channelRoot);
+ const read = await readJsonFile(file);
+ if (!read.ok) {
+ if (read.reason === "absent") return { version: 1, blobs: {}, oversize: {} };
+ throw new XTrendingMediaIndexError(file, read.reason === "unparseable" ? "is not JSON (cut short, or edited by hand)" : "cannot be read");
+ }
+ if (!read.value || typeof read.value !== "object" || Array.isArray(read.value)) {
+ throw new XTrendingMediaIndexError(file, "is not a media index (not an object)");
+ }
+ return parseIndex(read.value);
}
// The blob that came from this address, or undefined.
@@ -162,6 +186,13 @@ async function linkOver(target: string, file: string): Promise<boolean> {
return true;
}
+// Link temps a crash left in a capture directory (`.<name>.link-<pid>`):
+// removed under the index's lock, where no link of this process is in flight.
+async function sweepLinkTemps(dir: string): Promise<void> {
+ const names = await readdir(dir).catch(() => [] as string[]);
+ for (const name of names) if (/^\..+\.link-\d+$/.test(name)) await rm(path.join(dir, name), { force: true });
+}
+
const sameFile = (a: { dev: number; ino: number }, b: { dev: number; ino: number }) => a.dev === b.dev && a.ino === b.ino;
function note(blob: XTrendingMediaBlob, postId: string, name: string, url?: string): void {
@@ -209,11 +240,17 @@ export async function adoptXTrendingMedia(
const ext = have?.ext ?? extOf(o.name);
const blob = blobPath(channelRoot, sha256, ext);
await mkdir(path.dirname(blob), { recursive: true });
+ await sweepLinkTemps(path.dirname(file));
const [fileStat, blobStat] = await Promise.all([stat(file), stat(blob).catch(() => null)]);
let deduped = false;
let linked: boolean;
if (blobStat && sameFile(fileStat, blobStat)) {
linked = true;
+ } else if (blobStat && blobStat.size !== bytes) {
+ // A blob under this hash's name that is not this size is not these
+ // bytes (cut short, or changed under the store): never linked onto.
+ // The file stays its own copy, and the index does not claim it.
+ return { sha256, bytes, deduped: false, linked: false };
} else if (blobStat) {
// The library holds these bytes: this name becomes a link to them.
linked = await linkOver(blob, file);
@@ -252,8 +289,11 @@ export async function linkXTrendingMedia(
const blob = blobPath(channelRoot, o.sha256, entry.ext);
const blobStat = await stat(blob).catch(() => null);
if (!blobStat?.isFile()) return null;
+ // The index's size for it, or it is not the file the index means.
+ if (entry.bytes > 0 && blobStat.size !== entry.bytes) return null;
const dir = postCaptureDir(xTrendingPostsMediaDir(channelRoot), o.postId);
await mkdir(dir, { recursive: true });
+ await sweepLinkTemps(dir);
if (!(await linkOver(blob, path.join(dir, o.name)))) return null;
note(entry, o.postId, o.name, o.url);
await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true });
@@ -277,11 +317,25 @@ export type RemovedCapture = {
// deleted: its bytes stay under that post's name and in the store.
// (No door calls this in this slice; the purge button and its ops twin are a
// later one's.)
-export async function removeXTrendingPostCapture(channelRoot: string, postId: string): Promise<RemovedCapture> {
+//
+// REFUSED WHILE A CAPTURE OF THE LIBRARY IS QUEUED OR RUNNING (`captureInFlight`,
+// which the caller answers from its job registry — required, so no door can
+// forget it): a capture writes these same directories outside the lock.
+export const CAPTURE_IN_FLIGHT =
+ "A capture of this library is queued or running: remove a post's capture once it has finished (its job is on /jobs).";
+
+export async function removeXTrendingPostCapture(
+ channelRoot: string,
+ postId: string,
+ o: { captureInFlight: () => boolean | Promise<boolean> },
+): Promise<RemovedCapture> {
if (!POST_ID.test(postId)) throw new Error(`"${postId}" is not a post id`);
+ if (await o.captureInFlight()) throw new Error(CAPTURE_IN_FLIGHT);
const dir = postCaptureDir(xTrendingPostsMediaDir(channelRoot), postId);
return withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => {
const out: RemovedCapture = { files: 0, blobsFreed: 0, bytesFreed: 0, blobsKept: 0 };
+ // The index FIRST: one that cannot be read stops this before a file goes.
+ const index = await readXTrendingMediaIndex(channelRoot);
const names = await readdir(dir).catch(() => [] as string[]);
for (const name of names) {
const st = await lstat(path.join(dir, name)).catch(() => null);
@@ -291,7 +345,6 @@ export async function removeXTrendingPostCapture(channelRoot: string, postId: st
out.files++;
}
await rmdir(dir).catch(() => {});
- const index = await readXTrendingMediaIndex(channelRoot);
let changed = false;
for (const [sha, entry] of Object.entries(index.blobs)) {
if (!entry.posts[postId]) continue;
diff --git a/common/social/profileBrowserPid.test.ts b/common/social/profileBrowserPid.test.ts
@@ -4,7 +4,7 @@ import { after, test } from "node:test";
import assert from "node:assert/strict";
import { spawn, type ChildProcess } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";
-import { tmpdir } from "node:os";
+import { hostname, tmpdir } from "node:os";
import path from "node:path";
import { killProfileBrowser, profileBrowserPid } from "./profileBrowserPid";
@@ -23,8 +23,9 @@ function profile(name: string, lock?: string): string {
}
// A process that stands in for a browser: it sleeps, with `arg` on its command line.
-function sleeper(arg: string): Promise<ChildProcess> {
- const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000); console.log('up')", "--", arg], { stdio: ["ignore", "pipe", "ignore"] });
+// `argv0` is what /proc shows as its name: "chrome" for the stand-in browser.
+function sleeper(arg: string, argv0 = "chrome"): Promise<ChildProcess> {
+ const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000); console.log('up')", "--", arg], { argv0, stdio: ["ignore", "pipe", "ignore"] });
children.push(child);
return new Promise((resolve, reject) => {
child.once("error", reject);
@@ -40,7 +41,7 @@ test("the pid comes from the profile's own lock, and only when that process name
const none = profile("none");
assert.deepEqual(await profileBrowserPid(none, { platform: "linux" }), { pid: null, why: "the profile has no browser lock (no browser holds it)" });
const dir = profile("exact", "host-4242");
- const deps = (cmdline: string) => ({ platform: "linux", cmdline: async () => cmdline });
+ const deps = (cmdline: string) => ({ platform: "linux", hostname: "host", cmdline: async () => cmdline });
assert.deepEqual(await profileBrowserPid(dir, deps(`chrome\0--headless\0--user-data-dir=${dir}\0`)), { pid: 4242 });
// Another profile whose path merely starts the same: left alone.
const other = await profileBrowserPid(dir, deps(`chrome\0--user-data-dir=${dir}-other\0`));
@@ -48,8 +49,19 @@ test("the pid comes from the profile's own lock, and only when that process name
assert.match(other.pid === null ? other.why : "", /process 4242 does not name this profile on its command line \(a stale lock\): it is left alone/);
// The directory mentioned, but not as the profile argument.
assert.equal((await profileBrowserPid(dir, deps(`vim\0${dir}\0`))).pid, null);
+ // Review 1: another program that carries the very argument is not a browser...
+ const notChrome = await profileBrowserPid(dir, deps(`/usr/bin/python3\0--user-data-dir=${dir}\0`));
+ assert.match(notChrome.pid === null ? notChrome.why : "", /process 4242 is not a Chromium browser \(python3\): it is left alone/);
+ // ...a browser's child process (a renderer) is not the browser...
+ const child = await profileBrowserPid(dir, deps(`/opt/chromium/chrome\0--type=renderer\0--user-data-dir=${dir}\0`));
+ assert.match(child.pid === null ? child.why : "", /one of a browser's child processes/);
+ // ...and a lock written on another machine names a pid of that machine.
+ const elsewhere = await profileBrowserPid(dir, { platform: "linux", hostname: "another-host", cmdline: async () => `chrome\0--user-data-dir=${dir}\0` });
+ assert.match(elsewhere.pid === null ? elsewhere.why : "", /written on another machine/);
+ // The headless shell, by its full path, is a browser.
+ assert.deepEqual(await profileBrowserPid(dir, deps(`/opt/pw/chromium_headless_shell-1/chrome-linux/headless_shell\0--user-data-dir=${dir}\0`)), { pid: 4242 });
// A lock whose process is gone.
- const gone = await profileBrowserPid(dir, { platform: "linux", cmdline: async () => { throw new Error("ENOENT"); } });
+ const gone = await profileBrowserPid(dir, { platform: "linux", hostname: "host", cmdline: async () => { throw new Error("ENOENT"); } });
assert.match(gone.pid === null ? gone.why : "", /\(4242\) is gone/);
// A lock that names no usable pid: 0, 1, this process, no number.
for (const lock of ["host-0", "host-1", `host-${process.pid}`, "nonsense"]) {
@@ -64,10 +76,10 @@ test("a kill signals the checked pid and nothing else", async () => {
const dir = profile("kill", "host-777");
const sent: Array<[number, string]> = [];
const kill = (pid: number, signal: NodeJS.Signals) => void sent.push([pid, signal]);
- assert.deepEqual(await killProfileBrowser(dir, { platform: "linux", cmdline: async () => `c\0--user-data-dir=${dir}\0`, kill }), { killed: true, pid: 777 });
+ assert.deepEqual(await killProfileBrowser(dir, { platform: "linux", hostname: "host", cmdline: async () => `chrome\0--user-data-dir=${dir}\0`, kill }), { killed: true, pid: 777 });
assert.deepEqual(sent, [[777, "SIGKILL"]]);
// A stale lock: no signal at all.
- const stale = await killProfileBrowser(dir, { platform: "linux", cmdline: async () => "bash\0", kill });
+ const stale = await killProfileBrowser(dir, { platform: "linux", hostname: "host", cmdline: async () => "bash\0", kill });
assert.equal(stale.killed, false);
assert.equal(sent.length, 1);
// Off Linux: no signal, and why.
@@ -81,13 +93,19 @@ test("for real: a process holding the profile is killed; one that does not name
const holder = await sleeper(`--user-data-dir=${dir}`);
const bystander = await sleeper(`--user-data-dir=${dir}-other`);
// The lock names the bystander: nothing is killed.
- symlinkSync(`host-${bystander.pid}`, path.join(dir, "SingletonLock"));
+ symlinkSync(`${hostname()}-${bystander.pid}`, path.join(dir, "SingletonLock"));
const no = await killProfileBrowser(dir);
assert.equal(no.killed, false);
assert.equal(bystander.exitCode, null);
// The lock names the holder: it is killed, the bystander is not.
rmSync(path.join(dir, "SingletonLock"));
- symlinkSync(`host-${holder.pid}`, path.join(dir, "SingletonLock"));
+ // A process that names the profile and is not a browser: left alone.
+ const impostor = await sleeper(`--user-data-dir=${dir}`, "node");
+ symlinkSync(`${hostname()}-${impostor.pid}`, path.join(dir, "SingletonLock"));
+ assert.equal((await killProfileBrowser(dir)).killed, false);
+ assert.equal(impostor.exitCode, null);
+ rmSync(path.join(dir, "SingletonLock"));
+ symlinkSync(`${hostname()}-${holder.pid}`, path.join(dir, "SingletonLock"));
const gone = exited(holder);
assert.deepEqual(await killProfileBrowser(dir), { killed: true, pid: holder.pid });
assert.equal(await gone, "SIGKILL");
diff --git a/common/social/profileBrowserPid.ts b/common/social/profileBrowserPid.ts
@@ -8,18 +8,29 @@
// somebody kills it by hand. So the pid is read where Chromium itself writes
// it: `<profile>/SingletonLock`, a symlink to `<host>-<pid>`.
//
-// A PID IS ONLY EVER KILLED WHEN ITS COMMAND LINE NAMES THIS EXACT PROFILE
-// DIRECTORY (`--user-data-dir=<profile>` as one argument of
-// `/proc/<pid>/cmdline`), checked again immediately before the signal: a stale
-// lock whose pid now belongs to another process, or a lock of another profile,
-// is never signalled. Linux only (it reads /proc); anywhere else, and whenever
-// the check does not hold, nothing is killed and the caller is told why — it
-// falls back to closing, and says so in the job's log.
+// A PID IS ONLY EVER KILLED WHEN IT IS THIS PROFILE'S BROWSER, and every one
+// of these holds:
+// - the lock was written on THIS machine (its host is os.hostname(): a
+// profile on a shared disk can carry another machine's pid);
+// - the process's command line (`/proc/<pid>/cmdline`) names this exact
+// profile directory, `--user-data-dir=<profile>` as one argument;
+// - its first argument looks like a Chromium binary (chrome, chromium,
+// headless_shell, …);
+// - it is the BROWSER process, not one of its children: no `--type=`
+// argument (renderers, the GPU process and the rest carry one).
+// The check is made once, by killProfileBrowser, immediately before the
+// signal — nothing else runs between reading the command line and signalling.
+// A stale lock whose pid now belongs to another process, a lock of another
+// profile, another program that merely mentions the directory: none is
+// signalled. Linux only (it reads /proc); anywhere else, and whenever the
+// check does not hold, nothing is killed and the caller is told why — it falls
+// back to closing, and says so in the job's log.
//
// `process.kill(pid)` on a checked pid, never a child's `.kill()` and never a
// process group.
import { readFile, readlink } from "node:fs/promises";
+import os from "node:os";
import path from "node:path";
export type ProfileBrowserPidDeps = {
@@ -29,8 +40,11 @@ export type ProfileBrowserPidDeps = {
cmdline?: (pid: number) => Promise<string>;
kill?: (pid: number, signal: NodeJS.Signals) => void;
selfPid?: number;
+ hostname?: string;
};
+const CHROMIUM_BINARY = /^(chrome|chromium|chromium-browser|chrome-headless-shell|headless_shell|google-chrome(-[a-z]+)?|brave(-browser)?|msedge|microsoft-edge(-[a-z]+)?)$/i;
+
export type ProfileBrowserPid = { pid: number } | { pid: null; why: string };
const realCmdline = (pid: number) => readFile(`/proc/${pid}/cmdline`, "utf8");
@@ -48,8 +62,11 @@ export async function profileBrowserPid(profileDir: string, deps: ProfileBrowser
} catch {
return { pid: null, why: "the profile has no browser lock (no browser holds it)" };
}
- const m = /-(\d{1,10})$/.exec(target);
- const pid = m ? Number(m[1]) : NaN;
+ const m = /^(.*)-(\d{1,10})$/.exec(target);
+ const pid = m ? Number(m[2]) : NaN;
+ if (m && m[1] !== (deps.hostname ?? os.hostname())) {
+ return { pid: null, why: "the profile's lock was written on another machine: its process is not looked for here" };
+ }
if (!Number.isInteger(pid) || pid <= 1 || pid === (deps.selfPid ?? process.pid)) {
return { pid: null, why: "the profile's lock names no browser process" };
}
@@ -65,13 +82,19 @@ export async function profileBrowserPid(profileDir: string, deps: ProfileBrowser
if (!names) {
return { pid: null, why: `process ${pid} does not name this profile on its command line (a stale lock): it is left alone` };
}
+ if (!CHROMIUM_BINARY.test(path.basename(args[0] ?? ""))) {
+ return { pid: null, why: `process ${pid} is not a Chromium browser (${path.basename(args[0] ?? "") || "no name"}): it is left alone` };
+ }
+ if (args.some((a) => a.startsWith("--type="))) {
+ return { pid: null, why: `process ${pid} is one of a browser's child processes, not the browser: it is left alone` };
+ }
return { pid };
}
export type KilledProfileBrowser = { killed: true; pid: number } | { killed: false; why: string };
// SIGKILL to the browser holding `profileDir` — only to a pid that passes the
-// check above, taken again here, immediately before the signal.
+// check above, made here, immediately before the signal.
export async function killProfileBrowser(profileDir: string, deps: ProfileBrowserPidDeps = {}): Promise<KilledProfileBrowser> {
const found = await profileBrowserPid(profileDir, deps);
if (found.pid === null) return { killed: false, why: found.why };
diff --git a/common/social/xTrendingMedia.test.ts b/common/social/xTrendingMedia.test.ts
@@ -29,11 +29,12 @@ const vid = (key: string): TrendingMediaSource => ({
ext: "mp4",
});
-type Answer = { status?: number; body?: string; length?: number; throws?: string };
+type Answer = { status?: number; body?: string; length?: number; throws?: string; slowBodyMs?: number };
function harness(name: string, answers: Record<string, Answer>, over: Partial<LibraryMediaDeps> = {}) {
const root = path.join(TMP, name);
const asked: string[] = [];
+ const cancelled: string[] = [];
const pauses: number[] = [];
const state = { cooldown: 0, limited: 0 };
const fetch: MediaFetch = async (url, init) => {
@@ -47,11 +48,16 @@ function harness(name: string, answers: Record<string, Answer>, over: Partial<Li
return {
status: a.status ?? 200,
headers: { get: (h) => (h === "content-length" ? String(a.length ?? bytes.length) : null) },
- body: (async function* () {
- // Two chunks, so a cap can fall mid-stream.
- yield bytes.subarray(0, Math.ceil(bytes.length / 2));
- yield bytes.subarray(Math.ceil(bytes.length / 2));
- })(),
+ body: Object.assign(
+ (async function* () {
+ // Two chunks, so a cap can fall mid-stream.
+ yield bytes.subarray(0, Math.ceil(bytes.length / 2));
+ if (a.slowBodyMs) await new Promise((r) => setTimeout(r, a.slowBodyMs));
+ if (init.signal.aborted) throw new Error("aborted");
+ yield bytes.subarray(Math.ceil(bytes.length / 2));
+ })(),
+ { cancel: async () => void cancelled.push(url) },
+ ),
};
};
const deps: LibraryMediaDeps = {
@@ -71,7 +77,7 @@ function harness(name: string, answers: Record<string, Answer>, over: Partial<Li
const noLogin = async (): Promise<PostMediaDownload> => {
throw new Error("the logged-in download must not run");
};
- return { root, asked, pauses, state, deps, dirOf, args, noLogin };
+ return { root, asked, cancelled, pauses, state, deps, dirOf, args, noLogin };
}
test("files come from the CDN one after another, 1 to 2 s apart, and each is kept once", async () => {
@@ -273,3 +279,118 @@ test("an address off X's media CDN is never asked; a fetch that throws marks the
assert.match(res.error, /761_1\.jpg: not an address on X's media CDN; 761_2\.jpg: the CDN did not answer \(socket hang up\)/);
assert.deepEqual(h.asked, ["https://pbs.twimg.com/media/T?format=jpg&name=orig"]);
});
+
+// Review 1 S3.
+test("S3: the wait for the headers ends when they arrive — a body slower than it still comes down; an oversize body is cancelled", async () => {
+ const h = harness(
+ "timers",
+ { [img("Slow").fetchUrl]: { body: "SLOW-BUT-WHOLE", slowBodyMs: 80 }, [vid("Big").fetchUrl]: { body: "x", length: 5000 } },
+ { timeouts: { headersMs: 20, fileMs: 5_000 } },
+ );
+ const download = createLibraryMediaDownloader({
+ channelRoot: h.root,
+ sources: new Map([["771", [img("Slow"), vid("Big")]]]),
+ maxVideoBytes: 100,
+ fallback: "none",
+ deps: h.deps,
+ });
+ const res = await download(h.args("771"), h.noLogin);
+ // The body took four times the headers' limit: it is whole.
+ assert.equal(readFileSync(path.join(h.dirOf("771"), "771_1.jpg"), "utf8"), "SLOW-BUT-WHOLE");
+ assert.equal(res.ok, false);
+ if (res.ok) return;
+ assert.equal(res.owed, "kept");
+ // The file declared over the cap was not left downloading.
+ assert.deepEqual(h.cancelled, [vid("Big").fetchUrl]);
+ // And the file's own limit is still a limit.
+ const strict = harness("timers-file", { [img("Slow").fetchUrl]: { body: "NEVER-WHOLE", slowBodyMs: 80 } }, { timeouts: { headersMs: 20, fileMs: 30 } });
+ const cut = await createLibraryMediaDownloader({ channelRoot: strict.root, sources: new Map([["772", [img("Slow")]]]), maxVideoBytes: 100, fallback: "none", deps: strict.deps })(strict.args("772"), strict.noLogin);
+ assert.equal(cut.ok, false);
+ assert.equal(existsSync(path.join(strict.dirOf("772"), "772_1.jpg")), false);
+ assert.deepEqual(readdirSync(strict.dirOf("772")), []);
+});
+
+// Review 1 S9.
+test("S9: three refusals in a row (a 403, or no answer) and the job asks the CDN no more; the rest is owed to a later capture", async () => {
+ const answers: Record<string, Answer> = {
+ [img("R1").fetchUrl]: { status: 403 },
+ [img("R2").fetchUrl]: { throws: "socket hang up" },
+ [img("R3").fetchUrl]: { status: 403 },
+ [img("Never1").fetchUrl]: { body: "N1" },
+ [img("Never2").fetchUrl]: { body: "N2" },
+ };
+ const h = harness("refusing", answers);
+ const log: string[] = [];
+ const download = createLibraryMediaDownloader({
+ channelRoot: h.root,
+ sources: new Map([["781", [img("R1"), img("R2")]], ["782", [img("R3"), img("Never1")]], ["783", [img("Never2")]]]),
+ maxVideoBytes: 100,
+ fallback: "none",
+ deps: h.deps,
+ });
+ const withLog = (id: string) => ({ ...h.args(id), onLog: (l: string) => void log.push(l) });
+ await download(withLog("781"), h.noLogin);
+ const second = await download(withLog("782"), h.noLogin);
+ const third = await download(withLog("783"), h.noLogin);
+ assert.deepEqual(h.asked, [img("R1").fetchUrl, img("R2").fetchUrl, img("R3").fetchUrl]);
+ assert.equal(second.ok, false);
+ if (!second.ok) assert.match(second.error, /782_2\.jpg: owed \(the CDN refused 3 files in a row; this job asks it no more\)/);
+ // A post that only met the halt is merely owed, to the next capture.
+ assert.deepEqual(third.ok ? null : [third.owed, third.stop], ["next", undefined]);
+ assert.equal(log.filter((l) => /refused 3 files in a row/.test(l)).length, 1);
+
+ // A 404 between them is not a refusal, and a file that comes down starts the count again.
+ const mixed = harness("refusing-mixed", {
+ [img("A").fetchUrl]: { status: 403 },
+ [img("B").fetchUrl]: { status: 403 },
+ [img("C").fetchUrl]: { body: "FINE" },
+ [img("D").fetchUrl]: { status: 403 },
+ [img("E").fetchUrl]: { status: 403 },
+ [img("G").fetchUrl]: { body: "ALSO FINE" },
+ });
+ const res = await createLibraryMediaDownloader({
+ channelRoot: mixed.root,
+ sources: new Map([["791", [img("A"), img("B"), img("C"), img("D"), img("E"), img("Gone"), img("G")]]]),
+ maxVideoBytes: 100,
+ fallback: "none",
+ deps: mixed.deps,
+ })(mixed.args("791"), mixed.noLogin);
+ assert.equal(mixed.asked.length, 7);
+ assert.deepEqual((res.ok ? [] : res.files ?? []).map((f) => f.name), ["791_3.jpg", "791_7.jpg"]);
+});
+
+// Review 1 M4.
+test("M4: the logged-in download is asked for only while the post is STILL kept, checked right before it", async () => {
+ const h = harness("still-kept", {});
+ const kept = new Set(["801"]);
+ const asked: string[] = [];
+ const log: string[] = [];
+ const download = createLibraryMediaDownloader({
+ channelRoot: h.root,
+ sources: new Map(),
+ expected: new Map([["801", 1], ["802", 1]]),
+ maxVideoBytes: null,
+ fallback: "login",
+ mayLogin: async (id) => (asked.push(id), kept.has(id)),
+ deps: h.deps,
+ });
+ let logins = 0;
+ const login = async ({ id, dir }: PostMediaDownloadArgs): Promise<PostMediaDownload> => {
+ logins++;
+ const { writeFileSync } = await import("node:fs");
+ writeFileSync(path.join(dir, `${id}_1.jpg`), "VIA-LOGIN");
+ return { ok: true, files: [{ name: `${id}_1.jpg` }] };
+ };
+ assert.equal((await download(h.args("801"), login)).ok, true);
+ // 802 was kept when the job was queued and dropped since: no login for it.
+ const dropped = await download({ ...h.args("802"), onLog: (l) => void log.push(l) }, login);
+ assert.equal(logins, 1);
+ assert.deepEqual(asked, ["801", "802"]);
+ assert.equal(dropped.ok, false);
+ if (!dropped.ok) {
+ assert.equal(dropped.owed, "kept");
+ assert.match(dropped.error, /802: no longer marked keep: the logged-in download is not run for it/);
+ }
+ assert.ok(log.includes("802: no longer marked keep: the logged-in download is not run for it."));
+ assert.deepEqual(readdirSync(h.dirOf("802")), []);
+});
diff --git a/common/social/xTrendingMedia.ts b/common/social/xTrendingMedia.ts
@@ -22,7 +22,10 @@
// default; a kept post has no cap);
// - a 429 from the CDN STOPS THE JOB and records the 15-minute cooldown; a
// 403, a 404 or any other answer marks that file and moves on. NOTHING IS
-// RETRIED.
+// RETRIED;
+// - THREE REFUSALS IN A ROW (a 403, or no answer at all) and the job asks
+// the CDN for nothing more: a CDN that has turned this client away is not
+// asked forty times. The rest is owed to a later capture.
//
// A FILE THE LIBRARY ALREADY HOLDS IS NOT FETCHED: one whose address the media
// index knows is linked from the store (lib/xTrending/mediaStore.ts), and one
@@ -75,7 +78,9 @@ export type MediaFetch = (
) => Promise<{
status: number;
headers: { get: (name: string) => string | null };
- body: AsyncIterable<Uint8Array> | null;
+ // `cancel`, when the body has one (a web stream does), ends a download
+ // nobody is going to read.
+ body: (AsyncIterable<Uint8Array> & { cancel?: () => Promise<void> | void }) | null;
}>;
export type LibraryMediaDeps = {
@@ -87,6 +92,8 @@ export type LibraryMediaDeps = {
cooldownMs: () => Promise<number>;
noteRateLimit: () => Promise<number>;
now?: () => number;
+ // For tests: the wait for an answer's headers, and for a whole file.
+ timeouts?: { headersMs?: number; fileMs?: number };
};
export type LibraryMediaOptions = {
@@ -100,6 +107,10 @@ export type LibraryMediaOptions = {
// A file over this is owed, not kept. null: no cap (a kept post).
maxVideoBytes: number | null;
fallback: "login" | "none";
+ // Asked IMMEDIATELY BEFORE each logged-in download (review 1 M4): whether
+ // this post is still marked keep. A post dropped since the job was queued
+ // gets none. Absent: the fallback is as `fallback` says.
+ mayLogin?: (id: string) => Promise<boolean>;
maxFiles?: number;
maxBytes?: number;
deps: LibraryMediaDeps;
@@ -111,7 +122,12 @@ const firstLine = (err: unknown) => ((err as Error)?.message ?? String(err)).spl
const overCapWhy = (bytes: number, cap: number) =>
`it is ${bytes > cap + 1 ? `${mb(bytes)}, ` : ""}over the ${mb(cap)} cap: owed until the post is kept`;
-type Fetched = { ok: true; bytes: number } | { ok: false; why: string; oversize?: number; rateLimited?: boolean };
+// `refused`: the CDN said 403, or did not answer at all — what a CDN that has
+// turned this client away looks like.
+type Fetched = { ok: true; bytes: number } | { ok: false; why: string; oversize?: number; rateLimited?: boolean; refused?: boolean };
+
+// A job stops asking the CDN after this many refusals in a row (review 1 S9).
+export const LIBRARY_MEDIA_MAX_REFUSALS = 3;
// One file, streamed to `<name>.part` and renamed when whole.
async function fetchOne(o: {
@@ -121,29 +137,54 @@ async function fetchOne(o: {
capIsHard: boolean;
fetch: MediaFetch;
signal: AbortSignal;
+ headersMs: number;
+ fileMs: number;
}): Promise<Fetched> {
const part = `${o.file}.part`;
const over = (bytes: number): Fetched =>
o.capIsHard
? { ok: false, why: `it is larger than ${mb(o.cap)}, more than is ever kept` }
: { ok: false, oversize: bytes > 0 ? bytes : o.cap + 1, why: overCapWhy(bytes, o.cap) };
- const deadline = AbortSignal.any([o.signal, AbortSignal.timeout(LIBRARY_MEDIA_FILE_TIMEOUT_MS)]);
+ const deadline = AbortSignal.any([o.signal, AbortSignal.timeout(o.fileMs)]);
+ // THE WAIT FOR THE HEADERS IS ITS OWN TIMER, CLEARED WHEN THEY ARRIVE
+ // (review 1 S3): the signal handed to fetch also aborts the body, so a timer
+ // left running there would cut every download at the headers' limit and the
+ // file's own limit would never be reached.
+ const headers = new AbortController();
+ const headersTimer = setTimeout(() => headers.abort(new Error("no answer in time")), o.headersMs);
let res: Awaited<ReturnType<MediaFetch>>;
try {
res = await o.fetch(o.source.fetchUrl, {
- signal: AbortSignal.any([deadline, AbortSignal.timeout(LIBRARY_MEDIA_HEADERS_TIMEOUT_MS)]),
+ signal: AbortSignal.any([deadline, headers.signal]),
redirect: "error",
credentials: "omit",
});
} catch (err) {
- return { ok: false, why: `the CDN did not answer (${firstLine(err)})` };
+ return { ok: false, refused: !o.signal.aborted, why: `the CDN did not answer (${firstLine(err)})` };
+ } finally {
+ clearTimeout(headersTimer);
+ }
+ // A body nobody will read is ended, not left to download.
+ const drop = async () => {
+ try {
+ await res.body?.cancel?.();
+ } catch {
+ /* already ended */
+ }
+ };
+ if (res.status === 429) {
+ await drop();
+ return { ok: false, rateLimited: true, why: "the CDN answered 429 (rate limit)" };
}
- if (res.status === 429) return { ok: false, rateLimited: true, why: "the CDN answered 429 (rate limit)" };
if (res.status < 200 || res.status >= 300 || !res.body) {
- return { ok: false, why: `the CDN answered ${res.status}` };
+ await drop();
+ return { ok: false, refused: res.status === 403, why: `the CDN answered ${res.status}` };
}
const declared = Number(res.headers.get("content-length") ?? "");
- if (Number.isFinite(declared) && declared > o.cap) return over(declared);
+ if (Number.isFinite(declared) && declared > o.cap) {
+ await drop();
+ return over(declared);
+ }
await rm(part, { force: true });
const out = createWriteStream(part);
let bytes = 0;
@@ -161,10 +202,11 @@ async function fetchOne(o: {
} catch (err) {
out.destroy();
await rm(part, { force: true });
- return { ok: false, why: `the download broke off (${firstLine(err)})` };
+ return { ok: false, refused: !o.signal.aborted, why: `the download broke off (${firstLine(err)})` };
}
await new Promise<void>((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve())));
if (tooBig) {
+ await drop();
await rm(part, { force: true });
return over(0);
}
@@ -189,6 +231,12 @@ export function createLibraryMediaDownloader(
const capIsHard = o.maxVideoBytes === null || o.maxVideoBytes >= LIBRARY_MEDIA_HARD_MAX_BYTES;
const budget = { files: 0, bytes: 0 };
let saidSpent = false;
+ // Refusals in a row, across the job's posts; and whether the job has
+ // stopped asking the CDN for it.
+ let refusals = 0;
+ let halted = false;
+ const headersMs = deps.timeouts?.headersMs ?? LIBRARY_MEDIA_HEADERS_TIMEOUT_MS;
+ const fileMs = deps.timeouts?.fileMs ?? LIBRARY_MEDIA_FILE_TIMEOUT_MS;
return async (args, login) => {
const { id, dir, signal } = args;
@@ -245,6 +293,12 @@ export function createLibraryMediaDownloader(
problems.push(`${name}: ${overCapWhy(big.bytes, cap)}`);
continue;
}
+ // The CDN has refused this job three times running: it is not asked again.
+ if (halted) {
+ owedNext = true;
+ problems.push(`${name}: owed (the CDN refused ${LIBRARY_MEDIA_MAX_REFUSALS} files in a row; this job asks it no more)`);
+ continue;
+ }
if (budget.files >= maxFiles || budget.bytes >= maxBytes) {
owedNext = true;
problems.push(`${name}: owed (this job's media budget of ${maxFiles} files / ${mb(maxBytes)} is used)`);
@@ -256,8 +310,16 @@ export function createLibraryMediaDownloader(
}
if (budget.files > 0) await deps.pause(deps.pauseMs(), signal);
if (signal.aborted) break;
- const got = await fetchOne({ source, file, cap, capIsHard, fetch: deps.fetch, signal });
+ const got = await fetchOne({ source, file, cap, capIsHard, fetch: deps.fetch, signal, headersMs, fileMs });
budget.files++;
+ refusals = !got.ok && got.refused ? refusals + 1 : 0;
+ if (refusals >= LIBRARY_MEDIA_MAX_REFUSALS && !halted) {
+ halted = true;
+ log(
+ `X's media CDN refused ${LIBRARY_MEDIA_MAX_REFUSALS} files in a row (a 403, or no answer): this job asks it for no more. ` +
+ "What is left is owed to a later capture; nothing retries by itself.",
+ );
+ }
if (got.ok) {
budget.bytes += got.bytes;
await adopt(name, source.url);
@@ -293,6 +355,12 @@ export function createLibraryMediaDownloader(
// A kept post the CDN could not serve whole: the fetcher's own logged-in
// download, once, and what it lands is taken into the store.
if (failed && !stop && o.fallback === "login") {
+ // Still kept? Asked now, not when the job was queued (review 1 M4).
+ if (o.mayLogin && !(await o.mayLogin(id).catch(() => false))) {
+ const why = `${id}: no longer marked keep: the logged-in download is not run for it`;
+ log(`${why}.`);
+ return { ok: false, owed: "kept", error: [...problems, why].join("; "), files };
+ }
log(`${id}: ${problems.join("; ")} — falling back to the logged-in download.`);
const viaLogin = await login(args);
for (const name of await listCapturedMediaFiles(dir)) {
diff --git a/common/social/xTrendingRead.test.ts b/common/social/xTrendingRead.test.ts
@@ -509,6 +509,7 @@ test("kill ends the browser's own process when its pid checks out; else it says
onLog: (l) => log.push(l),
killDeps: {
platform: "linux",
+ hostname: "host",
readlink: async (file) => {
assert.equal(file, path.join(profileDir, "SingletonLock"));
return "host-31337";
@@ -533,7 +534,7 @@ test("kill ends the browser's own process when its pid checks out; else it says
const stale = await openXTrendingPage(paths("stale"), {
chromium: other.chromium,
onLog: (l) => log2.push(l),
- killDeps: { platform: "linux", readlink: async () => "host-31337", cmdline: async () => "bash\0", kill: (pid, signal) => void sent.push([pid, signal]) },
+ killDeps: { platform: "linux", hostname: "host", readlink: async () => "host-31337", cmdline: async () => "bash\0", kill: (pid, signal) => void sent.push([pid, signal]) },
});
await stale.kill!();
assert.equal(sent.length, 1);
diff --git a/editor/app/api/ops/capture-posts/route.ts b/editor/app/api/ops/capture-posts/route.ts
@@ -59,8 +59,12 @@ export const dynamic = "force-dynamic";
// 429 from the CDN stops the job and leaves X alone for 15 minutes; a 403 or a
// 404 marks the file; nothing retries. `keptMedia: true` is for posts marked
// keep (refused for any other id): no per-file cap, and a post the CDN cannot
-// serve whole is downloaded the logged-in way. `judge-trending` runs it for
-// the posts it marks keep.
+// serve whole is downloaded the logged-in way — asked again of the judgements
+// immediately before each such download, so a post dropped since the job was
+// queued gets none. `judge-trending` runs it for the posts it marks keep. A
+// library's capture runs on X's queue only: `queueKey` is refused for it. Three
+// refusals in a row from the CDN (a 403, or no answer) and the job asks it for
+// no more; the rest is owed.
export async function POST(request: Request) {
return ops(
request,
diff --git a/editor/app/api/ops/judge-trending/route.test.ts b/editor/app/api/ops/judge-trending/route.test.ts
@@ -142,6 +142,12 @@ test("capture-posts keptMedia is for a library's kept posts only", async () => {
assert.match(String(notKept.json.error), new RegExp(`not kept: ${A}`));
const notLibrary = await ask({ slug: "account-x", ids: ["1"], keptMedia: true });
assert.equal(notLibrary.status, 400);
+ // Review 1 S5: a library's capture runs on X's queue only.
+ for (const queueKey of ["", "side-queue"]) {
+ const moved = await ask({ slug: "trending", ids: [B], queueKey });
+ assert.equal(moved.status, 400);
+ assert.match(String(moved.json.error), /is an X trending library: its captures run on X's queue only \("queueKey" is refused\)/);
+ }
// An id that is not the library's is refused as stray before anything else.
assert.match(String((await ask({ slug: "trending", ids: ["42"], keptMedia: true })).json.error), /not in trending's posts archive/);
});
diff --git a/editor/app/api/ops/judge-trending/route.ts b/editor/app/api/ops/judge-trending/route.ts
@@ -19,9 +19,14 @@ export const dynamic = "force-dynamic";
// entry is undecided)
// note up to 2000 characters, kept with the judgement
// by "agent" (the default here) or "operator" (the channel page's
-// buttons). AN AGENT'S JUDGEMENT IS A SUGGESTION: an agent's write
-// over a judgement the operator made is skipped for that id and
-// named in `skipped`; the rest of the ask is written.
+// buttons). IT IS THE CALLER'S WORD: this route cannot tell who is
+// asking, so an agent is trusted to say "agent" (the operator's
+// hand is the page's buttons, and slice 3's judge view).
+// AN AGENT'S JUDGEMENT IS A SUGGESTION: an agent's write over a
+// judgement the operator made is skipped for that id and named in
+// `skipped`; the rest of the ask is written. A post the operator
+// judged through its THREAD is the operator's too: an agent's
+// post-level write for it is skipped.
//
// `kept` names the posts whose judgement BECAME keep by this ask (their own,
// or their thread's). A KEEP ARCHIVES THEM: one `capture-posts` job on X's
diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts
@@ -405,6 +405,12 @@ export async function capturePostsAction(
: await readSeenPostIds(path.join(paths.channelsDir, slug)),
);
if (stray) return { ok: false, error: strayIdsRefusal(slug, stray) };
+ // A LIBRARY'S CAPTURE STAYS ON X'S QUEUE (review 1 S5): its media half is
+ // paced against every other X job there, and the watch counts on one
+ // stream. No queue override, named or immediate.
+ if (library && queueKey !== undefined) {
+ return { ok: false, error: `${slug} is an X trending library: its captures run on X's queue only ("queueKey" is refused).` };
+ }
if (keptMedia) {
if (!library) return { ok: false, error: `"keptMedia" is for an X trending library's kept posts; ${slug} is not a library.` };
const kept = await readXTrendingKeptIds(path.join(paths.channelsDir, slug));
@@ -460,6 +466,14 @@ export async function capturePostsAction(
? {
libraryMedia: {
fallback: keptMedia && !testServer ? ("login" as const) : ("none" as const),
+ // KEPT WHEN QUEUED IS NOT KEPT NOW (review 1 M4): the job may
+ // start minutes later (X's gap, a queue), and the operator
+ // may have dropped a post meanwhile. The judgements are read
+ // again immediately before each logged-in download, and a
+ // post no longer kept gets none.
+ ...(keptMedia
+ ? { mayLogin: async (id: string) => (await readXTrendingKeptIds(path.join(paths.channelsDir, slug))).has(id) }
+ : {}),
...(keptMedia ? { maxVideoBytes: null } : {}),
...(fakeFetch ? { deps: { fetch: fakeFetch, pauseMs: () => 20 } } : {}),
},