Archilyzer · Source

archilyzer

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

commit b672c4a9bd484de1d58dae417613065acfccab1c
parent 9951150a27479ecd2b49fa44e95aae6ef5c94722
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 16:55:28 -0500

review 2 N1-N9: an Instagram fetch runs on Instagram's queue only, and the rest of the review

N1: the action refuses any queue override but platform:instagram for an
Instagram channel; the job context carries the queue and the fetch refuses a
job on any other; a boot leaves an interrupted fetch of an Instagram channel
whatever queue it ran on. N2: a trimmed walk resumes from its own start, so no
page size is assumed. N3: the login, challenge and checkpoint walls are path
segments, never a word in a handle. N4: no request line read is a failure
whatever was printed. N5: the fetcher must match the platform of the channel's
URL as well as the one its config names. N6: a cancelled, drained, timed-out or
over-cap run is not the clean read that forgets a pending 401/403. N7: one
predicate says what an Instagram channel is, for the fetch, the action, the
scheduler and the boot. N8: the yt-dlp refusal is in the shared jitter.mjs, so
umtool's scripts are held to it, and a metadata scan leaves an instagram.com
URL out of its batch file. N9: the walk is 120 posts wherever it is said.

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

Diffstat:
MCOMMANDS.md | 2+-
MOPERATING.md | 11+++++++----
Mcommon/controller/fetchPosts.ts | 35+++++++++++++++++++++++++++++------
Mcommon/jobs/instagramPacing.test.ts | 62+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/jobs/instagramSchedule.test.ts | 16++++++++++++++++
Mcommon/jobs/resumeInterrupted.test.ts | 25+++++++++++++++++++++++++
Mcommon/jobs/resumeInterrupted.ts | 21+++++++++++++++++----
Mcommon/jobs/streamCommand.ts | 1+
Mcommon/jobs/syncScheduler.ts | 11++++++++---
Acommon/lib/instagram/channel.ts | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/instagram/ytdlp.test.ts | 31+++++++++++++++++++++++++++++++
Mcommon/lib/instagram/ytdlp.ts | 27+++------------------------
Acommon/lib/instagram/ytdlpRefusal.mjs | 45+++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/jitter.mjs | 9+++++++++
Mcommon/lib/jitter.ts | 10++++------
Mcommon/lib/jobContext.ts | 3+++
Mcommon/package.json | 1+
Mcommon/social/instagramGalleryDlFetcher.test.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/social/instagramGalleryDlFetcher.ts | 84++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mcommon/social/instagramSignals.test.ts | 41+++++++++++++++++++++++++++++++++++++++++
Mcommon/social/instagramSignals.ts | 48++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/ytdlp/metadataScan.ts | 33+++++++++++++++++++++++++++------
Meditor/CHANGELOG.md | 5+++--
Meditor/app/api/ops/fetch-posts/route.ts | 6++++--
Meditor/app/channels/[slug]/socialActions.ts | 9++++++++-
Meditor/e2e/instagram.spec.ts | 6++++++
Mplans/instagram.md | 8++++++++
Mscripts/archilyzer-ops.mjs | 3++-
Aumtool/report-to-video/instagram-ytdlp.test.mjs | 12++++++++++++
29 files changed, 585 insertions(+), 122 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -167,7 +167,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. "storedUrl": "fallback" \| "only" reads each video from the media URL its record stores when the page is rate-limited (or always), one file per 20 min; with one, a held platform's run goes ahead as "only". | | | `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | -| `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"} is SYNC NEW — from the top of the timeline down to the newest archived post (a sync that stopped part-way continues down to the watermark it began with). It never reads or clears an unfinished backfill's resume point. "backfill": true is RESUME BACKFILL instead (the same as resume-backfill). "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full", "older" and "backfill" are one at a time. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. AN INSTAGRAM CHANNEL: a sync reads ONE page (up to 30 posts), a first fetch, "full" or "backfill" walks up to 120 posts and the next run resumes; the new posts' pictures and videos are fetched in the same job (a sync 40 files / 200 MB, a walk 120 / 600 MB, 100 MB a file; a walk leaves the posts whose media would not fit for its next run; what is still not fetched is recorded as owed, and none after a refusal). Refused before a job exists when the channel has no cookiesFromBrowser of its own, and with "retryOnBlock" or "older". A login, challenge or checkpoint page raises Instagram's alert and refuses every Instagram job until recheck-service; the first 429 holds Instagram for an hour (clear-platform-hold {"platform": "instagram"} ends that by hand). A drained fetch stops at its next resume point and the next run of the same walk resumes there. | `pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait` | +| `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"} is SYNC NEW — from the top of the timeline down to the newest archived post (a sync that stopped part-way continues down to the watermark it began with). It never reads or clears an unfinished backfill's resume point. "backfill": true is RESUME BACKFILL instead (the same as resume-backfill). "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full", "older" and "backfill" are one at a time. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. AN INSTAGRAM CHANNEL: a sync reads ONE page (up to 30 posts), a first fetch, "full" or "backfill" walks up to 120 posts and the next run resumes; the new posts' pictures and videos are fetched in the same job (a sync 40 files / 200 MB, a walk 120 / 600 MB, 100 MB a file; a walk leaves the posts whose media would not fit for its next run; what is still not fetched is recorded as owed, and none after a refusal). Refused before a job exists when the channel has no cookiesFromBrowser of its own, with "retryOnBlock" or "older", and with a "queueKey" other than platform:instagram. A login, challenge or checkpoint page raises Instagram's alert and refuses every Instagram job until recheck-service; the first 429 holds Instagram for an hour (clear-platform-hold {"platform": "instagram"} ends that by hand). A drained fetch stops at its next resume point and the next run of the same walk resumes there. | `pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait` | | `resume-backfill` | resume-backfill continues a social channel's unfinished full-history timeline walk (X, Bluesky) from its saved resume point, with no watermark: {"slug"} ("limit"? caps the posts this run reads). The walk is left part-way by a first fetch, a full re-walk or a backfill that stopped; the channel page then says "backfill unfinished — N archived" and shows Resume backfill. Nothing resumes it but this (or fetch-posts "backfill": true): a plain fetch-posts, Sync and the scheduler sync new posts and keep its place. Refused when none is part-way, on a forum thread (every fetch catches up, then continues its history) and on an X search channel. | `pnpm ops resume-backfill --json '{"slug":"example-x"}' --wait` | | `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. An Instagram channel is refused: no screenshot is taken of an Instagram post, and its media come with the post, in the fetch-posts job. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"&lt;id&gt;": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/&lt;handle&gt;.&lt;ext&gt; + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["&lt;one of their post ids&gt;"\], "avatarsOnly": true}. X also reads each post's CONTEXT off the same page -- the post it quotes and the post it answers (its author, check, date, words, media links) -- into its capture.json's "context"; "context": false turns that off. "contextOnly": true (X) loads ONE page per post for that alone (and the avatars it shows): the context written into capture.json, nothing shot, no media, article, thread shot or availability; a post whose context is already read is skipped unless "force". Not with "avatarsOnly". Paced like a post fetch, on its queue. An X trending library is captured by this same job, under channels/&lt;slug&gt;/trending/posts-media/&lt;id&gt;/. Its media comes from X's media CDN by the addresses in the library's saved captures: no login, one file after another 1-2 s apart, under X's cooldown, each file kept once (trending/media-store/, a hardlink per post). A file over the library's maxVideoMb (100 MB) and whatever is past the job's budget (40 files / 200 MB) is owed: asked for again by the next capture of that post. A 429 from the CDN stops the job and leaves X alone for 15 minutes; a 403 or 404 marks the file; three refusals in a row (a 403, or no answer) and the job asks the CDN no more; 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, if it is still kept when that download would start. A library's capture runs on X's queue only: "queueKey" is refused for it. | | | `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "&lt;branch&gt;", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of &lt;id&gt; in &lt;dir&gt; — archilyzer publish build &lt;id&gt;". `get publish` is the status. | | diff --git a/OPERATING.md b/OPERATING.md @@ -628,7 +628,7 @@ pnpm ops settings --json '{"patch":{"social":{"instagram":{"visibility":"p `channels/<slug>/posts-media/<post id>/` beside a `capture.json`. A sync may fetch 40 files or 200 MB, a walk 120 files or 600 MB, a file at most 100 MB; the media half has 20 minutes and a file 5. **A walk is sized to its media**: it lists as many posts as its budget has files, and the posts whose media - would not fit are left for the next run, which lists them again. So a post a run archives has its media asked + would not fit are left for the next run, which starts where this one did and lists them again. So a post a run archives has its media asked for in that run. What was still not fetched (a file over the cap, a CDN refusal, a drain) is recorded as owed (`mediaOwed`) and the log says how many posts; nothing collects owed media yet. Three CDN refusals in a row end the media half. `posts-media/` is not in the media tier: it stays on the corpus disk. @@ -639,9 +639,12 @@ pnpm ops settings --json '{"patch":{"social":{"instagram":{"visibility":"p scheduler does not queue a channel with no cookie source, nor any Instagram channel while Instagram is held; /operations/sync says why. A restart never re-queues an interrupted Instagram fetch: its place is saved and the next scheduled or pressed sync continues. -- **Only the editor's jobs ask Instagram.** `pnpm archilyzer posts fetch <slug>` refuses an Instagram channel and - names `pnpm ops fetch-posts`; a channel whose `postFetcher` is another platform's is refused. yt-dlp is never - started on an instagram.com URL (`import-video` says so; a single reel's import comes later). +- **Only the editor's jobs ask Instagram, on Instagram's queue.** `pnpm archilyzer posts fetch <slug>` refuses an + Instagram channel and names `pnpm ops fetch-posts`. A `queueKey` other than `platform:instagram` is refused + for one (by `fetch-posts`, `resume-backfill`, a Sync, a Retry), and the fetch refuses again if its job is on + any other queue. A channel whose `postFetcher` is not of its platform — or of its URL's host — is refused. + yt-dlp is never started on an instagram.com URL, from the editor or from umtool's scripts (`import-video` + says so; a metadata scan leaves such a URL out of its batch and says so; a single reel's import comes later). - **Nothing is retried.** The first 429 ends the run, keeps what it read, and holds every Instagram job for 60 minutes. So does one 401 or 403; a second in a row with no clean read between raises the alert instead. A login, challenge or checkpoint page — and the "Page Not Found" a dead session gets — raises Instagram's alert diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -94,6 +94,7 @@ import { } from "../social/instagramMedia"; import { instagramJobGuard } from "../jobs/instagramGuard"; import { currentJobContext } from "../lib/jobContext"; +import { INSTAGRAM_QUEUE_KEY, INSTAGRAM_QUEUE_REFUSAL, isInstagramPostsChannelConfig } from "../lib/instagram/channel"; import { detectPlatform } from "../lib/platform"; import { postsMediaDir } from "../social/postCapture"; import type { XCookieSource } from "../social/xCookieSource"; @@ -193,16 +194,26 @@ export const INSTAGRAM_ONLY_AS_A_JOB = (slug: string) => // A channel's fetcher is of the channel's platform (review 1, M3): a config // naming X's fetcher on an Instagram channel (or the other way round) would // run one platform's requests on another's queue, past its guard. +// +// BOTH SIGNS ARE ASKED (review 2, N5): the platform the config names, AND the +// platform of its URL when the host is one the app knows. Trusting the config +// alone let {platform: "twitter", url: an instagram.com account, postFetcher: +// X's} hand X's fetcher an Instagram URL on X's queue. A URL whose host the +// app does not know (a Nitter instance, a bare Bluesky handle, a forum that +// is told by its platform) says nothing and is not judged. export function fetcherPlatformMismatch( slug: string, config: { platform?: string; url?: string }, fetcher: { platform: string; label: string; id: string }, ): string | null { - const channel = config.platform ?? detectPlatform(config.url) ?? null; - if (!channel || channel === fetcher.platform) return null; + const named = config.platform ?? null; + const ofUrl = detectPlatform(config.url) ?? null; + const channel = named && named !== fetcher.platform ? named : ofUrl && ofUrl !== fetcher.platform ? ofUrl : null; + if (!channel) return null; return ( - `${slug} is on ${channel}, and its fetcher (${fetcher.label}, "${fetcher.id}") is ${fetcher.platform}'s: ` + - "nothing was asked. Set the channel's postFetcher to one of its own platform's, or clear it." + `${slug} is on ${channel}${channel === ofUrl && channel !== named ? " (its URL's host)" : ""}, and its fetcher ` + + `(${fetcher.label}, "${fetcher.id}") is ${fetcher.platform}'s: nothing was asked. ` + + "Set the channel's postFetcher to one of its own platform's, or clear it." ); } @@ -429,14 +440,26 @@ export async function fetchPosts( return { ok: false, written: 0, skipped: 0, complete: false, error: FORUM_BACKFILL_REFUSAL }; } - if (fetcher.platform === "instagram") { + if (fetcher.platform === "instagram" || isInstagramPostsChannelConfig(config)) { const refusal = instagramFetchRefusal(slug, config, { retryOnBlock: Boolean(opts.retryOnBlock) }); if (refusal) return { ok: false, written: 0, skipped: 0, complete: false, ...refusal }; // Only as the editor's job, and its guard asked HERE too: the alert and // the cooldown hold whoever calls. - if (!currentJobContext()) { + const job = currentJobContext(); + if (!job) { return { ok: false, written: 0, skipped: 0, complete: false, error: INSTAGRAM_ONLY_AS_A_JOB(slug) }; } + // …and only on Instagram's own queue (review 2, N1): a job on any other + // runs beside the one there, with no gap between them. + if (job.queueKey !== INSTAGRAM_QUEUE_KEY) { + return { + ok: false, + written: 0, + skipped: 0, + complete: false, + error: INSTAGRAM_QUEUE_REFUSAL(slug, job.queueKey ?? "(none)"), + }; + } const guard = await instagramJobGuard({ paths }); if (!guard.ok) return { ok: false, written: 0, skipped: 0, complete: false, error: guard.message }; } diff --git a/common/jobs/instagramPacing.test.ts b/common/jobs/instagramPacing.test.ts @@ -118,6 +118,7 @@ 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"); @@ -156,10 +157,10 @@ const instagramMedia = { pauseMs: () => 3000, }; -async function fetchJob(slug: string, starts: Map<string, number>, extra: Record<string, unknown> = {}) { +async function fetchJob(slug: string, starts: Map<string, number>, extra: Record<string, unknown> = {}, queueKey = "platform:instagram") { return runManagedFunction({ kind: "fetch-posts", - queueKey: "platform:instagram", + queueKey, paths, channelSlug: slug, fn: async (onLog, signal) => { @@ -230,6 +231,26 @@ test("a channel with no cookie source of its own is refused, and gallery-dl neve 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]); @@ -278,7 +299,7 @@ test("5 Instagram fetches, job 1 meets a challenge: job 1 fails, the alert is up 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", onLog: () => {}, staleServices: new Set() }, + { 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); @@ -425,3 +446,38 @@ test("a run past its request cap is stopped with an interrupt and keeps what gal 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<string, number>(); + 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); +}); diff --git a/common/jobs/instagramSchedule.test.ts b/common/jobs/instagramSchedule.test.ts @@ -56,3 +56,19 @@ test("the one predicate", () => { // A video channel that names the platform is not an Instagram posts channel. assert.equal(instagramSyncHold({ platform: "instagram" } as ChannelConfig, HELD), null); }); + +// Review 2, N7: the scheduler and the fetch agree about which channel is +// Instagram's — by the platform, the fetcher or the URL's host. +test("an Instagram channel told only by its URL (no platform in its config) is held back like any other", () => { + const byUrl = { handling: "transcribe", sourceKind: "social", url: "https://www.instagram.com/example.account/" } as ChannelConfig; + const byFetcher = { handling: "transcribe", sourceKind: "social", postFetcher: "instagram-gallery-dl", url: "https://example.invalid/x" } as ChannelConfig; + assert.equal(instagramSyncHold(byUrl, null), INSTAGRAM_SYNC_NO_COOKIES); + assert.equal(instagramSyncHold(byFetcher, null), INSTAGRAM_SYNC_NO_COOKIES); + assert.equal(instagramSyncHold({ ...byUrl, cookiesFromBrowser: "firefox:ig" } as ChannelConfig, HELD), HELD); + const r = selectDueChannels({ ...base, channels: [{ slug: "ig-by-url", config: byUrl }, { slug: "x-chan", config: x }] }); + assert.deepEqual(r.due, ["x-chan"]); + const view = buildScheduleView({ ...base, channels: [{ slug: "ig-by-url", config: byUrl }] }); + assert.deepEqual([view[0]!.autoSyncEligible, view[0]!.heldReason], [false, INSTAGRAM_SYNC_NO_COOKIES]); + // Its cadence is Instagram's too. + assert.equal(view[0]!.intervalMinutes, 720); +}); diff --git a/common/jobs/resumeInterrupted.test.ts b/common/jobs/resumeInterrupted.test.ts @@ -254,3 +254,28 @@ test("an interrupted Instagram fetch is not re-queued by a boot: it waits for th await rm(fx.root, { recursive: true, force: true }); } }); + +// Review 2, N1: a queue key is only where a job ran. An Instagram channel's +// job that ran on another queue is left too. +test("an interrupted fetch of an Instagram channel is not re-queued whatever queue it ran on", async () => { + const spec: JobSpec = { kind: "fetch-posts", slug: "example-ig", params: { queueKey: "side" } }; + const fx = await fixture([ + { id: "IG2", kind: "fetch-posts", queueKey: "side", channelSlug: "example-ig", spec }, + { id: "X2", kind: "fetch-posts", queueKey: "side", channelSlug: "example-x", spec: { kind: "fetch-posts", slug: "example-x", params: { queueKey: "side" } } }, + ]); + try { + const channelsDir = path.join(fx.root, "channels"); + await mkdir(path.join(channelsDir, "example-ig"), { recursive: true }); + await mkdir(path.join(channelsDir, "example-x"), { recursive: true }); + // Told by its URL alone: no platform in the config. + await writeFile(path.join(channelsDir, "example-ig", "config.json"), JSON.stringify({ sourceKind: "social", url: "https://www.instagram.com/example.account/" })); + await writeFile(path.join(channelsDir, "example-x", "config.json"), JSON.stringify({ sourceKind: "social", platform: "twitter", url: "https://x.com/example" })); + const { calls, requeue } = recorder(); + const out = await resumeInterruptedJobs({ paths: { ...fx.paths, channelsDir } as Paths, requeue, ids: ["IG2", "X2"], now: NOW }); + assert.equal(out.find((o) => o.id === "IG2")!.action, "not-resumed"); + assert.equal(out.find((o) => o.id === "X2")!.action, "resumed"); + assert.deepEqual(calls.map((c) => c.slug), ["example-x"]); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); diff --git a/common/jobs/resumeInterrupted.ts b/common/jobs/resumeInterrupted.ts @@ -34,7 +34,8 @@ // `resumedAs`. import path from "node:path"; -import { appendFile, readdir } from "node:fs/promises"; +import { appendFile, readFile, readdir } from "node:fs/promises"; +import { INSTAGRAM_QUEUE_KEY, isInstagramPostsChannelConfig, type InstagramChannelSigns } from "../lib/instagram/channel"; import { writeFileAtomic } from "../lib/jsonFile-server"; import type { Paths } from "../lib/paths"; import { INTERRUPTED_REASON, specKey, type RequeueFn } from "./bootQueuedJobs"; @@ -47,8 +48,20 @@ import { runWithResumeTag } from "./resumeTag"; // is "interrupted twice in a row" and is left for the operator. export const MAX_RESUMES_IN_A_ROW = 1; -// Instagram's queue, and why a job interrupted on it is left. -export const INSTAGRAM_QUEUE_KEY = "platform:instagram"; +// Why an interrupted Instagram job is left: one on Instagram's queue, or — a +// queue key is only where the job ran — one whose channel is an Instagram +// posts channel by the one predicate (lib/instagram/channel.ts). +export { INSTAGRAM_QUEUE_KEY }; + +async function isInstagramChannel(paths: Paths, slug: string | undefined): Promise<boolean> { + if (!slug || !paths.channelsDir) return false; + try { + const raw = JSON.parse(await readFile(path.join(paths.channelsDir, slug, "config.json"), "utf8")) as InstagramChannelSigns; + return isInstagramPostsChannelConfig(raw); + } catch { + return false; + } +} export const INSTAGRAM_NOT_RESUMED = "an Instagram job is not started by a restart — its place is saved, and the next scheduled sync (or a press) continues from it"; @@ -186,7 +199,7 @@ export async function resumeInterruptedJobs(opts: ResumeInterruptedOpts): Promis // one is a logged-in read, and a boot that re-queued it would ask // Instagram at a moment nobody chose. Its resume point is on disk; the // next scheduled sync, or a press, continues from it. - if (meta.queueKey === INSTAGRAM_QUEUE_KEY) { + if (meta.queueKey === INSTAGRAM_QUEUE_KEY || (await isInstagramChannel(opts.paths, meta.channelSlug ?? meta.spec?.slug))) { await decline(meta, "not-resumable", INSTAGRAM_NOT_RESUMED); continue; } diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -519,6 +519,7 @@ export async function runManagedFunction( jobId: id, kind: opts.kind, ...(opts.channelSlug ? { channelSlug: opts.channelSlug } : {}), + queueKey: opts.queueKey, onLog, staleServices: new Set<string>(), }; diff --git a/common/jobs/syncScheduler.ts b/common/jobs/syncScheduler.ts @@ -1,3 +1,4 @@ +import { isInstagramPostsChannelConfig } from "../lib/instagram/channel"; import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig"; import type { SyncSchedulerSettings } from "../lib/settings"; import { @@ -62,12 +63,16 @@ export type SelectDueInput = { export const INSTAGRAM_SYNC_NO_COOKIES = "Instagram: no cookie source of its own (set Cookies from browser on the channel's Edit form)"; -export function isInstagramPostsConfig(config: Pick<ChannelConfig, "sourceKind" | "platform">): boolean { - return config.sourceKind === "social" && config.platform === "instagram"; +// The ONE predicate (lib/instagram/channel.ts): the platform, the fetcher or +// the URL's host — whatever the fetch itself would treat as Instagram's. +export function isInstagramPostsConfig( + config: Pick<ChannelConfig, "sourceKind" | "platform"> & Partial<Pick<ChannelConfig, "postFetcher" | "url">>, +): boolean { + return isInstagramPostsChannelConfig(config); } export function instagramSyncHold( - config: Pick<ChannelConfig, "sourceKind" | "platform" | "cookiesFromBrowser">, + config: Pick<ChannelConfig, "sourceKind" | "platform" | "cookiesFromBrowser"> & Partial<Pick<ChannelConfig, "postFetcher" | "url">>, held: string | null | undefined, ): string | null { if (!isInstagramPostsConfig(config)) return null; diff --git a/common/lib/instagram/channel.ts b/common/lib/instagram/channel.ts @@ -0,0 +1,48 @@ +// IS THIS AN INSTAGRAM POSTS CHANNEL? One predicate, pure and client-safe, for +// everything that must agree about it: the fetch (controller/fetchPosts.ts), +// the action that queues it, the scheduler that would queue it +// (jobs/syncScheduler.ts) and the boot's resume (jobs/resumeInterrupted.ts). +// +// ANY SIGN OF INSTAGRAM COUNTS — the platform the config names, the fetcher it +// names, or its URL's host — because the fetch refuses a channel whose signs +// disagree (fetcherPlatformMismatch) and everything else must hold back the +// same channels the fetch would treat as Instagram's. Testing the config's +// `platform` alone queued a channel with an instagram.com URL and no platform +// every tick, to be refused every tick. + +import { detectPlatform } from "../detectPlatform.mjs"; + +export const INSTAGRAM_FETCHER_ID = "instagram-gallery-dl"; +export const INSTAGRAM_QUEUE_KEY = "platform:instagram"; + +export type InstagramChannelSigns = { + sourceKind?: string; + platform?: string; + postFetcher?: string; + url?: string; +}; + +export function isInstagramPostsChannelConfig(config: InstagramChannelSigns | null | undefined): boolean { + if (!config || config.sourceKind !== "social") return false; + return ( + config.platform === "instagram" || + config.postFetcher === INSTAGRAM_FETCHER_ID || + detectPlatform(config.url) === "instagram" + ); +} + +// An Instagram fetch runs on Instagram's queue and no other: a queue override +// would run it beside the job already there, with no gap between them. +export const INSTAGRAM_QUEUE_REFUSAL = (slug: string, asked: string) => + `${slug} is an Instagram channel: its jobs run on ${INSTAGRAM_QUEUE_KEY} and nowhere else (one at a time, ten minutes apart), ` + + `so the queue override "${asked}" is refused. Leave the queue at its default.`; + +// Why a queue override is refused for this channel, or null. +export function instagramQueueProblem( + slug: string, + config: InstagramChannelSigns | null | undefined, + override: string | undefined, +): string | null { + if (override === undefined || !isInstagramPostsChannelConfig(config)) return null; + return override.trim() === INSTAGRAM_QUEUE_KEY ? null : INSTAGRAM_QUEUE_REFUSAL(slug, override); +} diff --git a/common/lib/instagram/ytdlp.test.ts b/common/lib/instagram/ytdlp.test.ts @@ -6,6 +6,8 @@ import { readFile, readdir } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { jitterYtdlpSleeps } from "../jitter"; +import { jitterSleepArgs } from "../jitter.mjs"; +import { scanBatchIds } from "../../ytdlp/metadataScan"; import { INSTAGRAM_YTDLP_REFUSAL, instagramUrlInArgs, refuseInstagramYtdlp } from "./ytdlp"; test("an argv naming an instagram.com URL is refused, wherever the URL sits; any other is passed on", () => { @@ -38,3 +40,32 @@ test("every module of common/ that spawns yt-dlp passes its argv through that re } assert.deepEqual(offenders, []); }); + +test("the refusal is in the shared plain-JS pass, so umtool's scripts are held to it too", async () => { + const reel = "https://www.instagram.com/reel/CabcDEF1234/"; + assert.throws(() => jitterSleepArgs(["--simulate", "--", reel]), new Error(INSTAGRAM_YTDLP_REFUSAL)); + assert.throws(() => jitterSleepArgs(["--simulate", "--", reel], 0), new Error(INSTAGRAM_YTDLP_REFUSAL), "with jitter off too"); + assert.deepEqual(jitterSleepArgs(["--simulate", "--", "https://www.youtube.com/watch?v=aaaaaaaaaaa"], 0), ["--simulate", "--", "https://www.youtube.com/watch?v=aaaaaaaaaaa"]); + // The two umtool scripts that start yt-dlp hand it only an argv that went through that pass. + const umtool = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "umtool", "report-to-video"); + for (const [file, bin] of [["check-availability.mjs", "ytdlp"], ["build-video.mjs", "YTDLP"]] as const) { + const src = await readFile(path.join(umtool, file), "utf8"); + const calls = [...src.matchAll(new RegExp(`execFileP\\(${bin},\\s*([^)]{0,40})`, "g"))].map((m) => m[1]!); + assert.ok(calls.length > 0, `${file} starts yt-dlp`); + for (const c of calls) assert.ok(c.startsWith("jitterSleepArgs("), `${file}: ${c}`); + } +}); + +test("a metadata scan's batch file never holds an instagram.com URL: left out, in order, and said", () => { + const urls: Record<string, string> = { + a: "https://www.youtube.com/watch?v=aaaaaaaaaaa", + b: "https://www.instagram.com/reel/CabcDEF1234/", + c: "https://www.youtube.com/watch?v=ccccccccccc", + d: "https://instagram.com/p/CabcDEF1235/", + }; + const r = scanBatchIds(["a", "b", "c", "d"], (id) => urls[id]!); + assert.deepEqual(r.ids, ["a", "c"]); + assert.equal(r.leftOut, `2 instagram.com URL(s) left out of this scan: ${INSTAGRAM_YTDLP_REFUSAL}\n`); + assert.deepEqual(scanBatchIds(["a", "c"], (id) => urls[id]!), { ids: ["a", "c"], leftOut: null }); + assert.deepEqual(scanBatchIds(["b"], (id) => urls[id]!).ids, []); +}); diff --git a/common/lib/instagram/ytdlp.ts b/common/lib/instagram/ytdlp.ts @@ -1,24 +1,3 @@ -// yt-dlp IS NEVER STARTED ON AN instagram.com URL (lane instagram, review 1 -// S11). Instagram is read as a posts channel, by its own fetcher, on its own -// queue, behind its own guard; a yt-dlp run on a reel or an account would be -// a second, unguarded path to the same site. A single reel's import comes -// with a later slice. Pure and client-safe. - -import { isInstagramUrl } from "./ids"; - -export const INSTAGRAM_YTDLP_REFUSAL = - "Instagram is read as a posts channel; a single reel import comes with a later slice. " + - "No yt-dlp process was started for this instagram.com URL."; - -// The first argument that is an instagram.com URL, or null. -export function instagramUrlInArgs(args: readonly string[]): string | null { - for (const a of args) { - if (/^https?:\/\//i.test(a) && isInstagramUrl(a)) return a; - } - return null; -} - -// Throws the refusal when the argv names an instagram.com URL. -export function refuseInstagramYtdlp(args: readonly string[]): void { - if (instagramUrlInArgs(args)) throw new Error(INSTAGRAM_YTDLP_REFUSAL); -} +// yt-dlp is never started on an instagram.com URL: the rule and its sentence +// are in ./ytdlpRefusal.mjs (plain JS, so umtool's .mjs scripts share it). +export { INSTAGRAM_YTDLP_REFUSAL, instagramUrlInArgs, isInstagramComUrl, refuseInstagramYtdlp } from "./ytdlpRefusal.mjs"; diff --git a/common/lib/instagram/ytdlpRefusal.mjs b/common/lib/instagram/ytdlpRefusal.mjs @@ -0,0 +1,45 @@ +// yt-dlp IS NEVER STARTED ON AN instagram.com URL (lane instagram, review 1 +// S11, review 2 N8). Instagram is read as a posts channel, by its own +// fetcher, on its own queue, behind its own guard; a yt-dlp run on a reel or +// an account would be a second, unguarded path to the same site. A single +// reel's import comes with a later slice. +// +// Plain JS (with JSDoc types) so the ONE pass every yt-dlp argv takes before a +// spawn — `jitterSleepArgs` in ../jitter.mjs — can ask it for common's TS and +// for umtool's .mjs scripts alike. `./ytdlp.ts` re-exports this for TS callers. + +export const INSTAGRAM_YTDLP_REFUSAL = + "Instagram is read as a posts channel; a single reel import comes with a later slice. " + + "No yt-dlp process was started for this instagram.com URL."; + +/** + * Whether `value` is an http(s) URL on instagram.com. + * @param {unknown} value + * @returns {boolean} + */ +export function isInstagramComUrl(value) { + if (typeof value !== "string" || !/^https?:\/\//i.test(value.trim())) return false; + try { + return new URL(value.trim()).hostname.toLowerCase().replace(/^www\./, "") === "instagram.com"; + } catch { + return false; + } +} + +/** + * The first argument that is an instagram.com URL, or null. + * @param {readonly string[]} args + * @returns {string | null} + */ +export function instagramUrlInArgs(args) { + for (const a of args) if (isInstagramComUrl(a)) return a; + return null; +} + +/** + * Throws the refusal when the argv names an instagram.com URL. + * @param {readonly string[]} args + */ +export function refuseInstagramYtdlp(args) { + if (instagramUrlInArgs(args)) throw new Error(INSTAGRAM_YTDLP_REFUSAL); +} diff --git a/common/lib/jitter.mjs b/common/lib/jitter.mjs @@ -14,6 +14,8 @@ // // Plain JS so umtool's .mjs scripts and common's TS share one implementation. +import { refuseInstagramYtdlp } from "./instagram/ytdlpRefusal.mjs"; + export const DEFAULT_JITTER_SPREAD = 0.25; export const MAX_JITTER_SPREAD = 1; @@ -84,12 +86,19 @@ export function secondsArg(seconds) { * `args` with the value after each `--sleep-requests` / `--sleep-subtitles` * (and the other fixed yt-dlp waits) stretched by `jitterUp`. Every occurrence * is stretched because yt-dlp takes the last one. Returns a copy. + * + * EVERY yt-dlp ARGV PASSES HERE ON ITS WAY TO A SPAWN — common's (through + * jitter.ts jitterYtdlpSleeps) and umtool's .mjs scripts' — which is why the + * one refusal that holds for all of them is asked here: an instagram.com URL + * is never handed to yt-dlp (./instagram/ytdlpRefusal.mjs). It THROWS, and no + * process starts. * @param {readonly string[]} args * @param {number} [spread] * @param {() => number} [rand] * @returns {string[]} */ export function jitterSleepArgs(args, spread = DEFAULT_JITTER_SPREAD, rand = Math.random) { + refuseInstagramYtdlp(args); const out = [...args]; if (clampSpread(spread) === 0) return out; for (let i = 0; i < out.length - 1; i++) { diff --git a/common/lib/jitter.ts b/common/lib/jitter.ts @@ -1,7 +1,6 @@ // The operator's jitter (settings.json `pacing.jitter`) over ./jitter.mjs — see // there for why every request-pacing wait is stretched, and only stretched. -import { refuseInstagramYtdlp } from "./instagram/ytdlp"; import { getSettings } from "./settings"; import { clampSpread, @@ -47,14 +46,13 @@ export function jitterMsStable(ms: number, seed: string): number { // yt-dlp args with their fixed waits (`--sleep-requests`, `--sleep-subtitles`) // stretched — once per spawn, since yt-dlp itself waits exactly what it is told. // -// EVERY yt-dlp ARGV PASSES HERE ON ITS WAY TO A SPAWN, which is why the one -// refusal that holds for all of them is asked here too: an instagram.com URL -// is never handed to yt-dlp (lib/instagram/ytdlp.ts) — it throws, and no -// process starts. +// EVERY yt-dlp ARGV PASSES HERE ON ITS WAY TO A SPAWN. The one refusal that +// holds for all of them is asked inside jitterSleepArgs (jitter.mjs, shared +// with umtool's scripts): an instagram.com URL is never handed to yt-dlp +// (lib/instagram/ytdlpRefusal.mjs) — it throws, and no process starts. export function jitterYtdlpSleeps( args: readonly string[], rand: () => number = Math.random, ): string[] { - refuseInstagramYtdlp(args); return jitterSleepArgs(args, pacingJitter(), rand); } diff --git a/common/lib/jobContext.ts b/common/lib/jobContext.ts @@ -18,6 +18,9 @@ export type JobContext = { jobId: string; kind: string; channelSlug?: string; + // The queue the job runs on (its key in the registry). Code that must run + // on ONE queue — an Instagram fetch, on platform:instagram — asks it here. + queueKey?: string; // The job's log (the same sink its `fn` writes to). onLog: (line: string) => void; // Services whose cookie alert this job met while it ran (serviceCookies). diff --git a/common/package.json b/common/package.json @@ -41,6 +41,7 @@ "./lib/clips/suggest.mjs": "./lib/clips/suggest.mjs", "./lib/atomicFile.mjs": "./lib/atomicFile.mjs", "./lib/xTrending/marker.mjs": "./lib/xTrending/marker.mjs", + "./lib/instagram/ytdlpRefusal.mjs": "./lib/instagram/ytdlpRefusal.mjs", "./lib/cueWiden.mjs": "./lib/cueWiden.mjs", "./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs", "./lib/platformSeek.mjs": "./lib/platformSeek.mjs", diff --git a/common/social/instagramGalleryDlFetcher.test.ts b/common/social/instagramGalleryDlFetcher.test.ts @@ -9,7 +9,6 @@ import assert from "node:assert/strict"; import { buildInstagramGalleryDlArgs, fetchInstagramPosts, - instagramResumeFor, instagramGalleryDlFetcher, INSTAGRAM_FROM_TOP_CURSOR, INSTAGRAM_NO_COOKIES, @@ -185,12 +184,6 @@ test("the plan: a sync is one page, a walk is sized to its media budget, a refus // Streaming output would hide the exception: never asked for. assert.ok(!args.join(" ").includes("jsonl")); assert.ok(!args.includes("--no-download")); - // Which resume point covers a post: the page it was on at the latest. - assert.equal(instagramResumeFor(0, ["p2", "p3"], undefined), undefined); - assert.equal(instagramResumeFor(29, ["p2", "p3"], "start"), "start"); - assert.equal(instagramResumeFor(30, ["p2", "p3"], "start"), "p2"); - assert.equal(instagramResumeFor(75, ["p2", "p3"], "start"), "p3"); - assert.equal(instagramResumeFor(200, ["p2", "p3"], "start"), "p3"); }); test("SYNC NEW: stops at the first archived post, skipping the pinned ones on top; one page, two requests", async () => { @@ -340,8 +333,8 @@ test("A WALK IS SIZED TO ITS MEDIA: posts whose media would not fit the job's 12 assert.deepEqual(r.posts.map((p) => p.id), range(400, 361).map(igPk)); assert.equal(r.media!.reduce((n, m) => n + m.files.length, 0), 120); assert.equal(r.complete, false); - // Post 360 is row 40: on page 2 at the latest, so the next run starts at page-2. - assert.equal(r.cursor, "page-2"); + // The next run starts where this one did (the top): no page size is assumed. + assert.equal(r.cursor, INSTAGRAM_FROM_TOP_CURSOR); assert.equal(r.error, undefined); assert.ok(h.log.some((l) => /80 of the 120 new post\(s\) listed are left for the next run: their media would not fit this job's budget of 120 files/.test(l))); // A cut on the first page resumes where the run began (the top), and still moves on: the posts before the cut are archived. @@ -356,6 +349,38 @@ test("A WALK IS SIZED TO ITS MEDIA: posts whose media would not fit the job's 12 assert.deepEqual(r3.mediaBudget, { maxFiles: 40, maxBytes: 200 * 1024 * 1024 }); }); +// Review 2, N2: a page is not always 30 posts. A trimmed walk resumes from its +// OWN start, so the posts it left behind are listed again whatever a page held. +test("A TRIMMED WALK over 33-post pages loses nothing: run after run from the same start, every post is archived once", async () => { + // 132 posts in pages of 33, each a carousel of 3: 40 posts' media fit a run. + const all = days(132, 132, { media: ["image", "image", "video"] }); + const pagesOf33 = [page, igCursorLine("p2"), page, igCursorLine("p3"), page, igCursorLine("p4"), page]; + const seen = new Set<string>(); + const got: string[] = []; + let cursor: string | undefined; + let complete = false; + for (let run = 0; run < 8 && !complete; run++) { + // gallery-dl lists up to 120 posts from where the run starts: the top, or page k (33 posts a page). + const startRow = cursor && cursor !== INSTAGRAM_FROM_TOP_CURSOR ? (Number(cursor.slice(1)) - 1) * 33 : 0; + const listed = all.slice(startRow, startRow + 120); + const h = harness({ rows: igRows(listed), stderr: pagesOf33.slice(0, Math.max(1, Math.ceil(listed.length / 33) * 2 - 1)) }); + const r = await fetchInstagramPosts(input(h, { seenIds: new Set(seen), ...(cursor ? { cursor } : {}) }), h.deps); + assert.equal(r.error, undefined); + assert.ok(r.posts.length > 0 || r.complete || r.cursor !== cursor, `run ${run} made no progress`); + for (const p of r.posts) { + assert.ok(!seen.has(p.id), `post ${p.id} archived twice`); + seen.add(p.id); + got.push(p.id); + } + assert.ok((r.media ?? []).reduce((n, m) => n + m.files.length, 0) <= 120); + cursor = r.cursor; + complete = r.complete; + } + assert.equal(complete, true); + // Every post, in order, none skipped: with the old page arithmetic posts 121..132 of a page past row 99 were lost. + assert.deepEqual(got, all.map((p) => igPk(p.n))); +}); + test("A REFUSAL DURING THE ACCOUNT LOOKUP ends the run: gallery-dl swallows it and would go on to the feed", async () => { // A 429 on the search: gallery-dl would try the profile page next, and then the feed. const h = harness({ rows: igRows(days(10, 3)), stderr: [igRequestLine(igSearchPath(), 429), igRequestLine(`/${IG_HANDLE}`, 200), page] }); @@ -414,13 +439,60 @@ test("ONE 401/403 holds Instagram for the hour; a SECOND with no clean read betw assert.equal(many.rateLimits, 1); }); -test("posts with no request line read are a failure, never a clean read: the cap and the refusal watch were blind", async () => { +test("NO request line read is a failure whatever was printed: never a clean read, never complete", async () => { const h = harness({ rows: igRows(days(10, 3)), stderr: ["[instagram][debug] Sleeping 8.83 seconds (request)"] }); const r = await fetchInstagramPosts(input(h), h.deps); - assert.match(r.error!, /none of its requests could be read from its log/); + assert.match(r.error!, /None of gallery-dl's requests could be read from its log/); assert.equal(r.complete, false); assert.equal(r.posts.length, 3, "what it printed is kept"); assert.deepEqual(h.outcomes, [], "no clean read is noted"); + // …and with NOTHING printed too: an empty listing with no request seen is not "the account has no posts". + const empty = harness({ rows: [], stderr: [] }); + const e = await fetchInstagramPosts(input(empty), empty.deps); + assert.match(e.error!, /None of gallery-dl's requests could be read/); + assert.equal(e.complete, false); + assert.deepEqual(empty.outcomes, []); + // A sync that printed only archived posts and showed no request is not "caught up" either. + const known = harness({ rows: igRows(days(10, 3)), stderr: [] }); + const k = await fetchInstagramPosts(input(known, { since: "2020-01-02T00:00:00.000Z", seenIds: new Set(days(10, 3).map((p) => igPk(p.n))) }), known.deps); + assert.equal(k.complete, false); + assert.match(k.error!, /None of gallery-dl's requests/); +}); + +// Review 2, N6: only a run that ended by itself counts as the clean read that +// forgets a pending 401/403. +test("a cancelled, drained, timed-out or over-cap run that printed rows is not a clean read", async () => { + const rows = igRows(days(20, 10)); + const ac = new AbortController(); + ac.abort(); + const cancelled = harness({ rows, stderr: [page], out: { canceled: true } }); + const c = await fetchInstagramPosts(input(cancelled, { signal: ac.signal }), cancelled.deps); + assert.deepEqual([c.complete, c.posts.length, c.error], [false, 10, undefined]); + assert.deepEqual(cancelled.outcomes, [], "cancelled: no clean read noted"); + const timed = harness({ rows, stderr: [page], out: { timedOut: true } }); + assert.equal((await fetchInstagramPosts(input(timed), timed.deps)).complete, false); + assert.deepEqual(timed.outcomes, []); + const drain = new AbortController(); + drain.abort(); + const drained = harness({ rows, stderr: [page] }); + const d = await fetchInstagramPosts(input(drained, { drain: drain.signal }), drained.deps); + assert.deepEqual([d.complete, d.drained], [false, true]); + assert.deepEqual(drained.outcomes, []); + const capped = harness({ rows, stderr: [page, page, page, page] }); + const o = await fetchInstagramPosts(input(capped, { since: "2020-01-01T00:00:00.000Z", seenIds: new Set(["1"]) }), capped.deps); + assert.equal(capped.runs[0]!.stops, 1); + assert.equal(o.complete, false); + assert.deepEqual(capped.outcomes, [], "over its request cap: no clean read noted"); + // A run that ended by itself is one: at the account's end… + const ended = harness({ rows, stderr: [page] }); + assert.equal((await fetchInstagramPosts(input(ended), ended.deps)).complete, true); + assert.equal(ended.outcomes.length, 1); + assert.equal(ended.outcomes[0]!.challengeLine, undefined); + // …and at its own cap of posts. + const atCap = harness({ rows: igRows(days(400, 120)), stderr: [page, igCursorLine("page-2"), page, igCursorLine("page-3"), page, igCursorLine("page-4"), page] }); + const a = await fetchInstagramPosts(input(atCap), atCap.deps); + assert.equal(a.complete, false); + assert.equal(atCap.outcomes.length, 1); }); test("a run is stopped at its request cap, whatever Instagram's page size", async () => { diff --git a/common/social/instagramGalleryDlFetcher.ts b/common/social/instagramGalleryDlFetcher.ts @@ -13,8 +13,10 @@ // page is LEFT, so the page a capped run ended inside is the resume point). // A WALK IS SIZED TO ITS MEDIA: 120 posts is its job's media budget in files, // and the posts whose media would not fit that budget are not archived by this -// run — the next one lists them again — so every post a run archives has its -// media asked for in the same run. A run that sent as many requests as +// run, so every post a run archives has its media asked for in the same run. +// The next run starts where THIS one did and lists them again (the posts this +// run archived are skipped as known): no page size is assumed, so nothing is +// lost whatever a page holds, and each run archives at least one post. A run that sent as many requests as // MAX_REQUESTS is stopped, whatever Instagram's page size turns out to be. // // A SYNC THAT CONTINUES (its page was all new, or it stopped part-way) walks on @@ -292,16 +294,6 @@ export function instagramCostLine(requests: readonly InstagramRequestLine[]): st ); } -// WHICH RESUME POINT COVERS A POST: the page the post at `row` was on is, at -// the latest, page floor(row / 30) + 1 of this run (a page holds at most 30 -// posts), and the cursor that page was reached by is the (page − 1)th logged. -// Page 1 is where the run began. -export function instagramResumeFor(row: number, cursors: readonly string[], start: string | undefined): string | undefined { - const page = Math.floor(row / INSTAGRAM_PAGE_POSTS) + 1; - if (page <= 1) return start; - return cursors[Math.min(page - 2, cursors.length - 1)] ?? start; -} - export async function fetchInstagramPosts( input: PostFetchInput, given: Partial<InstagramFetcherDeps> = {}, @@ -432,13 +424,16 @@ export async function fetchInstagramPosts( ".", ); - // Where the next run picks up when this one did not finish: the page the - // first post it left behind was on; else the last page gallery-dl left; - // else the point it was given; else — when it saved posts before leaving - // any page — the top. + // Where the next run picks up when this one did not finish. A run that + // left posts behind for its media budget starts again WHERE THIS ONE DID + // (its own cursor, or the top): which page a post was on is not known — + // gallery-dl prints no page marks, and a page is not always 30 posts — so + // any later cursor could skip the posts left behind. Otherwise: the last + // page gallery-dl left; else the point it was given; else — when it saved + // posts before leaving any page — the top. const start = plan.cursor ?? (input.cursor === INSTAGRAM_FROM_TOP_CURSOR ? INSTAGRAM_FROM_TOP_CURSOR : undefined); const resumeAt = trimmedAt - ? (instagramResumeFor(trimmedAt.row, cursors, start) ?? INSTAGRAM_FROM_TOP_CURSOR) + ? (start ?? INSTAGRAM_FROM_TOP_CURSOR) : (cursor ?? start ?? (posts.length > 0 ? INSTAGRAM_FROM_TOP_CURSOR : undefined)); const base = { posts, @@ -557,46 +552,47 @@ export async function fetchInstagramPosts( return { posts: [], complete: false, error: "gallery-dl printed nothing this reads as its JSON output." }; } - // POSTS WITH NO REQUEST LINE READ: the request cap and the refusal watch - // were blind (gallery-dl's log format changed, or --verbose was lost). What - // it printed is kept; the run is a failure, never a clean read. - if (requests.length === 0 && rows.emitted > 0) { + // A RUN THAT WAS STOPPED — cancelled, drained, out of time, at its request + // cap — keeps what it printed and its place, and is NOT a clean read: it + // settles no pending refusal (review 2, N6) and is never complete. + const stoppedWhy = + out.canceled || signal.aborted + ? "Cancelled; the next run resumes where this one left off." + : out.timedOut + ? `Stopped at this run's ${Math.round(INSTAGRAM_BUDGET_MS / 60_000)}-minute budget; the next run resumes where this one left off.` + : input.drain?.aborted + ? "Drained; the next run resumes where this one left off." + : overCap + ? `Stopped at ${plan.maxRequests} requests, this run's cap: Instagram's pages were smaller than ${INSTAGRAM_PAGE_POSTS} posts. ` + + "The next run resumes where this one left off." + : null; + if (stoppedWhy) { + log(stoppedWhy); + const drained = Boolean(input.drain?.aborted) && !out.canceled && !signal.aborted && !out.timedOut; + return { ...base, complete: false, ...(resumeAt && !reachedEnd ? { cursor: resumeAt } : {}), ...(drained ? { drained: true } : {}) }; + } + + // NO REQUEST LINE READ (review 2, N4): the request cap and the refusal watch + // were blind — gallery-dl's log format changed, or --verbose was lost. A + // failure whatever it printed: never a clean read, never complete. + if (requests.length === 0) { return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}), error: - "gallery-dl listed posts but none of its requests could be read from its log, so this run's request cap and its " + - "watch for a refusal saw nothing. The posts are kept; fix the log reading (instagramSignals.ts) before the next fetch.", + "None of gallery-dl's requests could be read from its log, so this run's request cap and its watch for a refusal " + + "saw nothing. What it listed is kept; fix the log reading (instagramSignals.ts) before the next fetch.", }; } - // A clean read: a pending signal is settled, and this is a request a person can name. + // A clean read — it ended by itself, with no signal, at its end or at its + // own cap: a pending signal is settled, and this is a request a person can name. const cleared = await deps.noteOutcome({ url: accountUrl, channel: channelSlug }); if (cleared) log(cleared.trimEnd()); if (trimmedAt) return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}) }; if (reachedEnd) return { ...base, complete: true }; - - if (out.canceled || signal.aborted || out.timedOut) { - log( - out.timedOut - ? `Stopped at this run's ${Math.round(INSTAGRAM_BUDGET_MS / 60_000)}-minute budget; the next run resumes where this one left off.` - : "Cancelled; the next run resumes where this one left off.", - ); - return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}) }; - } - if (input.drain?.aborted) { - log("Drained; the next run resumes where this one left off."); - return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}), drained: true }; - } - if (overCap) { - log( - `Stopped at ${plan.maxRequests} requests, this run's cap: Instagram's pages were smaller than ${INSTAGRAM_PAGE_POSTS} posts. ` + - "The next run resumes where this one left off.", - ); - return { ...base, complete: false, ...(resumeAt ? { cursor: resumeAt } : {}) }; - } // Fewer posts than were asked for: the walk reached the account's first post. if (rows.emitted < plan.maxPosts) return { ...base, complete: true }; if (plan.mode === "sync") { diff --git a/common/social/instagramSignals.test.ts b/common/social/instagramSignals.test.ts @@ -3,6 +3,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { + instagramWallPage, instagramErrorStatus, instagramStopSignal, classifyInstagramError, @@ -102,3 +103,43 @@ test("a request line that ends the run: a 429/401/403, the login page, the chall assert.equal(instagramErrorStatus({ message: "'401 Unauthorized' for 'https://www.instagram.com/x'" }), 401); assert.equal(instagramErrorStatus({ message: "Requested user could not be found" }), null); }); + +// Review 2, N3: the walls are path SEGMENTS. gallery-dl asks for the account's +// own page as /<handle>, and a handle may begin with "challenge" or contain +// "checkpoint" (both handles invented). +test("a handle that begins with 'challenge' or contains 'checkpoint' is an account's page, never a wall", () => { + const sig = (l: string) => instagramStopSignal(parseInstagramRequestLine(l)!); + for (const handle of ["challengeaccepted", "checkpoint.charlie", "challenge", "checkpoint"]) { + assert.equal(sig(req(`/${handle}`, 200)), null, handle); + assert.equal(instagramWallPage(`/${handle}`), null, handle); + // Its 404 is the account being gone, as for any handle. + const gone = classifyInstagramError( + { error: "NotFoundError", message: "Requested user could not be found" }, + { requests: lines(req(`/web/search/topsearch/?query=${handle}`, 404), req(`/${handle}`, 404)), handle }, + ); + assert.equal(gone.class, "not-found", handle); + // An error row that quotes the account's own URL is not a challenge either. + const row = classifyInstagramError( + { error: "HttpError", message: `'500 Internal Server Error' for 'https://www.instagram.com/${handle}'` }, + { requests: [], handle }, + ); + assert.equal(row.class, "error", handle); + // The search for it is not a wall. + assert.equal(sig(req(`/web/search/topsearch/?query=${handle}`, 200)), null); + } + // The walls themselves, by segment. + assert.equal(instagramWallPage("/challenge/"), "challenge"); + assert.equal(instagramWallPage("/challenge/action/abc/"), "challenge"); + assert.equal(instagramWallPage("/api/v1/challenge/"), null, "only the first segment is the challenge page"); + assert.equal(instagramWallPage("/accounts/checkpoint/"), "challenge"); + assert.equal(instagramWallPage("/checkpoint/"), "challenge"); + assert.equal(instagramWallPage("/accounts/login/"), "login"); + assert.equal(instagramWallPage("/accounts/login"), "login"); + assert.equal(instagramWallPage("/accounts/loginhelp/"), null); + assert.equal(instagramWallPage("/challengeaccepted/"), null, "a handle with a trailing slash is still a handle"); + assert.equal(instagramWallPage("/"), null); + // A row whose URL IS a wall still classifies by it. + const ctx = { requests: [], handle: "challengeaccepted" }; + assert.equal(classifyInstagramError({ error: "HttpError", message: "'400 Bad Request' for 'https://www.instagram.com/challenge/?next=/'" }, ctx).class, "challenge"); + assert.equal(classifyInstagramError({ error: "HttpError", message: "'200 OK' for 'https://www.instagram.com/accounts/login/?next=/'" }, ctx).class, "login"); +}); diff --git a/common/social/instagramSignals.ts b/common/social/instagramSignals.ts @@ -71,6 +71,44 @@ export function profilePageStatus(requests: readonly InstagramRequestLine[], han return null; } +// WHICH WALL A PATH IS, by its SEGMENTS — never by a substring: gallery-dl +// asks for the account's own page as `/<handle>`, and a handle may begin with +// "challenge" or contain "checkpoint". A wall is +// /challenge/… the first segment, with something under it (or a +// trailing slash): never the bare `/<handle>` form +// /…/checkpoint/… a segment that is exactly "checkpoint", in a path +// of more than one segment (or with a trailing slash) +// /accounts/login… the first two segments +export function instagramWallPage(pathname: string): "challenge" | "login" | null { + const path = pathname.split("?")[0]!.toLowerCase(); + const segs = path.split("/").filter(Boolean); + if (segs.length === 0) return null; + // The bare one-segment form with no trailing slash is an account's page. + const bareHandle = segs.length === 1 && !path.endsWith("/"); + if (segs[0] === "accounts" && segs[1] === "login") return "login"; + if (bareHandle) return null; + if (segs[0] === "challenge" || segs.includes("checkpoint")) return "challenge"; + return null; +} + +// The wall an error row's text names: gallery-dl's own words for a redirect, +// or the path of the URL it quotes — never a word inside a handle. +function wallInText(text: string): "challenge" | "login" | null { + if (/redirect to challenge page|ChallengeError|challenge_required|checkpoint_required/i.test(text)) return "challenge"; + if (/redirect to (?:login|home) page/i.test(text)) return "login"; + for (const m of text.matchAll(/https?:\/\/[^\s'")]+/g)) { + try { + const u = new URL(m[0]); + if (!isInstagramApiHost(u.hostname.toLowerCase())) continue; + const page = instagramWallPage(u.pathname); + if (page) return page; + } catch { + /* not a URL */ + } + } + return null; +} + // WHAT ONE REQUEST LINE SAYS, AS IT ARRIVES. gallery-dl swallows every // exception of its account lookup (the search, then the profile page) and // goes on to the next request, so a refusal there never reaches the error @@ -86,8 +124,9 @@ export function instagramStopSignal(r: InstagramRequestLine): { class: "rate-lim if (!isInstagramApiHost(r.host)) return null; const path = r.path.split("?")[0]!.toLowerCase(); const line = `${r.method} ${r.path.split("?")[0]} answered ${r.status}`.slice(0, 300); - if (path.startsWith("/challenge") || path.includes("checkpoint")) return { class: "challenge", status: r.status, line: `${r.method} ${path} (a challenge or checkpoint page)` }; - if (path.startsWith("/accounts/login")) return { class: "login", status: r.status, line: `${r.method} ${path} (the login page)` }; + const page = instagramWallPage(path); + if (page === "challenge") return { class: "challenge", status: r.status, line: `${r.method} ${path} (a challenge or checkpoint page)` }; + if (page === "login") return { class: "login", status: r.status, line: `${r.method} ${path} (the login page)` }; if (r.status === 429 || r.status === 401 || r.status === 403) return { class: "rate-limit", status: r.status, line }; return null; } @@ -110,8 +149,9 @@ export function classifyInstagramError( ): InstagramSignal { const line = `${row.error}: ${row.message}`.trim().slice(0, 300); const text = `${row.error} ${row.message}`; - if (/redirect to challenge page|\/challenge\/|checkpoint|ChallengeError/i.test(text)) return { class: "challenge", line }; - if (/redirect to (?:login|home) page|\/accounts\/login/i.test(text)) return { class: "login", line }; + const wall = wallInText(text); + if (wall === "challenge") return { class: "challenge", line }; + if (wall === "login") return { class: "login", line }; if (/AuthRequired|AuthenticationError|AuthorizationError|authenticated cookies|login required|credentials/i.test(text)) { return { class: "login", line }; } diff --git a/common/ytdlp/metadataScan.ts b/common/ytdlp/metadataScan.ts @@ -14,6 +14,7 @@ // on a filtered channel, every one of those videos would otherwise be prefetched // by the downloader on every run, forever. +import { INSTAGRAM_YTDLP_REFUSAL, isInstagramComUrl } from "../lib/instagram/ytdlp"; import path from "node:path"; import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -93,6 +94,23 @@ const UNAVAILABLE_LINE = /video unavailable/i; // video's own URL, falling back to yt-dlp's native id when there is no usable // URL. Pure and exported so the divergence is testable without spawning // anything. +// THE IDS A BATCH FILE MAY HOLD: every one whose URL is not on instagram.com, +// in the order asked (the pass's verdict reads that order), and the sentence +// for the log when any was left out. yt-dlp is never started on an +// instagram.com URL (lib/instagram/ytdlpRefusal.mjs), and a URL inside a +// batch file is not in the argv that refusal reads. +export function scanBatchIds( + asked: ReadonlyArray<string>, + urlOf: (id: string) => string, +): { ids: string[]; leftOut: string | null } { + const ids = asked.filter((id) => !isInstagramComUrl(urlOf(id))); + const n = asked.length - ids.length; + return { + ids, + leftOut: n > 0 ? `${n} instagram.com URL(s) left out of this scan: ${INSTAGRAM_YTDLP_REFUSAL}\n` : null, + }; +} + export function canonicalScanId(record: { id?: unknown; webpage_url?: unknown; @@ -418,16 +436,19 @@ export async function runMetadataScan( // One pass over a batch file. Returns the ids it could not read as needs_auth, // so the caller can decide whether a cookie retry is worth a second pass. const runPass = async ( - ids: ReadonlyArray<string>, + asked: ReadonlyArray<string>, cookies: string | undefined, label: string, ): Promise<void> => { + // The batch file's URLs are not in the argv, so the argv's refusal + // (jitterSleepArgs) cannot see them: an instagram.com URL is left out of + // the batch here, and said (lib/instagram/ytdlpRefusal.mjs). + const urlOf = (id: string) => urlsById.get(id) ?? urlForId(id, channelConfig); + const { ids, leftOut } = scanBatchIds(asked, urlOf); + if (leftOut) opts.onLog(leftOut); + if (ids.length === 0) return; const batchFile = path.join(tmpRoot, `${label}.batch`); - await writeFile( - batchFile, - ids.map((id) => urlsById.get(id) ?? urlForId(id, channelConfig)).join("\n") + - "\n", - ); + await writeFile(batchFile, ids.map(urlOf).join("\n") + "\n"); const args = [ "--ignore-config", "--skip-download", diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -8,8 +8,9 @@ **Cookies from browser** in the Source section and the channel never borrows the global browser; with none set, a fetch is refused before a job exists. Use an account made for the archive: Instagram may checkpoint or ban an account that reads this way. - - **Gentle by rule.** One Instagram job at a time, ten minutes apart, and only as the editor's job (the CLI's - `posts fetch` refuses and names `pnpm ops fetch-posts`). A sync reads one page; a walk reads up to 120 posts + - **Gentle by rule.** One Instagram job at a time, ten minutes apart, only as the editor's job and only on + Instagram's queue (the CLI's `posts fetch` refuses and names `pnpm ops fetch-posts`; a queue override is + refused). A sync reads one page; a walk reads up to 120 posts and resumes. Nothing is retried: the first 429 (or one 401/403) holds Instagram for an hour; a login, challenge or checkpoint page, or a second 401/403 in a row, raises Instagram's alert, which refuses every Instagram job until **Recheck**. A run says what it cost in requests and files. A channel is synced every 12 diff --git a/editor/app/api/ops/fetch-posts/route.ts b/editor/app/api/ops/fetch-posts/route.ts @@ -45,9 +45,11 @@ export const dynamic = "force-dynamic"; // queue, as the buttons' does. // // An Instagram channel (lane instagram): a sync reads one page, a walk up to -// 300 posts, and the new posts' media are fetched in the same job. Refused +// 120 posts, and the new posts' media are fetched in the same job. Refused // here, before a job exists, when the channel has no cookie source of its own -// (`cookiesFromBrowser`), and with `retryOnBlock`. +// (`cookiesFromBrowser`), with `retryOnBlock`, and with a `queueKey` other +// than platform:instagram (its jobs run one at a time, ten minutes apart, on +// that queue and no other). // // Every refusal is the action's own sentence: a channel that is not a social // one, `full` and `older` together, a fetcher with no older walk, a floor diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -31,6 +31,7 @@ import { fakeXMediaFetch, fakeXProfileChromium } from "yt-dlp-transcript-common/ import { X_SEARCH_OLDER_REFUSAL } from "yt-dlp-transcript-common/controller/fetchXSearch"; import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts"; import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage"; +import { instagramQueueProblem, isInstagramPostsChannelConfig } from "yt-dlp-transcript-common/lib/instagram/channel"; import { BACKFILL_AND_FULL_REFUSAL, BACKFILL_AND_OLDER_REFUSAL, @@ -258,9 +259,15 @@ export async function fetchPostsAction( if (isSourcelessPostsChannel(config)) return { ok: false, info: true, error: SOURCELESS_POSTS_CHANNEL(slug) }; // An Instagram channel (lane instagram): nothing is queued without a cookie // source of its own, and its fetch is never retried on a block. - if (config.platform === "instagram") { + if (isInstagramPostsChannelConfig(config)) { const refusal = instagramFetchRefusal(slug, config, { retryOnBlock: Boolean(retry) }); if (refusal) return { ok: false, error: refusal.error }; + // On Instagram's queue and no other (review 2, N1). Every way a fetch of + // this channel is queued comes through here — the button, `pnpm ops + // fetch-posts` and resume-backfill, a Sync, the form's "Fetch posts now", + // a Retry or a replay — and the fetch itself asks again when it runs. + const queueProblem = instagramQueueProblem(slug, config, queueKey); + if (queueProblem) return { ok: false, error: queueProblem }; } // An X search channel's one walk is its search windows (release 38). if (older && isXSearchChannel(config)) return { ok: false, error: X_SEARCH_OLDER_REFUSAL }; diff --git a/editor/e2e/instagram.spec.ts b/editor/e2e/instagram.spec.ts @@ -118,6 +118,12 @@ test("no cookie source, nothing is asked; with one, a walk archives posts and th // Its own cookie source: the first fetch is a walk, capped here at 60 posts (two pages). expect((await ops(request, "channel-config", { slug, patch: { cookiesFromBrowser: COOKIES } })).body.ok).toBe(true); + // On Instagram's queue and no other: a queue override would run it beside the job there, with no gap. + for (const action of ["fetch-posts", "resume-backfill"]) { + const side = await ops(request, action, { slug, queueKey: "side" }); + expect(side.status).toBe(400); + expect(side.body.error).toMatch(/ig-fake is an Instagram channel: its jobs run on platform:instagram and nowhere else .*the queue override "side" is refused/); + } const walk = await ops(request, "fetch-posts", { slug, limit: 60 }); expect(walk.body.ok).toBe(true); expect(await waitJob(request, walk.body.jobId!)).toBe("done"); diff --git a/plans/instagram.md b/plans/instagram.md @@ -61,6 +61,14 @@ These are rulings, not reasons. A later ruling overturns an earlier one only whe `common/jobs/instagram*.test.ts`, `editor/e2e/instagram.spec.ts` with `editor/e2e/fixtures/bin/fake-gallery-dl-instagram.mjs`. +**Review 2 (18 Nov), as fixed.** N1 a queue override ran an Instagram fetch beside the one on its queue: the +action refuses any queue but `platform:instagram`, and the fetch refuses when its job is on another (the job +context carries the queue). N2 a trimmed walk resumes from its own start (no page size assumed). N3 the walls +are path segments, never a word in a handle. N4 no request line read is a failure whatever was printed. N5 the +fetcher must match the URL's platform too. N6 a stopped run is not a clean read. N7 one predicate for "an +Instagram channel" (`common/lib/instagram/channel.ts`). N8 the yt-dlp refusal is in the shared `jitter.mjs` +(umtool's scripts too) and a metadata scan's batch file. + **Review 1 (18 Nov), as fixed.** M1 a continuing sync dropped the gap (it stopped at its own posts); M2 a refusal during the lookup did not end the run; M3 the CLI's `posts fetch` ran past the guard, and a fetcher of another platform could. S1–S13: digits inside captions, no media after a refusal, the media half's diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1955,7 +1955,8 @@ export function usage() { " leaves the posts whose media would not fit for its next run; what is", " still not fetched is recorded as owed, and none after a refusal).", " Refused before a job exists when the channel has no cookiesFromBrowser", - ' of its own, and with "retryOnBlock" or "older". A login, challenge or', + ' of its own, with "retryOnBlock" or "older", and with a "queueKey" other', + " than platform:instagram. A login, challenge or", " checkpoint page raises Instagram's alert and refuses every Instagram job", " until recheck-service; the first 429 holds Instagram for an hour", ' (clear-platform-hold {"platform": "instagram"} ends that by hand). A', diff --git a/umtool/report-to-video/instagram-ytdlp.test.mjs b/umtool/report-to-video/instagram-ytdlp.test.mjs @@ -0,0 +1,12 @@ +// yt-dlp is never started on an instagram.com URL (lane instagram): the pass +// umtool's scripts hand every yt-dlp argv through throws, so no process starts. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { jitterSleepArgs } from "yt-dlp-transcript-common/lib/jitter.mjs"; +import { INSTAGRAM_YTDLP_REFUSAL } from "yt-dlp-transcript-common/lib/instagram/ytdlpRefusal.mjs"; + +test("the argv pass check-availability and build-video use refuses an instagram.com URL", () => { + assert.throws(() => jitterSleepArgs(["--simulate", "--no-warnings", "https://www.instagram.com/reel/CabcDEF1234/"]), new Error(INSTAGRAM_YTDLP_REFUSAL)); + assert.throws(() => jitterSleepArgs(["-f", "b", "--download-sections", "*10-20", "--", "https://instagram.com/p/CabcDEF1234/"]), /Instagram is read as a posts channel/); + assert.deepEqual(jitterSleepArgs(["--simulate", "https://www.youtube.com/watch?v=aaaaaaaaaaa"], 0), ["--simulate", "https://www.youtube.com/watch?v=aaaaaaaaaaa"]); +});