// INSTAGRAM THROUGH THE REAL JOB FUNNEL (runManagedFunction), the real fetch // controller and the real fetcher, against a fake gallery-dl written here (no // request leaves the machine; the media CDN is an injected function): // - a channel with no cookie source of its own is refused and gallery-dl // never runs; // - a challenge in job 1 fails job 1, raises Instagram's alert, and refuses // every later Instagram job unrun, until a person's Recheck; // - the first 429 ends the run, keeps what it read, and holds Instagram for // an hour: the jobs behind it are refused unrun; // - clean jobs start at least pacing.jobGapSeconds.instagram (600 s) apart, // write their posts and fetch their media in the same job, and say what // the run cost; // - a run past its request cap is stopped with SIGINT and keeps what // gallery-dl then prints. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/instagramPacing.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; const ROOT = await mkdtemp(path.join(os.tmpdir(), "instagram-pacing-")); const BIN = path.join(ROOT, "fake-gallery-dl.mjs"); const RUNS = path.join(ROOT, "runs.log"); process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.GALLERY_DL_BIN = BIN; process.env.FAKE_RUNS = RUNS; delete process.env.E2E_JOB_GAP_SECONDS; delete process.env.E2E_TEST_ROUTES; // What gallery-dl prints for Instagram with --dump-json --verbose: request // lines and cursors on stderr, ONE array on stdout at exit — the exception as // its last row — and exit 0 whatever happened. SIGINT: it prints what it has. await writeFile( BIN, `#!/usr/bin/env node import { appendFileSync } from "node:fs"; const args = process.argv.slice(2); appendFileSync(process.env.FAKE_RUNS, args.join(" ") + "\\n"); const mode = process.env.FAKE_MODE ?? "clean"; const handle = /instagram\\.com\\/([^/]+)\\/posts/.exec(args.at(-1))?.[1] ?? "nobody"; const rows = []; const req = (p, s = 200) => process.stderr.write('[urllib3.connectionpool][debug] https://www.instagram.com:443 "GET ' + p + ' HTTP/1.1" ' + s + ' None\\n'); const feed = "/api/v1/feed/user/4000000001/?count=30"; const post = (n, media) => { const pk = (3500000000000000000n + BigInt(n)).toString(); const p = { post_id: pk, post_shortcode: "Code" + n, type: media[0] === "video" && media.length === 1 ? "reel" : "post", username: handle, fullname: "Example Account", description: "post " + n + " of " + handle, post_date: "2026-03-" + String(n).padStart(2, "0") + " 10:00:00", pinned: [], count: media.length, likes: n }; rows.push([2, p]); media.forEach((kind, i) => { const ext = kind === "video" ? "mp4" : "jpg"; const url = "https://scontent-invented.cdninstagram.com/" + handle + "/" + n + "-" + (i + 1) + "." + ext + "?sig=invented"; rows.push([3, url, { ...p, num: i + 1, media_id: String(BigInt(pk) * 10n + BigInt(i + 1)), video_url: kind === "video" ? url : null, display_url: url, extension: ext }]); }); }; const dump = () => { process.stdout.write(JSON.stringify(rows, null, 2) + "\\n"); process.exit(0); }; process.on("SIGINT", dump); req("/web/search/topsearch/?query=" + handle); if (mode === "challenge") { // Instagram answers after a moment: the loop has queued every job by then. await new Promise((r) => setTimeout(r, 1500)); req(feed, 302); rows.push([-1, { error: "AbortExtraction", message: "HTTP redirect to challenge page (https://www.instagram.com/challenge/)" }]); dump(); } if (mode === "ratelimit") { await new Promise((r) => setTimeout(r, 1500)); req(feed); post(9, ["image"]); process.stderr.write("[instagram][debug] Cursor: page-2\\n"); req(feed + "&max_id=page-2", 429); rows.push([-1, { error: "HttpError", message: "'429 Too Many Requests' for 'https://www.instagram.com" + feed + "&max_id=page-2'" }]); dump(); } if (mode === "endless") { // Pages of one post, for ever: only the request cap ends this. let n = 1; const t = setInterval(() => { req(feed); post(n++, ["image"]); process.stderr.write("[instagram][debug] Cursor: page-" + n + "\\n"); }, 40); setTimeout(() => { clearInterval(t); process.exit(3); }, 30_000); await new Promise(() => {}); } req(feed); post(3, ["image", "video"]); post(2, ["video"]); post(1, ["image"]); dump(); `, ); await chmod(BIN, 0o755); await writeFile(process.env.SETTINGS_FILE, JSON.stringify({})); const transcripts = path.join(ROOT, "transcripts"); const SLUGS = Array.from({ length: 5 }, (_, i) => `ig-acct-${i + 1}`); async function makeChannel(slug: string, cookies: string | null): Promise { const dir = path.join(transcripts, "channels", slug); await rm(dir, { recursive: true, force: true }); await mkdir(dir, { recursive: true }); await writeFile( path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", postFetcher: "instagram-gallery-dl", socialHandle: `example.${slug}`, platform: "instagram", name: slug, url: `https://www.instagram.com/example.${slug}/`, ...(cookies ? { cookiesFromBrowser: cookies } : {}), }), ); } const { getPaths } = await import("../lib/paths"); const { runManagedFunction } = await import("./streamCommand"); const { fetchPosts, fetcherPlatformMismatch, INSTAGRAM_ONLY_AS_A_JOB, INSTAGRAM_RETRY_REFUSAL } = await import("../controller/fetchPosts"); const { runInJobContext } = await import("../lib/jobContext"); const { instagramQueueProblem } = await import("../lib/instagram/channel"); const { capturePosts } = await import("../controller/capturePosts"); const { checkPostAvailability, INSTAGRAM_NO_AVAILABILITY_CHECK } = await import("../controller/checkPostAvailability"); const { getSettings } = await import("../lib/settings"); const { setQueueGapClock, clearQueueGaps } = await import("./queueGap"); const { readServiceCookieState, serviceCookiesFile } = await import("../lib/serviceCookies-server"); const { recheckServiceCookies } = await import("../controller/recheckServiceCookies"); const { readAllPosts, readPostFetchState } = await import("../lib/posts-server"); const { platformCooldownRemainingMs, clearPlatformHold } = await import("./downloadBackoff"); const { readChannelConfig } = await import("../controller/channels"); const paths = getPaths(); let fakeNow = Date.parse("2026-03-10T03:00:00Z"); setQueueGapClock({ now: () => fakeNow, sleep: async (ms) => { fakeNow += ms; }, }); // The media CDN, invented: every address answers a few bytes naming it. const cdn: string[] = []; const instagramMedia = { fetch: async (url: string) => { cdn.push(url); const bytes = new TextEncoder().encode(`media ${url}`); return { status: 200, headers: { get: () => String(bytes.length) }, body: (async function* () { yield bytes; })(), }; }, pause: async () => {}, pauseMs: () => 3000, }; async function fetchJob(slug: string, starts: Map, extra: Record = {}, queueKey = "platform:instagram") { return runManagedFunction({ kind: "fetch-posts", queueKey, paths, channelSlug: slug, fn: async (onLog, signal) => { starts.set(slug, fakeNow); const result = await fetchPosts({ paths, slug, settings: getSettings(), onLog, signal, instagramMedia, ...extra }); if (!result.ok) throw new Error(result.error ?? "Post fetch failed"); fakeNow += 3_000; }, }); } async function runCount(): Promise { try { return (await readFile(RUNS, "utf8")).split("\n").filter(Boolean).length; } catch { return 0; } } // EVERY JOB'S END ASKS FOR ITS CHANNEL'S REPORT (jobs/snapshotScheduler.ts): // a refresh-report a second later, which writes into the channel's dir. Left // alone it lands in the next test's reset — or the final cleanup — while that // removes the dir: ENOTEMPTY under a loaded run. Before either, the pending // regeneration is dropped and any one already started is waited out. const { resetSnapshotScheduler } = await import("./snapshotScheduler"); const { getRegistry } = await import("./registry"); async function settleReports(): Promise { resetSnapshotScheduler(); const busy = () => getRegistry().list().some((j) => j.kind === "refresh-report" && (j.status === "queued" || j.status === "running")); for (let i = 0; i < 400 && busy(); i += 1) await new Promise((r) => setTimeout(r, 25)); assert.equal(busy(), false, "a channel report still regenerating after 10 s"); } async function reset(cookies: string | null = "firefox:ig-profile"): Promise { await settleReports(); clearQueueGaps(); cdn.length = 0; await rm(RUNS, { force: true }); await rm(serviceCookiesFile(paths), { force: true }); await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true }); for (const slug of SLUGS) await makeChannel(slug, cookies); } async function readLog(jobId: string): Promise { return readFile(path.join(paths.jobsDir, `${jobId}.log`), "utf8"); } test.after(async () => { await settleReports(); await rm(ROOT, { recursive: true, force: true }); }); test("a channel with no cookie source of its own is refused, and gallery-dl never runs — the global browser is not borrowed", async () => { await reset(null); await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ cookiesFromBrowser: "firefox", cookieMode: "always" })); try { const r = await fetchPosts({ paths, slug: SLUGS[0], settings: { cookiesFromBrowser: "firefox", cookieMode: "always" } }); assert.equal(r.ok, false); assert.equal(r.needsCookies, true); assert.match(r.error!, /has no cookie source of its own/); assert.match(r.error!, /Set "Cookies from browser" on the channel's Edit form/); assert.equal(await runCount(), 0); // Retry on a block is refused by name, before anything else is asked. await makeChannel(SLUGS[0], "firefox:ig-profile"); const retry = await fetchPosts({ paths, slug: SLUGS[0], settings: {}, retryOnBlock: { minutes: 30, max: 3 } }); assert.deepEqual([retry.ok, retry.error], [false, INSTAGRAM_RETRY_REFUSAL]); assert.equal(await runCount(), 0); // NOT AS A JOB: a direct call (the CLI's) is refused with where to ask instead, and nothing runs. const direct = await fetchPosts({ paths, slug: SLUGS[0], settings: {} }); assert.deepEqual([direct.ok, direct.error], [false, INSTAGRAM_ONLY_AS_A_JOB(SLUGS[0])]); assert.match(direct.error!, /pnpm ops fetch-posts --json '\{"slug":"ig-acct-1"\}' --wait/); assert.equal(await runCount(), 0); // A fetcher of another platform on an Instagram channel (and the other way round) is refused: it would run past the guard. const dir = path.join(transcripts, "channels", SLUGS[0], "config.json"); const config = JSON.parse(await readFile(dir, "utf8")); await writeFile(dir, JSON.stringify({ ...config, postFetcher: "x-gallery-dl" })); const crossed = await fetchPosts({ paths, slug: SLUGS[0], settings: {} }); assert.equal(crossed.ok, false); assert.match(crossed.error!, /ig-acct-1 is on instagram, and its fetcher \(X \/ Twitter \(gallery-dl\), "x-gallery-dl"\) is twitter's: nothing was asked/); await writeFile(dir, JSON.stringify({ ...config, platform: "twitter", url: "https://x.com/example", postFetcher: "instagram-gallery-dl" })); assert.match((await fetchPosts({ paths, slug: SLUGS[0], settings: {} })).error!, /is on twitter, and its fetcher \(Instagram \(gallery-dl\)/); assert.equal(await runCount(), 0); await writeFile(dir, JSON.stringify(config)); assert.equal(fetcherPlatformMismatch("x", { platform: "twitter" }, { platform: "twitter", label: "X", id: "x-gallery-dl" }), null); assert.equal(fetcherPlatformMismatch("x", { url: "https://x.com/example" }, { platform: "twitter", label: "X", id: "x-nitter" }), null); assert.equal(fetcherPlatformMismatch("x", {}, { platform: "bluesky", label: "B", id: "b" }), null, "a channel that names no platform is not judged"); // BOTH SIGNS (review 2, N5): the config says X, the URL is Instagram's — X's fetcher is not handed it. await writeFile(dir, JSON.stringify({ ...config, platform: "twitter", postFetcher: "x-gallery-dl" })); const lied = await fetchPosts({ paths, slug: SLUGS[0], settings: {} }); assert.equal(lied.ok, false); assert.match(lied.error!, /ig-acct-1 is on instagram \(its URL's host\), and its fetcher \(X \/ Twitter \(gallery-dl\), "x-gallery-dl"\) is twitter's: nothing was asked/); assert.equal(await runCount(), 0); await writeFile(dir, JSON.stringify(config)); const X = { platform: "twitter", label: "X", id: "x-gallery-dl" }; assert.match(fetcherPlatformMismatch("c", { platform: "twitter", url: "https://www.instagram.com/example.account/" }, X) ?? "", /is on instagram \(its URL's host\)/); assert.match(fetcherPlatformMismatch("c", { url: "https://x.com/example" }, { platform: "instagram", label: "I", id: "instagram-gallery-dl" }) ?? "", /is on twitter/); // The legitimate shapes are what they were: a Nitter instance's URL, an X search, a bare Bluesky handle, // a forum told by its platform alone, no platform at all. assert.equal(fetcherPlatformMismatch("c", { platform: "twitter", url: "https://nitter.example.invalid/example" }, { ...X, id: "x-nitter" }), null); assert.equal(fetcherPlatformMismatch("c", { platform: "twitter", url: "https://x.com/search?q=%22demo%22" }, X), null); assert.equal(fetcherPlatformMismatch("c", { platform: "twitter", url: "https://twitter.com/example" }, X), null); assert.equal(fetcherPlatformMismatch("c", { platform: "bluesky", url: "example.bsky.social" }, { platform: "bluesky", label: "B", id: "bluesky-atproto" }), null); assert.equal(fetcherPlatformMismatch("c", { platform: "bluesky", url: "https://bsky.app/profile/example.bsky.social" }, { platform: "bluesky", label: "B", id: "bluesky-atproto" }), null); assert.equal(fetcherPlatformMismatch("c", { platform: "xenforo", url: "https://forum.example.invalid/community/topic-1/" }, { platform: "xenforo", label: "F", id: "xenforo-thread" }), null); assert.equal(fetcherPlatformMismatch("c", { url: "https://unknown.example.invalid/someone" }, X), null); assert.equal(fetcherPlatformMismatch("c", { platform: "instagram", url: "https://www.instagram.com/example.account/" }, { platform: "instagram", label: "I", id: "instagram-gallery-dl" }), null); // The deleted-posts sweep says it is not built for Instagram, and asks nothing. const sweep = await checkPostAvailability({ paths, slug: SLUGS[0] }); assert.deepEqual([sweep.ok, sweep.error], [false, INSTAGRAM_NO_AVAILABILITY_CHECK]); assert.equal(await runCount(), 0); // capture-posts takes no screenshot of an Instagram post and asks nothing. const cap = await capturePosts({ paths, slug: SLUGS[0], settings: {}, ids: ["3500000000000000001"] } as never); assert.equal(cap.ok, false); assert.match(cap.error!, /takes no screenshot of an Instagram post/); assert.equal(await runCount(), 0); } finally { await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({})); } }); test("5 Instagram fetches, job 1 meets a challenge: job 1 fails, the alert is up, jobs 2-5 are refused unrun until a person's Recheck", async () => { await reset(); process.env.FAKE_MODE = "challenge"; try { const starts = new Map(); const started = []; for (const slug of SLUGS) { const res = await fetchJob(slug, starts); assert.equal(res.ok, true, res.ok ? "" : res.error); if (res.ok) started.push(res); } const ends = await Promise.all(started.map((r) => r.done)); assert.deepEqual(ends.map((e) => e.status), Array(5).fill("failed")); assert.equal(await runCount(), 1, "gallery-dl ran once: only job 1 asked Instagram"); assert.deepEqual([...starts.keys()], [SLUGS[0]]); const first = await readLog(ends[0]!.jobId); assert.match(first, /Instagram answered with a challenge or checkpoint page/); assert.match(first, /Cost: 2 request\(s\) to Instagram/); const second = await readLog(ends[1]!.jobId); assert.match(second, /its alert is up, so no Instagram job starts/); const ig = (await readServiceCookieState(paths)).services.instagram; assert.ok(ig?.raisedAt && !ig.clearedAt); assert.equal(ig.kind, "challenge"); assert.equal(ig.jobs.length, 5); // A sixth is refused at enqueue: no job at all. const again = await fetchJob(SLUGS[0], new Map()); assert.equal(again.ok, false); assert.match(again.ok ? "" : again.error, /its alert is up/); // The run with the gallery-dl that would now answer cleanly is still refused: nothing probes by itself. process.env.FAKE_MODE = "clean"; assert.equal((await fetchJob(SLUGS[1], new Map())).ok, false); assert.equal(await runCount(), 1); // fetchPosts asks the guard itself, whoever calls it inside a job: the funnel's start check is not the only one. const inside = await runInJobContext( { jobId: "by-hand", kind: "fetch-posts", queueKey: "platform:instagram", onLog: () => {}, staleServices: new Set() }, () => fetchPosts({ paths, slug: SLUGS[2], settings: {}, instagramMedia }), ); assert.equal(inside.ok, false); assert.match(inside.error!, /its alert is up, so no Instagram job starts/); assert.equal(await runCount(), 1); // The operator's Recheck (no request) clears it, and a fetch runs. await recheckServiceCookies({ paths, service: "instagram" }); const after = await fetchJob(SLUGS[1], new Map()); assert.equal(after.ok, true); if (after.ok) assert.equal((await after.done).status, "done"); assert.equal(await runCount(), 2); } finally { delete process.env.FAKE_MODE; } }); test("the first 429 ends the run and holds Instagram for an hour: what was read is kept, the jobs behind it are refused unrun", async () => { await reset(); process.env.FAKE_MODE = "ratelimit"; try { const starts = new Map(); const started = []; for (const slug of SLUGS.slice(0, 3)) { const res = await fetchJob(slug, starts); assert.equal(res.ok, true, res.ok ? "" : res.error); if (res.ok) started.push(res); } const ends = await Promise.all(started.map((r) => r.done)); assert.deepEqual(ends.map((e) => e.status), ["failed", "failed", "failed"]); assert.equal(await runCount(), 1); const first = await readLog(ends[0]!.jobId); assert.match(first, /Instagram refused the read \(GET \/api\/v1\/feed\/user\/\d+\/ answered 429\): a rate limit/); assert.match(first, /Nothing retries by itself/); assert.match(await readLog(ends[1]!.jobId), /Instagram answered a rate limit a short while ago: no Instagram job starts before/); const left = await platformCooldownRemainingMs("instagram", paths); assert.ok(left > 58 * 60_000 && left <= 60 * 60_000, `cooldown ${left}`); // The post it read before the 429 is archived with the resume point — and NO media is asked for: // after a refusal everything Instagram stops, its CDN too. Its record says the media are owed. const root = path.join(paths.channelsDir, SLUGS[0]); assert.deepEqual((await readAllPosts(root)).map((p) => p.id), ["3500000000000000009"]); assert.equal((await readPostFetchState(root))?.backfill?.cursor, "page-2"); assert.equal(cdn.length, 0); const owed = JSON.parse(await readFile(path.join(root, "posts-media", "3500000000000000009", "capture.json"), "utf8")); assert.deepEqual([owed.mediaState, owed.mediaOwed, owed.media.length], ["error", "next", 0]); assert.match(first, /Media: none asked for\. Instagram refused the listing, so its CDN is not asked either; 1 post\(s\) are archived with their media owed/); assert.match(first, /This run cost Instagram 3 request\(s\) and its CDN 0 file\(s\)\./); // No alert: the cookies are not the fix. assert.equal((await readServiceCookieState(paths)).services.instagram, undefined); // Refused at enqueue while it cools down. assert.equal((await fetchJob(SLUGS[3], new Map())).ok, false); } finally { delete process.env.FAKE_MODE; // The cooldown is cleared by hand for the tests below (the operator's clear-platform-hold). await clearPlatformHold("instagram", paths); assert.equal(await platformCooldownRemainingMs("instagram", paths), 0); } }); test("clean fetches start at least 600 s apart, archive the posts and fetch their media in the same job, and say what the run cost", async () => { await reset(); const starts = new Map(); const started = []; for (const slug of SLUGS.slice(0, 3)) { const res = await fetchJob(slug, starts); assert.equal(res.ok, true, res.ok ? "" : res.error); if (res.ok) started.push(res); } const ends = await Promise.all(started.map((r) => r.done)); assert.deepEqual(ends.map((e) => e.status), ["done", "done", "done"]); assert.equal(await runCount(), 3); const at = SLUGS.slice(0, 3).map((s) => starts.get(s)!); for (let i = 1; i < at.length; i++) { assert.ok(at[i] - at[i - 1] >= 600_000, `job ${i + 1} started ${(at[i] - at[i - 1]) / 1000}s after job ${i}`); } assert.match(await readLog(ends[1]!.jobId), /Instagram jobs are spaced 10 min apart \(pacing\.jobGapSeconds\.instagram\)/); const slug = SLUGS[0]; const root = path.join(paths.channelsDir, slug); const posts = await readAllPosts(root); assert.deepEqual(posts.map((p) => p.id).sort(), ["3500000000000000001", "3500000000000000002", "3500000000000000003"]); const carousel = posts.find((p) => p.id === "3500000000000000003")!; assert.equal(carousel.platform, "instagram"); assert.equal(carousel.mediaCount, 2); assert.equal(carousel.instagram?.kind, "post"); assert.equal(posts.find((p) => p.id === "3500000000000000002")!.instagram?.kind, "reel"); // No signed address is stored with a post. assert.ok(!JSON.stringify(posts).includes("cdn.example.invalid")); // Its media are in posts-media//, in order, with a capture record and no screenshot. const dir = path.join(root, "posts-media", "3500000000000000003"); assert.deepEqual((await readdir(dir)).sort(), ["01-35000000000000000031.jpg", "02-35000000000000000032.mp4", "capture.json"]); const record = JSON.parse(await readFile(path.join(dir, "capture.json"), "utf8")); assert.equal(record.state, "captured"); assert.equal(record.mediaState, "ok"); assert.equal(record.shot, undefined); assert.equal(record.media.length, 2); assert.equal(record.url, carousel.url); // One GET per file, with no cookies asked of anything: 4 files a channel. assert.equal(cdn.length, 12); const log = await readLog(ends[0]!.jobId); assert.match(log, /Instagram login: the channel's own cookie source, read by gallery-dl\./); assert.ok(!log.includes("firefox:ig-profile"), "the cookie source is never printed"); assert.match(log, /Cost: 2 request\(s\) to Instagram \(1 for the account's id, 1 feed page\(s\)\)\./); assert.match(log, /Media: 4 file\(s\) fetched from its CDN/); assert.match(log, /This run cost Instagram 2 request\(s\) and its CDN 4 file\(s\)\./); // The argv: never a retry, never the operator's own gallery-dl config, the channel's cookies. const argv = (await readFile(RUNS, "utf8")).split("\n")[0]!; assert.match(argv, /--config-ignore/); assert.match(argv, /extractor\.instagram\.retries=0/); assert.match(argv, /--cookies-from-browser firefox:ig-profile/); // The first fetch walked everything there was: complete, no resume point; the channel is stamped. assert.equal((await readPostFetchState(root))?.backfill, undefined); assert.ok((await readChannelConfig(paths, slug))?.lastSyncedAt); // SYNC NEW after it: one page, everything known, nothing written, nothing fetched. cdn.length = 0; fakeNow += 3_600_000; const again = await fetchJob(slug, new Map()); assert.equal(again.ok, true); if (again.ok) { const end = await again.done; assert.equal(end.status, "done"); const l = await readLog(end.jobId); assert.match(l, /Reading one page \(up to 30 posts\) from the top/); assert.match(l, /Wrote 0 new post\(s\)/); assert.match(l, /This run cost Instagram 2 request\(s\) and its CDN 0 file\(s\)\./); } assert.equal(cdn.length, 0); }); test("a run past its request cap is stopped with an interrupt and keeps what gallery-dl then prints", async () => { await reset(); process.env.FAKE_MODE = "endless"; try { const slug = SLUGS[4]; const res = await fetchJob(slug, new Map()); assert.equal(res.ok, true); if (res.ok) assert.equal((await res.done).status, "done"); // A first fetch is a walk: 7 requests at most (the lookup and 6 pages of one post). const posts = await readAllPosts(path.join(paths.channelsDir, slug)); assert.ok(posts.length >= 6 && posts.length <= 8, `${posts.length} posts`); const state = await readPostFetchState(path.join(paths.channelsDir, slug)); assert.match(state?.backfill?.cursor ?? "", /^page-\d+$/); } finally { delete process.env.FAKE_MODE; } }); // Review 2, N1: a queue override ran an Instagram fetch beside the job on // Instagram's queue, with no gap between them. test("an Instagram fetch runs on platform:instagram and nowhere else: a job on any other queue is refused when it runs, and gallery-dl is not started", async () => { await reset(); // By the rule the action asks before a job exists… const config = (await readChannelConfig(paths, SLUGS[0]))!; assert.equal(instagramQueueProblem(SLUGS[0], config, undefined), null); assert.equal(instagramQueueProblem(SLUGS[0], config, "platform:instagram"), null); assert.equal(instagramQueueProblem(SLUGS[0], config, " platform:instagram "), null); for (const side of ["side", "", "platform:twitter", "platform:instagram.com"]) { assert.match( instagramQueueProblem(SLUGS[0], config, side) ?? "", /is an Instagram channel: its jobs run on platform:instagram and nowhere else \(one at a time, ten minutes apart\)/, side, ); } // An X channel's override is not Instagram's business. assert.equal(instagramQueueProblem("x", { sourceKind: "social", platform: "twitter", url: "https://x.com/example" }, "side"), null); // A channel that is Instagram's by its URL alone is held to it too. assert.match(instagramQueueProblem("c", { sourceKind: "social", url: "https://www.instagram.com/example.account/" }, "side") ?? "", /nowhere else/); // …and by the fetch itself, whatever queued the job: a named side queue is not the network guard's // "unqueued" case, so the job starts — and is refused before anything is asked. const starts = new Map(); const res = await fetchJob(SLUGS[0], starts, {}, "side"); assert.equal(res.ok, true, res.ok ? "" : res.error); if (res.ok) { const end = await res.done; assert.equal(end.status, "failed"); assert.match(await readLog(end.jobId), /its jobs run on platform:instagram and nowhere else .*the queue override "side" is refused/); } assert.equal(await runCount(), 0); assert.equal(cdn.length, 0); });