Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

9.8 KB
Raw Blame
import type { Dictionary } from '@crawlee/types';

import type { CrawleeLogger } from '../log.js';
import type { Request, Source } from '../request.js';
import { serviceLocator } from '../service-locator.js';
import type { IRequestLoader, RequestSourceStatus } from './request-loader.js';
import { joinRequestSourceStatuses } from './request-loader.js';
import type { IRequestManager, PacingSignal, RequestsLike } from './request-manager.js';
import type {
    AddRequestsBatchedOptions,
    AddRequestsBatchedResult,
    RequestQueueOperationInfo,
    RequestQueueOperationOptions,
} from './request-queue.js';

/**
 * A request manager that combines a {@apilink IRequestLoader} (such as a `RequestList`) with a writable
 * {@apilink IRequestManager} (such as a `RequestQueue`).
 * It first reads requests from the loader and then, when needed, transfers them in batches to the manager.
 */
export class RequestManagerTandem implements IRequestManager {
    #log: CrawleeLogger;
    #requestLoader: IRequestLoader;
    #requestManagerPromise?: Promise<IRequestManager>;
    #resolvedRequestManager?: IRequestManager;

    #requestManagerFactory: () => IRequestManager | Promise<IRequestManager>;

    /**
     * The latest expected request-processing time hinted via {@link setExpectedRequestProcessingTime}.
     * Remembered so it can be applied to the writable manager once it is lazily resolved.
     */
    #expectedRequestProcessingSecs?: number;

    /**
     * @param requestLoader The read-only loader to read requests from first.
     * @param requestManager The writable manager to transfer requests into and enqueue new ones. May be passed as a
     *  factory function so that the tandem can be constructed synchronously and the manager opened lazily on first use
     *  (e.g. a lazily-opened default {@apilink RequestQueue}).
     */
    constructor(
        requestLoader: IRequestLoader,
        requestManager: IRequestManager | (() => IRequestManager | Promise<IRequestManager>),
    ) {
        this.#log = serviceLocator.getLogger().child({ prefix: 'RequestManagerTandem' });
        this.#requestLoader = requestLoader;

        if (typeof requestManager === 'function') {
            this.#requestManagerFactory = requestManager;
        } else {
            // Nothing to open, so mark it resolved up front - synchronous pacing signals can then reach it.
            this.#resolvedRequestManager = requestManager;
            this.#requestManagerFactory = () => requestManager;
        }
    }

