Skip to content

Open source alternative to Semrush and Ahrefs

Keep Shopify audits going past refused URLs (#1059)

Ben Senescuc79387a281b8
diff --git a/docs/maintainers/SITE_AUDIT_RENDERING.md b/docs/maintainers/SITE_AUDIT_RENDERING.md
index 28e08b83..3193af1b 100644
--- a/docs/maintainers/SITE_AUDIT_RENDERING.md
+++ b/docs/maintainers/SITE_AUDIT_RENDERING.md
@@ -58,18 +58,21 @@ calls are never retried automatically.
## Throttled Shopify storefronts
-Shopify's edge rate limits requests from Cloudflare Workers with a 429, often
-even when they carry a crawler signature, and backing off rarely helps. When the
-audited site is a Shopify store (its `powered-by` header, a saved crawler
-signature, or a host in Shopify's address range) and the audit renders
-JavaScript, a page whose direct fetch returns 429 goes straight to the
-renderers instead of the shared backoff. Browser Run is usually throttled too;
-Context fetches from outside Cloudflare and reads the page. A page neither
-renderer reads stays `rate_limited` and enters the shared backoff, so a store
-that stays unreadable pauses and then stops the crawl as before.
-
-An unrendered audit of a Shopify store backs off as before. Its report asks for
-a crawler signature first, since Shopify sometimes lets a signed crawl through.
+Shopify's edge refuses some requests from crawlers with a 429 served within
+milliseconds, signed or not, and the refusals are per URL more often than per
+site (see `shopify-crawling.md`). When the audited site is a Shopify store (its
+`powered-by` header, a saved crawler signature, or a host in Shopify's address
+range) and the audit renders JavaScript, a page whose direct fetch returns 429
+goes straight to the renderers instead of the shared backoff. Browser Run is
+usually throttled too; Context fetches from outside Cloudflare and reads the
+page. A page neither renderer reads is given up on as `rate_limited`, which
+pauses the crawl like any other refusal; a store that refuses several pages in
+a row stops the crawl.
+
+An unrendered audit of a Shopify store backs off as described in
+`crawl-throttle.ts`: a refused page gets one retry after the Retry-After and is
+then recorded as rate limited while the crawl continues. Its report asks for a
+crawler signature first, since Shopify sometimes lets a signed crawl through.
Once a signed, unrendered crawl is still rate limited, the report asks for a
new audit with Render JavaScript turned on instead.
diff --git a/docs/maintainers/shopify-crawling.md b/docs/maintainers/shopify-crawling.md
new file mode 100644
index 00000000..03260a78
--- /dev/null
+++ b/docs/maintainers/shopify-crawling.md
@@ -0,0 +1,138 @@
+# Shopify storefronts and the site audit crawler
+
+What Shopify does to crawlers, what our production data and experiments showed
+on 2026-10-23, what the crawler does about it, and what is left to try.
+
+## What Shopify does
+
+- Since 2026-05-30 Shopify applies tiered rate limits to bots on storefront
+ pages and the Storefront API: unsigned traffic gets the strictest tier,
+ traffic signed with Web Bot Auth a higher tier, and a third tier is granted
+ by application through a Google Form linked from the
+ [changelog](https://shopify.dev/changelog/posts/bots-and-agents-should-identify-themselves-via-web-bot-auth).
+ Shopify staff have said a third-party signature alone changes nothing until
+ the bot is registered through that form. No tier has published numbers.
+- Merchants can mint a crawler signature in admin (Online Store → Preferences →
+ Crawler access): three static headers, one connected domain each, at most
+ three months, not renewable. The help page says a signed crawler that still
+ gets 429s has an invalid signature. Our data says otherwise (below).
+- The refusal is `HTTP 429`, body `local_rate_limited`, `Retry-After: 60`,
+ answered by Shopify's ingress tier behind Cloudflare (one `x-dc` hop, no
+ `cf-mitigated`), not by Cloudflare's edge. Pages served from Cloudflare's
+ cache (`cf-cache-status: HIT`) are never refused; cold listing pages (blogs,
+ deep pagination, collections) are refused most.
+- Whether a request is refused depends on the client identity (IP class, TLS
+ fingerprint, user agent), the path, and the cache state together. Nothing
+ about it is documented, and Shopify offers no IP allowlisting.
+
+## What our data showed
+
+Sixty days to 2026-10-23, hosted production:
+
+| Measure | Value |
+| ---------------------------------------------------- | -------------- |
+| Shopify audits (projects) | 1,827 (1,033) |
+| Stopped early on a rate limit | 558 (31%) |
+| Stopped at first contact (homepage refused) | 302 |
+| Stopped mid-crawl | 256 |
+| Mid-crawl stops caused by exactly one refused URL | 242 |
+| Refused pages per 1,000 fetched, unsigned vs signed | 5.0 vs 2.5 |
+| Image and asset links fetched as pages, worst audit | 1,986 of 2,608 |
+| Stores refused at first contact, audited again later | 166 |
+| of which served on another run | 151 (91%) |
+| Stores with a stopped audit, audited again later | 219 |
+| of which had a clean run of more than ten pages | 177 (81%) |
+
+First-contact refusals did not correlate with how many other Shopify audits we
+had running, so they are not self-inflicted by our own pacing.
+
+A refusal is not a verdict on the store or on our identity: the same store,
+crawled from the same Worker identity, is usually served on a later run, and
+28 of the 146 first-contact refusals with a later clean run had it within ten
+minutes. What the old crawler never measured is whether the next URL in the
+same run is served after a refusal, because it stopped at the first refused
+URL. The new logs measure exactly that.
+
+## What the experiments showed
+
+- From the production Worker, Shopify sees every request as coming from
+ `2a06:98c0:3600::103`, the single address Cloudflare uses for Worker
+ subrequests to other Cloudflare-proxied zones (`/cdn-cgi/trace` on any
+ storefront shows it). Shopify storefronts are Cloudflare BYOIP. Every Worker
+ of every Cloudflare customer shares that identity at Shopify, and no
+ Cloudflare product changes it.
+- A throwaway Worker fetched 60 storefront homepages in 15 seconds with no
+ refusal, while a residential machine was refused on 12 of 23 homepages a
+ minute later and on 20 of 30 product pages at one request per second after
+ about 35 earlier requests. Cloudflare's Worker identity is treated more
+ generously than a residential IP, and public reports say datacenter IPs on
+ AWS, GCP and OCI are refused on their first request. Moving the crawler to a
+ static cloud IP would make Shopify coverage worse, not better.
+- The refusals that ended audits were per URL: around them, thousands of pages
+ were served at one request per second, signed or unsigned. The crawler's old
+ rule, retry the same URL three times with the whole crawl paused and stop
+ after four refusals in a row, turned one refused listing page into a stopped
+ audit.
+- Sending our own Web Bot Auth headers to Shopify is neutral; bogus signature
+ headers did not change outcomes either.
+
+## What the crawler does now
+
+The pacing and refusal rules live in `src/server/lib/audit/crawl-throttle.ts`
+and its header comment; the public summary is in `web/content/docs/crawler.md`.
+The Shopify-specific parts:
+
+- Links to images, fonts, scripts and other files are not fetched as pages,
+ and on Shopify neither are the customer-authentication, discount and
+ password routes, which its edge refuses and its robots.txt does not cover.
+- A refused `robots.txt` or sitemap is retried once after its `Retry-After`,
+ within a two-minute budget per discovery run.
+- Every 429 logs `site_audit:rate_limited` with the URL, Retry-After, response
+ time, `cf-cache-status`, whether a merchant signature was sent, and the
+ body's first characters.
+
+## Ruled out
+
+- Static or dedicated egress IPs on Cloudflare: none exist for Workers on any
+ plan. Aegis (Dedicated CDN Egress IPs) covers Cloudflare-to-your-origin
+ traffic only. Cloudflare One dedicated egress IPs are an Enterprise add-on
+ and undocumented for Workers VPC. Workers VPC with a Mesh or Tunnel exit node
+ is undocumented for Worker fetches to public hosts.
+- A self-run fetcher on AWS, Fly or Hetzner: cheap (about $5 to $10 a month)
+ but a datacenter IP is the identity Shopify refuses hardest.
+- Browser Rendering: Cloudflare always marks it as bot traffic.
+- Cloudflare Verified Bot status: Shopify says enrolling with Cloudflare is not
+ part of its process.
+
+## Plan
+
+1. Watch the new `site_audit:rate_limited` logs and the share of Shopify
+ audits that still stop early. The cache-status field tells whether cold
+ pages are what gets refused.
+2. Register OpenSEO-Audit with Shopify through the Web Bot Auth registration
+ form: Signature-Agent `"https://app.openseo.so"`, the key directory at
+ `/.well-known/http-message-signatures-directory`, user agent
+ `OpenSEO-Audit/1.0`, category Search Engine Optimization, the crawl rate
+ (one request per second, two in flight), and the public crawler page as
+ documentation. There is no review timeline, and no report yet of approval
+ lifting refusals for a Workers-based crawler, so treat it as a bet.
+3. Run a controlled test on a store we control or with a merchant's help:
+ the same refused URL with the merchant's signature from the Worker and from
+ a residential machine, logging status, `x-dc` and `cf-cache-status`. This is
+ the only way to learn whether a signature exempts the refused listing pages.
+4. Try Context.dev for refused pages in unrendered audits. It fetches from
+ outside Cloudflare, costs about 3.8 usage credits a page, and already exists
+ as the rendering fallback. Two credits answer whether it gets a refused URL
+ through; a capped fallback for the handful of refused pages would follow.
+ For Shopify, Context should go before Browser Run, which never passes.
+5. Crawl sitemap URLs before link-only URLs and strip tracking parameters
+ (issue #274), so capped audits cover what the store declares first.
+
+## Open questions
+
+- After a refusal, is the next URL in the same run served (a per-URL
+ refusal), or does the store refuse everything for a few minutes? The crawler
+ tolerates about six minutes of continuous refusals before it stops.
+- Does Shopify's registration lift refusals for the shared Workers identity?
+- Does a valid merchant signature exempt the refused listing pages at all?
+- Does Context.dev's egress get those pages through, and from what network?
diff --git a/src/client/features/audit/results/ResultsView.tsx b/src/client/features/audit/results/ResultsView.tsx
index 941f2d33..d226aebd 100644
--- a/src/client/features/audit/results/ResultsView.tsx
+++ b/src/client/features/audit/results/ResultsView.tsx
@@ -127,7 +127,7 @@ export function ResultsView({
</AlertTitle>
<AlertDescription>
{crawlStopped
- ? "The requested cooldown exceeded the audit time limit, so some URLs were left unvisited. This report is incomplete. "
+ ? "The site kept refusing pages, so some URLs were left unvisited. This report is incomplete. "
: "Pages that returned 429 Too Many Requests could not be audited. "}
Re-run the audit after the rate limit resets, or ask the site owner
to allow the{" "}
diff --git a/src/server/lib/audit/crawl-throttle.test.ts b/src/server/lib/audit/crawl-throttle.test.ts
index d1945f4d..049868f4 100644
--- a/src/server/lib/audit/crawl-throttle.test.ts
+++ b/src/server/lib/audit/crawl-throttle.test.ts
@@ -7,15 +7,24 @@ beforeEach(() => {
});
afterEach(() => vi.useRealTimers());
+const URL_A = "https://example.com/a";
+const URL_B = "https://example.com/b";
+const URL_C = "https://example.com/c";
+const URL_D = "https://example.com/d";
+
describe("createCrawlThrottle", () => {
it("keeps oversized Retry-After values finite even with overlapping refusals", async () => {
const throttle = createCrawlThrottle(90_000);
await Promise.all([
- throttle.backoff(1, "9".repeat(310)),
- throttle.backoff(1, "60"),
+ throttle.backoff(URL_A, "9".repeat(310)),
+ throttle.backoff(URL_B, "60"),
]);
expect(throttle.stopped).toBe(true);
- expect(Object.values(throttle.state).every(Number.isFinite)).toBe(true);
+ expect(
+ Object.values(throttle.state)
+ .filter((value): value is number => typeof value === "number")
+ .every(Number.isFinite),
+ ).toBe(true);
expect(await throttle.ready()).toBe(false);
});
@@ -29,7 +38,7 @@ describe("createCrawlThrottle", () => {
save = resolve;
}),
);
- const backoff = throttle.backoff(1, "1");
+ const backoff = throttle.backoff(URL_A, "1");
await vi.advanceTimersByTimeAsync(0);
let started = false;
const request = throttle.ready().then(() => {
@@ -59,7 +68,7 @@ describe("createCrawlThrottle", () => {
it("pauses for thirty seconds on the first 429 and spaces retries", async () => {
const throttle = createCrawlThrottle(90_000);
expect(await throttle.ready()).toBe(true);
- expect(await throttle.backoff(1, null)).toBe(true);
+ expect(await throttle.backoff(URL_A, null)).toBe(true);
const starts: number[] = [];
const requests = Promise.all(
Array.from({ length: 3 }, async () => {
@@ -75,11 +84,11 @@ describe("createCrawlThrottle", () => {
it("rechecks a cooldown extended while requests are waiting", async () => {
const throttle = createCrawlThrottle(90_000);
- await throttle.backoff(1, "5");
+ await throttle.backoff(URL_A, "5");
const starts: number[] = [];
const request = throttle.ready().then(() => starts.push(Date.now()));
await vi.advanceTimersByTimeAsync(4_000);
- await throttle.backoff(1, "10");
+ await throttle.backoff(URL_B, "10");
await vi.advanceTimersByTimeAsync(9_999);
expect(starts).toEqual([]);
await vi.advanceTimersByTimeAsync(1);
@@ -91,7 +100,7 @@ describe("createCrawlThrottle", () => {
"honors Retry-After: %s",
async (header) => {
const throttle = createCrawlThrottle(90_000);
- await throttle.backoff(1, header);
+ await throttle.backoff(URL_A, header);
let started = false;
const request = throttle.ready().then(() => {
started = true;
@@ -104,35 +113,50 @@ describe("createCrawlThrottle", () => {
},
);
- it("backs off across chunks and stops after four consecutive refusals", async () => {
+ // Shopify's Retry-After outlasts most of a chunk, so the retry usually
+ // happens in the next one, after other pages have been served in between.
+ it("gives a URL one retry across chunks and served pages, then gives it up", async () => {
let throttle = createCrawlThrottle(90_000);
- for (const [index, delay] of [30_000, 60_000, 120_000, 240_000].entries()) {
- expect(await throttle.backoff(1, null)).toBe(index < 3);
- expect(throttle.state.pausedUntil - Date.now()).toBe(delay);
- if (index < 3) {
- await vi.advanceTimersByTimeAsync(delay);
- throttle = createCrawlThrottle(Date.now() + 90_000, throttle.state);
- }
+ expect(await throttle.backoff(URL_A, "60")).toBe(true);
+ await vi.advanceTimersByTimeAsync(60_000);
+ throttle = createCrawlThrottle(Date.now() + 90_000, throttle.state);
+ await throttle.recovered(URL_B);
+ expect(await throttle.backoff(URL_A, "60")).toBe(false);
+ expect(throttle.stopped).toBe(false);
+ });
+
+ it("stops after three URLs are given up on with nothing served between", async () => {
+ const throttle = createCrawlThrottle(90_000);
+ for (const url of [URL_A, URL_B]) {
+ await throttle.refuse(url, "1");
+ await vi.advanceTimersByTimeAsync(1_000);
}
+ await throttle.recovered(URL_C);
+ for (const url of [URL_C, URL_D]) {
+ await throttle.refuse(url, "1");
+ await vi.advanceTimersByTimeAsync(1_000);
+ }
+ expect(throttle.stopped).toBe(false);
+ await throttle.refuse(URL_A, "1");
expect(throttle.stopped).toBe(true);
- expect(await throttle.ready()).toBe(false);
});
- it("retains slower pacing after recovery and caps further slowdowns", async () => {
+ it("returns to normal pacing after twenty served pages, counted across chunks", async () => {
let throttle = createCrawlThrottle(90_000);
- for (let i = 0; i < 8; i++) {
- await throttle.backoff(1, "1");
- await vi.advanceTimersByTimeAsync(30_000);
- await throttle.recovered();
- throttle = createCrawlThrottle(Date.now() + 90_000, throttle.state);
+ for (const url of [URL_A, URL_B, URL_C, URL_D]) {
+ await throttle.backoff(url, "1");
+ await vi.advanceTimersByTimeAsync(1_000);
}
- expect(throttle.state.intervalMs).toBe(30_000);
- expect(throttle.stopped).toBe(false);
+ expect(throttle.state.intervalMs).toBe(10_000);
+ for (let i = 0; i < 9; i++) await throttle.recovered(URL_A);
+ throttle = createCrawlThrottle(Date.now() + 90_000, throttle.state);
+ for (let i = 0; i < 11; i++) await throttle.recovered(URL_A);
+ expect(throttle.state.intervalMs).toBe(1_000);
});
it("defers a ten-minute wait without marking the audit stopped", async () => {
const throttle = createCrawlThrottle(90_000);
- expect(await throttle.backoff(1, "600")).toBe(true);
+ expect(await throttle.backoff(URL_A, "600")).toBe(true);
expect(await throttle.ready()).toBe(false);
expect(throttle.stopped).toBe(false);
expect(throttle.state.pausedUntil).toBe(600_000);
@@ -162,15 +186,13 @@ describe("createCrawlThrottle", () => {
expect(throttle.stopped).toBe(false);
});
- it("stops when cumulative cooldowns exceed thirty minutes, without retrying early", async () => {
+ it("stops once two hours of waiting have accrued, served pages included, without retrying early", async () => {
let throttle = createCrawlThrottle(90_000);
- for (let i = 0; i < 3; i++) {
- expect(await throttle.backoff(1, "600")).toBe(true);
- await vi.advanceTimersByTimeAsync(600_000);
- await throttle.recovered();
- throttle = createCrawlThrottle(Date.now() + 90_000, throttle.state);
- }
- expect(await throttle.backoff(1, "600")).toBe(false);
+ expect(await throttle.backoff(URL_A, "4000")).toBe(true);
+ await vi.advanceTimersByTimeAsync(4_000_000);
+ await throttle.recovered(URL_A);
+ throttle = createCrawlThrottle(Date.now() + 90_000, throttle.state);
+ expect(await throttle.backoff(URL_B, "4000")).toBe(false);
expect(await throttle.ready()).toBe(false);
expect(vi.getTimerCount()).toBe(0);
});
diff --git a/src/server/lib/audit/crawl-throttle.ts b/src/server/lib/audit/crawl-throttle.ts
index ee055ad1..3a3618e1 100644
--- a/src/server/lib/audit/crawl-throttle.ts
+++ b/src/server/lib/audit/crawl-throttle.ts
@@ -1,20 +1,58 @@
+/**
+ * Pacing and 429 handling for one audit's origin.
+ *
+ * Every 429 pauses the whole crawl for the server's Retry-After (or an
+ * escalating default), and the refused URL gets one more try after the pause.
+ * A URL refused again is recorded as rate limited and the crawl moves on.
+ * Shopify's edge, for one, refuses individual listing pages to crawlers while
+ * serving everything around them, and a single such URL used to end audits
+ * thousands of pages in. The crawl stops only when the site refuses several
+ * URLs in a row without serving any, or has kept the crawler waiting for hours
+ * in total.
+ */
+
/** Retries per URL after its first 429. Every 429 still pauses new URLs. */
-const MAX_RETRIES = 3;
+const MAX_429_RETRIES = 1;
+/** URLs given up on in a row, with no page served between them, before the crawl stops. */
+const MAX_REFUSED_URLS = 3;
const FIRST_DELAY_MS = 30_000;
-const MAX_INTERVAL_MS = 30_000;
-const MAX_COOLDOWN_MS = 30 * 60_000;
+const MIN_INTERVAL_MS = 1_000;
+const MAX_INTERVAL_MS = 10_000;
+/** Pages served in a row before pacing returns to normal. */
+const RECOVERY_PAGES = 20;
+/**
+ * Waiting on 429s one audit may do in total. Cumulative, never reset: a site
+ * that interleaves refusals with served pages must still end, and a rendered
+ * audit must settle inside its 24-hour credit lock. Room for about sixty
+ * refused URLs at Shopify's 60-second Retry-After.
+ */
+const MAX_COOLDOWN_MS = 2 * 60 * 60_000;
+/** Longest single wait on a 429 during discovery. */
+const DISCOVERY_WAIT_MS = 60_000;
+/** All the waiting on 429s one discovery run may do, inside its step timeout. */
+const DISCOVERY_WAIT_BUDGET_MS = 120_000;
/** Checkpointed between chunks so a new step does not forget site limits. */
export type CrawlThrottleState = {
intervalMs: number;
nextRequestAt: number;
pausedUntil: number;
- consecutiveRateLimits: number;
+ /**
+ * 429s per URL still awaiting a retry. Kept here rather than in the fetch
+ * loop because a pause often outlasts the chunk and the URL comes back in
+ * the next one; without this it started over at its first try.
+ */
+ refusals: Record<string, number>;
+ /** URLs given up on since the last served page. */
+ givenUpRun: number;
+ /** Pages served since the last 429. */
+ served: number;
+ /** Waiting accrued over the whole audit. */
cooldownMs: number;
};
/** `Retry-After` is either delay-seconds or an HTTP-date. */
-function parseRetryAfterMs(header: string | null): number | null {
+export function parseRetryAfterMs(header: string | null): number | null {
if (!header) return null;
const value = header.trim();
// Keep over-budget values finite for checkpoint serialization/arithmetic.
@@ -27,10 +65,12 @@ function parseRetryAfterMs(header: string | null): number | null {
export interface CrawlThrottle {
/** False when this chunk can no longer start a request. */
ready(): Promise<boolean>;
- /** Pause the origin on every 429; return whether this URL may retry. */
- backoff(attempt: number, retryAfter: string | null): Promise<boolean>;
- /** A non-429 response breaks a run of consecutive refusals. */
- recovered(): Promise<void>;
+ /** Pause the origin on a 429 of `url`; return whether this URL may be tried again. */
+ backoff(url: string, retryAfter: string | null): Promise<boolean>;
+ /** Give `url` up as refused after a 429 nothing could read; pauses like backoff. */
+ refuse(url: string, retryAfter: string | null): Promise<void>;
+ /** A non-429 response for `url` ends a run of refusals. */
+ recovered(url: string): Promise<void>;
readonly checkpointFailed: boolean;
readonly stopped: boolean;
readonly state: CrawlThrottleState;
@@ -42,21 +82,24 @@ export function createCrawlThrottle(
previous?: CrawlThrottleState,
persist?: (state: CrawlThrottleState) => Promise<void>,
): CrawlThrottle {
- const state: CrawlThrottleState = previous
- ? { ...previous }
- : {
- intervalMs: 1_000,
- nextRequestAt: 0,
- pausedUntil: 0,
- consecutiveRateLimits: 0,
- cooldownMs: 0,
- };
+ const state: CrawlThrottleState = {
+ intervalMs: MIN_INTERVAL_MS,
+ nextRequestAt: 0,
+ pausedUntil: 0,
+ givenUpRun: 0,
+ served: 0,
+ cooldownMs: 0,
+ ...previous,
+ // A checkpoint from before refusals were tracked per URL has none.
+ refusals: { ...previous?.refusals },
+ };
let checkpointFailed = false;
let checkpoint = Promise.resolve();
+ const snapshot = () => ({ ...state, refusals: { ...state.refusals } });
const save = () => {
- const snapshot = { ...state };
+ const saved = snapshot();
checkpoint = checkpoint
- .then(() => persist?.(snapshot))
+ .then(() => persist?.(saved))
.catch((error) => {
checkpointFailed = true;
throw error;
@@ -65,8 +108,37 @@ export function createCrawlThrottle(
};
const stopped = () =>
checkpointFailed ||
- state.consecutiveRateLimits > MAX_RETRIES ||
+ state.givenUpRun >= MAX_REFUSED_URLS ||
state.cooldownMs > MAX_COOLDOWN_MS;
+ /** Record the `count`th 429 of `url` and pause the origin. */
+ const pause = async (
+ url: string,
+ count: number,
+ retryAfter: string | null,
+ ) => {
+ state.served = 0;
+ // A URL's second refusal is expected on Shopify and says nothing new
+ // about the site's pace; only a fresh URL's 429 slows the crawl down.
+ if (count === 1) {
+ state.intervalMs = Math.min(MAX_INTERVAL_MS, state.intervalMs * 2);
+ }
+ if (count > MAX_429_RETRIES) {
+ delete state.refusals[url];
+ state.givenUpRun += 1;
+ } else {
+ state.refusals[url] = count;
+ }
+ // Without a Retry-After, each URL given up on doubles the default wait.
+ const delayMs = Math.max(
+ state.intervalMs,
+ parseRetryAfterMs(retryAfter) ?? FIRST_DELAY_MS * 2 ** state.givenUpRun,
+ );
+ const now = Date.now();
+ const pausedUntil = Math.max(state.pausedUntil, now + delayMs);
+ state.cooldownMs += pausedUntil - Math.max(now, state.pausedUntil);
+ state.pausedUntil = pausedUntil;
+ await save();
+ };
return {
async ready() {
while (!stopped()) {
@@ -83,24 +155,22 @@ export function createCrawlThrottle(
}
return false;
},
- async backoff(attempt, retryAfter) {
- state.consecutiveRateLimits += 1;
- state.intervalMs = Math.min(MAX_INTERVAL_MS, state.intervalMs * 2);
- const delayMs = Math.max(
- state.intervalMs,
- parseRetryAfterMs(retryAfter) ??
- FIRST_DELAY_MS * 2 ** (state.consecutiveRateLimits - 1),
- );
- const now = Date.now();
- const pausedUntil = Math.max(state.pausedUntil, now + delayMs);
- state.cooldownMs += pausedUntil - Math.max(now, state.pausedUntil);
- state.pausedUntil = pausedUntil;
- await save();
- return !stopped() && attempt <= MAX_RETRIES;
+ async backoff(url, retryAfter) {
+ const count = (state.refusals[url] ?? 0) + 1;
+ await pause(url, count, retryAfter);
+ return !stopped() && count <= MAX_429_RETRIES;
},
- async recovered() {
- if (state.consecutiveRateLimits === 0) return;
- state.consecutiveRateLimits = 0;
+ async refuse(url, retryAfter) {
+ await pause(url, MAX_429_RETRIES + 1, retryAfter);
+ },
+ async recovered(url) {
+ state.served += 1;
+ delete state.refusals[url];
+ const normalPace =
+ state.served >= RECOVERY_PAGES && state.intervalMs > MIN_INTERVAL_MS;
+ if (normalPace) state.intervalMs = MIN_INTERVAL_MS;
+ if (state.givenUpRun === 0 && !normalPace) return;
+ state.givenUpRun = 0;
await save();
},
get checkpointFailed() {
@@ -110,7 +180,39 @@ export function createCrawlThrottle(
return stopped();
},
get state() {
- return { ...state };
+ return snapshot();
},
};
}
+
+/** Resolves true after waiting out a 429, false once the run's budget is spent. */
+export type RateLimitWait = (response: Response) => Promise<boolean>;
+
+/**
+ * One discovery run's shared wait on 429s. A refused robots.txt or sitemap is
+ * retried once after the server's Retry-After. Refusals that arrive together
+ * share one pause, and the run waits at most DISCOVERY_WAIT_BUDGET_MS in all
+ * so the discovery step keeps to its timeout. Before this, a sitemap shard
+ * refused at first contact was silently dropped with every URL in it, and a
+ * refused robots.txt read as "everything allowed".
+ */
+export function createRateLimitWait(): RateLimitWait {
+ let pausedUntil = 0;
+ let waitedMs = 0;
+ return async (response) => {
+ const now = Date.now();
+ const delayMs = Math.min(
+ parseRetryAfterMs(response.headers.get("retry-after")) ??
+ DISCOVERY_WAIT_MS,
+ DISCOVERY_WAIT_MS,
+ );
+ const until = Math.max(pausedUntil, now + delayMs);
+ const added = until - Math.max(now, pausedUntil);
+ if (waitedMs + added > DISCOVERY_WAIT_BUDGET_MS) return false;
+ waitedMs += added;
+ pausedUntil = until;
+ await response.body?.cancel();
+ await new Promise((resolve) => setTimeout(resolve, until - now));
+ return true;
+ };
+}
diff --git a/src/server/lib/audit/discovery.test.ts b/src/server/lib/audit/discovery.test.ts
index bb14c1a7..cd32b3b2 100644
--- a/src/server/lib/audit/discovery.test.ts
+++ b/src/server/lib/audit/discovery.test.ts
@@ -1,12 +1,55 @@
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { discoverUrls, parseRobotsTxt } from "@/server/lib/audit/discovery";
+// Resolves the request-signing env lookup instantly, so it can't race the
+// fake timers below.
+vi.mock("cloudflare:workers", () => ({ env: {} }));
+
function sitemapXml(urls: string[]): string {
const entries = urls.map((url) => `<url><loc>${url}</loc></url>`).join("");
return `<?xml version="1.0" encoding="UTF-8"?><urlset>${entries}</urlset>`;
}
describe("discoverUrls", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ // Shopify's edge refuses a crawler's first requests now and then; a sitemap
+ // shard dropped on a 429 took every URL in it out of the audit.
+ it("retries a sitemap refused with 429 after its Retry-After", async () => {
+ vi.useFakeTimers();
+ let sitemapFetches = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn((url: string) => {
+ if (url.endsWith("/robots.txt")) {
+ return Promise.resolve(new Response("User-agent: *\nAllow: /"));
+ }
+ sitemapFetches += 1;
+ return Promise.resolve(
+ sitemapFetches === 1
+ ? new Response("local_rate_limited", {
+ status: 429,
+ headers: { "retry-after": "5" },
+ })
+ : new Response(sitemapXml(["https://example.com/a"]), {
+ headers: { "content-type": "application/xml" },
+ }),
+ );
+ }),
+ );
+
+ const discovery = discoverUrls("https://example.com", 10);
+ await vi.advanceTimersByTimeAsync(4_999);
+ expect(sitemapFetches).toBe(1);
+ await vi.advanceTimersByTimeAsync(1);
+ const { urls } = await discovery;
+
+ expect(urls).toEqual(["https://example.com/a"]);
+ });
+
// Seeding the frontier is what sets a page's in-sitemap flag, so a URL
// dropped here reports inSitemap: false once the crawl reaches it through a
// link. Real sitemaps bury the homepage in the middle of the list
diff --git a/src/server/lib/audit/discovery.ts b/src/server/lib/audit/discovery.ts
index a12cd4d4..b6d87ca8 100644
--- a/src/server/lib/audit/discovery.ts
+++ b/src/server/lib/audit/discovery.ts
@@ -3,8 +3,10 @@
*/
import robotsParser from "robots-parser";
import { XMLParser } from "fast-xml-parser";
+import { readBodyCapped } from "./html-response";
import { isSameOrigin, normalizeUrl } from "./url-utils";
import { isCrawlableUrl } from "./url-policy";
+import { createRateLimitWait, type RateLimitWait } from "./crawl-throttle";
import type { CrawlerAccess } from "@/shared/crawler-access";
import {
auditRequestHeaders,
@@ -27,7 +29,6 @@ const SITEMAP_RETRIES = 1;
// shards are skipped whole — truncated XML would not parse anyway, and real
// generators shard far below this.
const MAX_SITEMAP_BYTES = 10 * 1024 * 1024;
-
const xmlParser = new XMLParser({
ignoreAttributes: false,
isArray: (name) => name === "sitemap" || name === "url",
@@ -45,14 +46,19 @@ export interface RobotsResult {
*/
async function fetchRobotsTxtText(
origin: string,
- access?: CrawlerAccess | null,
+ access: CrawlerAccess | null | undefined,
+ waitForRateLimit: RateLimitWait,
): Promise<string | null> {
try {
- const fetched = await fetchFollowingRedirects(
- `${origin}/robots.txt`,
- 10_000,
- access,
- );
+ const fetchRobots = () =>
+ fetchFollowingRedirects(`${origin}/robots.txt`, 10_000, access);
+ let fetched = await fetchRobots();
+ if (
+ fetched?.response.status === 429 &&
+ (await waitForRateLimit(fetched.response))
+ ) {
+ fetched = await fetchRobots();
+ }
if (!fetched?.response.ok) return null;
return (await fetched.response.text()).slice(0, MAX_ROBOTS_TXT_BYTES);
} catch (error) {
@@ -182,37 +188,10 @@ function isTimeoutError(error: unknown): boolean {
return "name" in error && error.name === "TimeoutError";
}
-/** Read a response body up to maxBytes; null when the body exceeds it. */
-async function readBodyCapped(
- response: Response,
- maxBytes: number,
-): Promise<string | null> {
- if (!response.body) return "";
- const reader = response.body.getReader();
- const chunks: Uint8Array[] = [];
- let total = 0;
- for (;;) {
- const { done, value } = await reader.read();
- if (done) break;
- total += value.byteLength;
- if (total > maxBytes) {
- await reader.cancel();
- return null;
- }
- chunks.push(value);
- }
- const joined = new Uint8Array(total);
- let offset = 0;
- for (const chunk of chunks) {
- joined.set(chunk, offset);
- offset += chunk.byteLength;
- }
- return new TextDecoder().decode(joined);
-}
-
async function fetchSitemapDocumentWithRetry(
sitemapUrl: string,
- access?: CrawlerAccess | null,
+ access: CrawlerAccess | null | undefined,
+ waitForRateLimit: RateLimitWait,
): Promise<{
nestedSitemaps: string[];
pageUrls: string[];
@@ -242,6 +221,13 @@ async function fetchSitemapDocumentWithRetry(
return { nestedSitemaps: [], pageUrls: [], timedOut: false };
}
+ if (
+ response.status === 429 &&
+ attempt < SITEMAP_RETRIES &&
+ (await waitForRateLimit(response))
+ ) {
+ continue;
+ }
if (!response.ok) {
return { nestedSitemaps: [], pageUrls: [], timedOut: false };
}
@@ -288,7 +274,8 @@ export async function discoverUrls(
maxPages = 50,
access?: CrawlerAccess | null,
): Promise<{ urls: string[]; robotsText: string | null }> {
- const robotsText = await fetchRobotsTxtText(origin, access);
+ const waitForRateLimit = createRateLimitWait();
+ const robotsText = await fetchRobotsTxtText(origin, access, waitForRateLimit);
const robots = parseRobotsTxt(origin, robotsText);
// Collect sitemap URLs: from robots.txt + default location
@@ -333,6 +320,7 @@ export async function discoverUrls(
const result = await fetchSitemapDocumentWithRetry(
normalizedUrl,
access,
+ waitForRateLimit,
);
if (
result.pageUrls.length === 0 &&
diff --git a/src/server/lib/audit/html-response.ts b/src/server/lib/audit/html-response.ts
index e74ba587..73ed1443 100644
--- a/src/server/lib/audit/html-response.ts
+++ b/src/server/lib/audit/html-response.ts
@@ -47,3 +47,31 @@ export function truncateToBytes(text: string, maxBytes: number) {
? text
: new TextDecoder().decode(bytes.subarray(0, maxBytes));
}
+
+/** Read a response body up to maxBytes; null when the body exceeds it. */
+export async function readBodyCapped(
+ response: Response,
+ maxBytes: number,
+): Promise<string | null> {
+ if (!response.body) return "";
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > maxBytes) {
+ await reader.cancel();
+ return null;
+ }
+ chunks.push(value);
+ }
+ const joined = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ joined.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return new TextDecoder().decode(joined);
+}
diff --git a/src/server/lib/audit/url-utils.test.ts b/src/server/lib/audit/url-utils.test.ts
index 082a6801..e4d02da3 100644
--- a/src/server/lib/audit/url-utils.test.ts
+++ b/src/server/lib/audit/url-utils.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
canonicalUrlKey,
detectUrlTemplate,
+ isAuditablePageUrl,
isSameOrigin,
normalizeUrl,
} from "@/server/lib/audit/url-utils";
@@ -57,3 +58,26 @@ describe("detectUrlTemplate", () => {
);
});
});
+
+describe("isAuditablePageUrl", () => {
+ it.each([
+ ["https://example.com/products/hat", undefined, true],
+ [
+ "https://example.com/cdn/shop/files/hat.jpg?v=1&width=1000",
+ undefined,
+ false,
+ ],
+ ["https://example.com/products/hat.json", undefined, false],
+ ["https://example.com/report.pdf", undefined, true],
+ [
+ "https://example.com/en/customer_authentication/redirect?locale=en",
+ "shopify",
+ false,
+ ],
+ ["https://example.com/discount/SAVE10?redirect=%2F", "shopify", false],
+ ["https://example.com/discount/SAVE10", undefined, true],
+ ["https://example.com/en/collections/all?page=2", "shopify", true],
+ ] as const)("isAuditablePageUrl(%s, %s) is %s", (url, platform, expected) => {
+ expect(isAuditablePageUrl(url, platform)).toBe(expected);
+ });
+});
diff --git a/src/server/lib/audit/url-utils.ts b/src/server/lib/audit/url-utils.ts
index f5175ba7..6fd0226f 100644
--- a/src/server/lib/audit/url-utils.ts
+++ b/src/server/lib/audit/url-utils.ts
@@ -156,3 +156,39 @@ export function detectUrlTemplate(pathname: string): string {
export function getOrigin(url: string): string {
return new URL(url).origin;
}
+
+/** Files a crawl can follow a link to but cannot audit as a page. */
+const NON_DOCUMENT_EXTENSIONS =
+ /\.(?:jpe?g|png|gif|webp|avif|svg|ico|bmp|tiff?|heic|woff2?|ttf|otf|eot|mp4|webm|m4v|mov|avi|mp3|wav|ogg|m4a|flac|css|js|mjs|json|xml|txt|map|zip|gz|tgz|tar|rar|7z|dmg|exe)$/i;
+
+/**
+ * Shopify routes that are never storefront pages and that its edge refuses to
+ * crawlers, with an optional locale prefix (`/en/`, `/pt-br/`). The cart,
+ * checkout and account routes need no entry: Shopify's robots.txt disallows
+ * them.
+ */
+const SHOPIFY_NON_PAGE_PATHS =
+ /^\/(?:[a-z]{2}(?:-[a-z]{2})?\/)?(?:customer_authentication\/|customer_identity\/|discount\/|password(?:\/|$))/i;
+
+/**
+ * Whether a same-origin URL is worth a page fetch. Links to images, fonts,
+ * scripts and other files pass the SSRF check but are not pages: Shopify
+ * themes link every gallery photo on the storefront origin, and one store's
+ * audit spent 1,986 of its 2,608 fetches on them. Unknown extensions pass.
+ * The trade: a broken link to such a file is no longer reported.
+ */
+export function isAuditablePageUrl(
+ url: string,
+ sitePlatform?: "shopify",
+): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ if (NON_DOCUMENT_EXTENSIONS.test(parsed.pathname)) return false;
+ return !(
+ sitePlatform === "shopify" && SHOPIFY_NON_PAGE_PATHS.test(parsed.pathname)
+ );
+}
diff --git a/src/server/workflows/site-audit-workflow-helpers.test.ts b/src/server/workflows/site-audit-workflow-helpers.test.ts
index 30e9bfe6..2c1ac6b7 100644
--- a/src/server/workflows/site-audit-workflow-helpers.test.ts
+++ b/src/server/workflows/site-audit-workflow-helpers.test.ts
@@ -64,25 +64,13 @@ describe("crawlPage", () => {
expect(page?.rateLimited).toBe(true);
});
- it("records a page the site keeps rate limiting, without calling it blocked", async () => {
- vi.useFakeTimers();
- const fetchMock = stubFetch({ status: 429, retryAfter: "1" });
-
- const crawled = crawl();
- await vi.advanceTimersByTimeAsync(30_000);
- const page = await crawled;
-
- expect(fetchMock).toHaveBeenCalledTimes(4);
- expect(page?.fetchClass).toBe("rate_limited");
- });
-
// A long Retry-After is deferred to a later chunk; one past the audit's
// whole cooldown budget is recorded as the page's final answer.
it.each([
["defers the URL when its cooldown outlasts the chunk", "600", null, false],
[
"records a final 429 when the wait exceeds the cooldown budget",
- "3600",
+ "8000",
"rate_limited",
true,
],
diff --git a/src/server/workflows/site-audit-workflow-helpers.ts b/src/server/workflows/site-audit-workflow-helpers.ts
index b2d47e34..6dfd443c 100644
--- a/src/server/workflows/site-audit-workflow-helpers.ts
+++ b/src/server/workflows/site-audit-workflow-helpers.ts
@@ -6,7 +6,7 @@ import type { PageFetchClass } from "@/shared/audit-fetch-class";
import { sha256Hex } from "@/server/lib/audit/ids";
import { normalizeUrl } from "@/server/lib/audit/url-utils";
import type { CrawlThrottle } from "@/server/lib/audit/crawl-throttle";
-import type { CrawlerAccess } from "@/shared/crawler-access";
+import { crawlerHeadersFor, type CrawlerAccess } from "@/shared/crawler-access";
import { auditRequestHeaders } from "@/server/lib/audit/web-bot-auth";
/** Parse `Link: <url>; rel="canonical"` response headers. */
@@ -26,9 +26,45 @@ function parseLinkHeaderCanonical(
}
/**
- * Fetch one URL, pausing the whole chunk and retrying while the site 429s
- * (see crawl-throttle.ts). `responseTimeMs` is measured from the last attempt
- * so backoff waiting never looks like a slow server.
+ * One warning per 429 so production shows what the edge answers: the
+ * Retry-After, how fast it came back (Shopify refuses at its edge within
+ * milliseconds), whether the request carried a crawler signature, and the
+ * body's first words (Shopify writes `local_rate_limited`).
+ */
+async function logRateLimited(input: {
+ url: string;
+ response: Response;
+ responseTimeMs: number;
+ attempt: number;
+ signed: boolean;
+}) {
+ const { url, response, responseTimeMs, attempt, signed } = input;
+ let body = "";
+ try {
+ body = (await readTextUpTo(response.clone(), 80)).trim();
+ } catch {
+ // The snippet is only context for the log line.
+ }
+ console.warn("site_audit:rate_limited", {
+ url,
+ attempt,
+ signed,
+ responseTimeMs,
+ retryAfter: response.headers.get("retry-after"),
+ // Shopify's edge answers warm pages from Cloudflare's cache without
+ // consulting its limiter; a HIT here would mean the 429 was cached.
+ cfCacheStatus: response.headers.get("cf-cache-status"),
+ // The two ids Shopify support asks for before it looks into a refusal.
+ xRequestId: response.headers.get("x-request-id"),
+ cfRay: response.headers.get("cf-ray"),
+ body,
+ });
+}
+
+/**
+ * Fetch one URL, pausing the whole chunk and retrying once while the site
+ * 429s (see crawl-throttle.ts). `responseTimeMs` is measured from the last
+ * attempt so backoff waiting never looks like a slow server.
*/
async function fetchPage(
url: string,
@@ -62,13 +98,20 @@ async function fetchPage(
rateLimited: attempt > 1,
};
if (response.status !== 429) {
- await throttle.recovered();
+ await throttle.recovered(url);
return result;
}
+ await logRateLimited({
+ url,
+ response,
+ responseTimeMs: result.responseTimeMs,
+ attempt,
+ signed: Object.keys(crawlerHeadersFor(url, access)).length > 0,
+ });
if (skipBackoff) return result;
const retry = await throttle.backoff(
- attempt,
+ url,
response.headers.get("retry-after"),
);
// The shared cooldown applies even when this URL has no retries left.
@@ -162,10 +205,11 @@ export async function crawlPage(
} catch (error) {
// A challenge that neither renderer passed stays blocked.
if (!challenged && !throttled) throw error;
- // A throttled page neither renderer read stays rate limited, and
- // pauses or stops the crawl like any other 429.
- if (throttled)
- await throttle.backoff(1, response.headers.get("retry-after"));
+ // A throttled page neither renderer read is given up on as rate
+ // limited, which pauses or stops the crawl like any other refusal.
+ if (throttled) {
+ await throttle.refuse(url, response.headers.get("retry-after"));
+ }
}
}
diff --git a/src/server/workflows/siteAuditWorkflowCrawl.test.ts b/src/server/workflows/siteAuditWorkflowCrawl.test.ts
index 6b38110b..8b346f82 100644
--- a/src/server/workflows/siteAuditWorkflowCrawl.test.ts
+++ b/src/server/workflows/siteAuditWorkflowCrawl.test.ts
@@ -178,7 +178,7 @@ describe("crawl pacing and cooldowns", () => {
expect(peak).toBe(2);
});
- it("retains slower pacing across chunks after recovering from the first 429", async () => {
+ it("slows down after a 429 and speeds back up once the site keeps serving", async () => {
const starts: number[] = [];
vi.spyOn(globalThis, "fetch").mockImplementation(async () => {
starts.push(Date.now());
@@ -191,9 +191,9 @@ describe("crawl pacing and cooldowns", () => {
await vi.runAllTimersAsync();
expect(await result).toEqual({ pagesCrawled: 100, completed: true });
expect(starts[1]).toBe(30_000);
- expect(starts.slice(2).every((at, i) => at - starts[i + 1] >= 2_000)).toBe(
- true,
- );
+ const gaps = starts.slice(1).map((at, i) => at - starts[i]);
+ expect(gaps.slice(1, 15).every((gap) => gap >= 2_000)).toBe(true);
+ expect(gaps.slice(-20).every((gap) => gap < 2_000)).toBe(true);
expect(saved.every((page) => page.fetchClass === "ok")).toBe(true);
expect(mocks.claimChunk.mock.calls.length).toBeGreaterThan(1);
});
@@ -277,20 +277,44 @@ describe("crawl pacing and cooldowns", () => {
expect(fetchMock).toHaveBeenCalledTimes(1);
});
- it("stops a permanently limited site after four refusals across chunks", async () => {
+ it("gives up on one refused URL and crawls the rest", async () => {
+ const refused = `${ORIGIN}/0`;
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockImplementation(async (input) => {
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ return new Response(HTML, {
+ status: input === refused ? 429 : 200,
+ headers: { "content-type": "text/html", "retry-after": "60" },
+ });
+ });
+ const result = crawl(50);
+ await vi.runAllTimersAsync();
+ expect(await result).toEqual({ pagesCrawled: 50, completed: true });
+ expect(
+ fetchMock.mock.calls.filter(([input]) => input === refused),
+ ).toHaveLength(2);
+ expect(saved.filter((page) => page.fetchClass === "rate_limited")).toEqual([
+ expect.objectContaining({ url: refused, statusCode: 429 }),
+ ]);
+ });
+
+ it("stops a permanently limited site after three URLs are refused across chunks", async () => {
const fetchMock = serve(() => 429);
const result = crawl();
await vi.runAllTimersAsync();
expect(await result).toMatchObject({ completed: false, rateLimited: true });
- expect(fetchMock).toHaveBeenCalledTimes(4);
- expect(saved).toHaveLength(1);
- expect(saved[0].fetchClass).toBe("rate_limited");
+ expect(fetchMock).toHaveBeenCalledTimes(6);
+ expect(saved).toHaveLength(3);
+ expect(saved.every((page) => page.fetchClass === "rate_limited")).toBe(
+ true,
+ );
expect(mocks.sleepUntil.mock.calls.length).toBeGreaterThan(0);
expect(mocks.releaseUrls).toHaveBeenCalled();
});
it("stops without sleeping or retrying early when Retry-After exceeds the cooldown budget", async () => {
- const fetchMock = serve(() => 429, "3600");
+ const fetchMock = serve(() => 429, "8000");
const result = crawl();
await vi.runAllTimersAsync();
expect(await result).toEqual({
diff --git a/src/server/workflows/siteAuditWorkflowCrawl.ts b/src/server/workflows/siteAuditWorkflowCrawl.ts
index 2eff9e77..d81222a5 100644
--- a/src/server/workflows/siteAuditWorkflowCrawl.ts
+++ b/src/server/workflows/siteAuditWorkflowCrawl.ts
@@ -2,7 +2,7 @@ import { env, type WorkflowStep } from "cloudflare:workers";
import { NonRetryableError } from "cloudflare:workflows";
import type { RobotsResult } from "@/server/lib/audit/discovery";
import type { AuditConfig, CrawledPageResult } from "@/server/lib/audit/types";
-import { isSameOrigin } from "@/server/lib/audit/url-utils";
+import { isAuditablePageUrl, isSameOrigin } from "@/server/lib/audit/url-utils";
import { isCrawlableUrl } from "@/server/lib/audit/url-policy";
import { deterministicAuditRowId } from "@/server/lib/audit/ids";
import { runPageReporters } from "@/server/lib/audit/issues/page-reporters";
@@ -79,9 +79,13 @@ function shouldQueueCrawlLink(
link: string,
origin: string,
robots: RobotsResult,
+ sitePlatform: AuditConfig["sitePlatform"],
): boolean {
return (
- isSameOrigin(link, origin) && isCrawlableUrl(link) && robots.isAllowed(link)
+ isSameOrigin(link, origin) &&
+ isCrawlableUrl(link) &&
+ isAuditablePageUrl(link, sitePlatform) &&
+ robots.isAllowed(link)
);
}
@@ -285,6 +289,7 @@ async function runCrawlChunk(
workflowInstanceId,
origin,
robots,
+ sitePlatform: input.sitePlatform,
scratchpad,
pages,
depthByUrl,
@@ -409,12 +414,21 @@ async function persistCrawledPages(input: {
workflowInstanceId: string;
origin: string;
robots: RobotsResult;
+ sitePlatform: AuditConfig["sitePlatform"];
scratchpad: ReturnType<typeof getAuditScratchpad>;
pages: CrawledPageResult[];
depthByUrl: Map<string, number | null>;
maxPages: number;
}): Promise<FrontierStats> {
- const { auditId, origin, robots, scratchpad, pages, depthByUrl } = input;
+ const {
+ auditId,
+ origin,
+ robots,
+ sitePlatform,
+ scratchpad,
+ pages,
+ depthByUrl,
+ } = input;
// Deterministic ids keep every write idempotent across step retries.
for (const page of pages) {
@@ -438,7 +452,7 @@ async function persistCrawledPages(input: {
if (
discovered.size < MAX_DISCOVERED_PER_BATCH &&
!discovered.has(link.targetUrl) &&
- shouldQueueCrawlLink(link.targetUrl, origin, robots)
+ shouldQueueCrawlLink(link.targetUrl, origin, robots, sitePlatform)
) {
discovered.set(link.targetUrl, childDepth);
}
@@ -451,7 +465,7 @@ async function persistCrawledPages(input: {
if (
page.redirectUrl &&
!discovered.has(page.redirectUrl) &&
- shouldQueueCrawlLink(page.redirectUrl, origin, robots)
+ shouldQueueCrawlLink(page.redirectUrl, origin, robots, sitePlatform)
) {
discovered.set(page.redirectUrl, pageDepth);
}
diff --git a/src/server/workflows/siteAuditWorkflowPhases.ts b/src/server/workflows/siteAuditWorkflowPhases.ts
index c2adc788..1bb36d0d 100644
--- a/src/server/workflows/siteAuditWorkflowPhases.ts
+++ b/src/server/workflows/siteAuditWorkflowPhases.ts
@@ -9,6 +9,7 @@ import {
} from "@/server/lib/audit/lighthouse";
import {
getOrigin,
+ isAuditablePageUrl,
isSameOrigin,
normalizeUrl,
} from "@/server/lib/audit/url-utils";
@@ -158,6 +159,7 @@ async function runDiscoveryPhase(
seen.add(normalized);
if (!isSameOrigin(normalized, origin)) continue;
if (!isCrawlableUrl(normalized)) continue;
+ if (!isAuditablePageUrl(normalized)) continue;
if (!robots.isAllowed(normalized)) continue;
seeds.push(normalized);
}
diff --git a/src/shared/audit-issues.ts b/src/shared/audit-issues.ts
index b6e1d2aa..e99c225f 100644
--- a/src/shared/audit-issues.ts
+++ b/src/shared/audit-issues.ts
@@ -36,7 +36,7 @@ export const AUDIT_ISSUE_TYPES = {
severity: "warning",
title: "Rate limited (429)",
explanation:
- "The server answered 429 Too Many Requests, so this page could not be audited. The crawler waits before retrying when the site's cooldown fits within the audit time limit.",
+ "The server answered 429 Too Many Requests, so this page could not be audited. The crawler paused for the server's Retry-After and tried the page once more before moving on.",
howToFix:
'Raise the rate limit for crawlers, or allowlist the "OpenSEO-Audit" user agent in your rate-limiting rules (on Cloudflare: a rate-limiting rule exception matching that user agent). Then re-run the audit. Re-running with fewer pages also helps if the limit is strict. On Shopify, use Crawler access instead (Online Store → Preferences → Crawler access) and paste the signature into OpenSEO under Settings → Crawler access. How to allow and verify the crawler: https://openseo.so/docs/crawler',
},
@@ -44,7 +44,7 @@ export const AUDIT_ISSUE_TYPES = {
severity: "warning",
title: "Crawl stopped early: rate limit",
explanation:
- "The site asked the crawler to wait longer than the audit time limit allowed. We stopped requesting pages. This report is incomplete; URLs we did not fetch are not recorded as broken or rate limited.",
+ "The site refused several pages in a row with 429 Too Many Requests, or kept the crawler waiting for too long, so we stopped requesting pages. This report is incomplete; URLs we did not fetch are not recorded as broken or rate limited.",
howToFix:
"Re-run the audit after the site's rate limit resets, or ask the site owner to allow the OpenSEO-Audit crawler (https://openseo.so/docs/crawler). On Shopify, use Crawler access instead (Online Store → Preferences → Crawler access) and paste the signature into OpenSEO under Settings → Crawler access.",
},
diff --git a/web/content/docs/crawler.md b/web/content/docs/crawler.md
index 1438c337..021f1927 100644
--- a/web/content/docs/crawler.md
+++ b/web/content/docs/crawler.md
@@ -32,7 +32,7 @@ Disallow: /
## Crawl rate
-The crawler sends about one request per second to a site, and an audit fetches a limited number of pages, set by the user who starts it. When a site answers with `429 Too Many Requests`, the crawler slows down and follows the `Retry-After` header before trying again. If the site keeps asking it to wait, the audit stops early.
+The crawler sends about one request per second to a site, and an audit fetches a limited number of pages, set by the user who starts it. When a site answers with `429 Too Many Requests`, the crawler pauses for the `Retry-After` header, slows down, and tries that page once more. A page refused again is reported as rate limited and the crawl moves on. If the site refuses several pages in a row, or keeps the crawler waiting for hours in total, the audit stops early. The crawler does not fetch links to images, scripts, fonts and other files.
## Allowing the crawler through a firewall