Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 55 additions & 10 deletions packages/basic-crawler/src/internals/throttling-request-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,18 @@ interface DomainState {
backoffUntil: number;
/** Earliest dispatch time imposed by the domain's crawl delay, as a `Date.now()` timestamp. */
crawlDelayUntil: number;
/**
* Monotonic token incremented whenever a fetch arms a `crawlDelayUntil` reservation or `purge()` resets it,
* so an empty or failed fetch only rolls back its own reservation and never clobbers a newer one.
*/
crawlDelayReservation: number;
/** Time after which an incoming 429 is treated as a fresh burst rather than a continuation. */
backoffDecaysAt: number;
consecutive429Count: number;
/** The `Crawl-delay` this domain's robots.txt asked for, if any - a floor, not the whole story. */
/** The longest `Crawl-delay` this domain's robots.txt asked for, if any - a floor, not the whole story. */
declaredCrawlDelayMs: number | null;
/** When the domain last dispatched a request, as a `Date.now()` timestamp, or `null` if it never has. */
lastDispatchedAt: number | null;
/**
* When the current unbroken run of 429s began, as a `Date.now()` timestamp, or `0` if the domain is not
* currently rate-limiting us. Cleared the moment a request gets through, so it measures how long we have
Expand Down Expand Up @@ -222,9 +229,11 @@ function newDomainState(domain: string): DomainState {
domain,
backoffUntil: 0,
crawlDelayUntil: 0,
crawlDelayReservation: 0,
backoffDecaysAt: 0,
consecutive429Count: 0,
declaredCrawlDelayMs: null,
lastDispatchedAt: null,
rateLimitedSince: 0,
lastRateLimitedAt: 0,
};
Expand Down Expand Up @@ -779,7 +788,9 @@ export class ThrottlingRequestManager<T extends IRequestManager = IRequestManage
* Records a declared minimum interval for a domain, which becomes its crawl delay unless
* {@apilink ThrottlingRequestManagerOptions.minCrawlDelaySecs|`minCrawlDelaySecs`} asks for longer.
*
* The first value wins, so a robots.txt re-fetch cannot change the cadence mid-crawl.
* The longest value wins, so a site with different delays across covered origins (e.g. subdomains
* sharing one domain clock) is paced by the most conservative `Crawl-delay`, and any active cooldown
* from the last dispatch is extended to match.
*
* @returns `false` if the domain is not throttled, in which case this is a no-op.
*/
Expand All @@ -794,9 +805,17 @@ export class ThrottlingRequestManager<T extends IRequestManager = IRequestManage
// the sub-queue it will end up pacing.
const state = this.#ensureDomainState(domain);

if (state.declaredCrawlDelayMs === null) {
if (state.declaredCrawlDelayMs === null || intervalMs > state.declaredCrawlDelayMs) {
const verb = state.declaredCrawlDelayMs === null ? 'Set' : 'Raised';
state.declaredCrawlDelayMs = intervalMs;
this.#log.debug(`Set crawl-delay for domain "${state.domain}" to ${(intervalMs / 1000).toFixed(1)}s`);
this.#log.debug(`${verb} crawl-delay for domain "${state.domain}" to ${(intervalMs / 1000).toFixed(1)}s`);

if (state.lastDispatchedAt !== null) {
const effectiveDelayMs = crawlDelayMs(state, this.#minCrawlDelayMs);
if (effectiveDelayMs > 0) {
state.crawlDelayUntil = Math.max(state.crawlDelayUntil, state.lastDispatchedAt + effectiveDelayMs);
}
}
}

return true;
Expand Down Expand Up @@ -1076,6 +1095,8 @@ export class ThrottlingRequestManager<T extends IRequestManager = IRequestManage
state.consecutive429Count = 0;
state.backoffUntil = 0;
state.crawlDelayUntil = 0;
state.crawlDelayReservation += 1;
state.lastDispatchedAt = null;
state.backoffDecaysAt = 0;
state.rateLimitedSince = 0;
state.lastRateLimitedAt = 0;
Expand Down Expand Up @@ -1141,20 +1162,44 @@ export class ThrottlingRequestManager<T extends IRequestManager = IRequestManage

// Armed while the fetch below is still suspended, so that a concurrent `fetchNextRequest` cannot
// find the domain fetchable and dispatch into the same window - which would pace each task
// rather than the domain.
// rather than the domain. `lastDispatchedAt` is updated only once a request is actually dequeued,
// so an empty or failed fetch can neither trigger a phantom extension nor clobber a newer dispatch.
const crawlDelayUntilBefore = state.crawlDelayUntil;
const now = Date.now();
const delayMs = crawlDelayMs(state, this.#minCrawlDelayMs);
let reservation: number | undefined;
if (delayMs > 0) {
state.crawlDelayUntil = Date.now() + delayMs;
state.crawlDelayReservation += 1;
reservation = state.crawlDelayReservation;
state.crawlDelayUntil = Math.max(state.crawlDelayUntil, now + delayMs);
}

let request: Request<R> | null = null;
try {
request = await (await this.#subManagers.get(domain)!).fetchNextRequest<R>(options);
} finally {
if (request) {
state.lastDispatchedAt =
state.lastDispatchedAt === null ? now : Math.max(state.lastDispatchedAt, now);
const currentDelayMs = crawlDelayMs(state, this.#minCrawlDelayMs);
if (currentDelayMs > 0) {
state.crawlDelayUntil = Math.max(state.crawlDelayUntil, now + currentDelayMs);
}
} else if (reservation !== undefined && state.crawlDelayReservation === reservation) {
// No dispatch to pace, so release our reservation unless a newer reservation or purge replaced it,
// while keeping any cooldown extension anchored to an earlier confirmed dispatch.
const currentDelayMs = crawlDelayMs(state, this.#minCrawlDelayMs);
const lastDispatchFloor =
state.lastDispatchedAt !== null && currentDelayMs > 0
? state.lastDispatchedAt + currentDelayMs
: 0;
state.crawlDelayUntil = Math.max(crawlDelayUntilBefore, lastDispatchFloor);
}
}

const request = await (await this.#subManagers.get(domain)!).fetchNextRequest<R>(options);
if (request) {
return request;
}

// No dispatch to pace, so the domain keeps its slot.
state.crawlDelayUntil = crawlDelayUntilBefore;
}

const request = await this.#fetchFromInner<R>(options);
Expand Down
Loading
Loading