    /**
     * Resolves the writable request manager, opening it lazily (via the factory) on first use and memoizing the result.
     */
    async #getRequestManager(): Promise<IRequestManager> {
        if (this.#resolvedRequestManager === undefined) {
            this.#requestManagerPromise ??= Promise.resolve(this.#requestManagerFactory());
            this.#resolvedRequestManager = await this.#requestManagerPromise;

            // Apply any hint received before the manager was resolved.
            if (this.#expectedRequestProcessingSecs !== undefined) {
                await this.#resolvedRequestManager.setExpectedRequestProcessingTime?.(
                    this.#expectedRequestProcessingSecs,
                );
            }
        }
        return this.#resolvedRequestManager;
    }

    /**
     * Transfers a single request from the read-only loader to the writable manager.
     * If the transfer fails, the request is dropped (and logged) rather than reclaimed.
     *
     * @returns `true` if a request was successfully transferred (or there was nothing to transfer), and `false` if a
     *  transfer was attempted but failed - in which case the caller should not fetch from the manager this round.
     */
    async #transferNextRequestToQueue(): Promise<boolean> {
        const request = await this.#requestLoader.fetchNextRequest();

        if (request === null) {
            return true;
        }

        const requestManager = await this.#getRequestManager();

        try {
            await requestManager.addRequest(request, { forefront: true });
            return true;
        } catch (error) {
            this.#log.exception(
                error as Error,
                'Adding request from the RequestLoader to the RequestManager failed, the request has been dropped.',
                { url: request.url, uniqueKey: request.uniqueKey },
            );
            return false;
        } finally {
            // Mark it as handled so that the request doesn't get stuck in the `inProgress` state in the loader.
            await this.#requestLoader.markRequestAsHandled(request);
        }
    }

    /**
     * Fetches the next request, transferring one from the loader first if the loader still has work.
     * @inheritdoc
     */
    async fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null> {
        // Only the loader's own state decides this: a manager waiting out a backoff must not freeze the
        // loader's unrelated requests for the length of it.
        if ((await this.#requestLoader.checkReadiness()).status === 'ready') {
            // If the transfer failed, the request was dropped; don't fetch from the manager this round (matching
            // crawlee-python behaviour). The next `fetchNextRequest()` call will pick up where we left off.
            if (!(await this.#transferNextRequestToQueue())) {
                return null;
            }
        }

        // Try to fetch from manager after the transfer
        return (await this.#getRequestManager()).fetchNextRequest<T>();
    }

    /**
     * The loader and the manager read as one source.
     * @inheritdoc
     */
    async checkReadiness(): Promise<RequestSourceStatus> {
        const requestManager = await this.#getRequestManager();
        const [loaderStatus, managerStatus] = await Promise.all([
            this.#requestLoader.checkReadiness(),
            requestManager.checkReadiness(),
        ]);

        return joinRequestSourceStatuses(loaderStatus, managerStatus);
    }

    /**
     * @inheritdoc
     */
    async getHandledCount(): Promise<number> {
        // Since one of the stores needs to have priority when both are present, we query the request manager - the request loader will first be dumped into the manager and then left empty.
        return (await this.#getRequestManager()).getHandledCount();
    }

    /**
     * @inheritdoc
     */
    async getTotalCount(): Promise<number> {
        const requestManager = await this.#getRequestManager();
        const [managerTotal, loaderTotal] = await Promise.all([
            requestManager.getTotalCount(),
            // count only pending to avoid double counting, requests marked as "handled" have been moved to requestManager
            this.#requestLoader.getPendingCount(),
        ]);
        return managerTotal + loaderTotal;
    }

    /**
     * @inheritdoc
     */
    async getPendingCount(): Promise<number> {
        const requestManager = await this.#getRequestManager();
        const [managerPending, loaderPending] = await Promise.all([
            requestManager.getPendingCount(),
            this.#requestLoader.getPendingCount(),
        ]);
        return managerPending + loaderPending;
    }

    /**
     * @inheritdoc
     */
    async *[Symbol.asyncIterator]() {
        while (true) {
            const req = await this.fetchNextRequest();
            if (!req) break;
            yield req;
        }
    }

    /**
     * @inheritdoc
     */
    async markRequestAsHandled(request: Request): Promise<RequestQueueOperationInfo | void | null> {
        return (await this.#getRequestManager()).markRequestAsHandled(request);
    }

    /**
     * @inheritdoc
     */
    async reclaimRequest(
        request: Request,
        options?: RequestQueueOperationOptions,
    ): Promise<RequestQueueOperationInfo | null> {
        return (await this.#getRequestManager()).reclaimRequest(request, options);
    }

    /**
     * @inheritdoc
     */
    async addRequest(requestLike: Source, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo> {
        return (await this.#getRequestManager()).addRequest(requestLike, options);
    }

    /**
     * @inheritdoc
     */
    async addRequestsBatched(
        requests: RequestsLike,
        options?: AddRequestsBatchedOptions,
    ): Promise<AddRequestsBatchedResult> {
        return (await this.#getRequestManager()).addRequestsBatched(requests, options);
    }

    /**
     * Purges the writable request manager so the tandem can be reused (e.g. across repeated `crawler.run()` calls).
     * The read-only loader is immutable and cannot be purged, so only the manager side is reset.
     * @inheritdoc
     */
    async purge(): Promise<void> {
        await (await this.#getRequestManager()).purge?.();
    }

    /**
     * Forwards the hint to the writable request manager — that is where requests are fetched from and
     * reserved. The manager is opened lazily, so the value is remembered and applied once it resolves.
     * @inheritdoc
     */
    async setExpectedRequestProcessingTime(processingTimeSecs: number): Promise<void> {
        this.#expectedRequestProcessingSecs = processingTimeSecs;
        await this.#resolvedRequestManager?.setExpectedRequestProcessingTime?.(processingTimeSecs);
    }

    /**
     * Forwards a pacing signal to the writable manager - the loader side is read-only and dispatches nothing of
     * its own. Only a resolved manager is signalled; the tandem will not open a queue to answer a question about
     * pacing.
     * @inheritdoc
     */
    recordPacingSignal(signal: PacingSignal): boolean {
        return this.#resolvedRequestManager?.recordPacingSignal(signal) ?? false;
    }

    async extendRequestProcessingTime(request: Request, extensionSecs: number): Promise<boolean> {
        return (await this.#getRequestManager()).extendRequestProcessingTime?.(request, extensionSecs) ?? false;
    }
}