Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
fix(scrapeURL/fire-engine): turn off instantReturn
Gergő Móriczd1418c86e8c4
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/index.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/index.tsindex e65b77c47..b76ac075f 100644--- a/apps/api/src/scraper/scrapeURL/engines/fire-engine/index.ts+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/index.ts@@ -48,6 +48,7 @@ async function performFireEngineScrape<production = true,): Promise<FireEngineCheckStatusSuccess> {const scrape = await fireEngineScrape(+ meta,logger.child({ method: "fireEngineScrape" }),request,mock,@@ -55,89 +56,93 @@ async function performFireEngineScrape<production,);- const errorLimit = 3;- let errors: any[] = [];let status: FireEngineCheckStatusSuccess | undefined = undefined;+ if ((scrape as any).processing) {+ const errorLimit = 3;+ let errors: any[] = [];- while (status === undefined) {- if (errors.length >= errorLimit) {- logger.error("Error limit hit.", { errors });- fireEngineDelete(- logger.child({- method: "performFireEngineScrape/fireEngineDelete",- afterErrors: errors,- }),- scrape.jobId,- mock,- undefined,- production,- );- throw new Error("Error limit hit. See e.cause.errors for errors.", {- cause: { errors },- });- }-- meta.abort.throwIfAborted();-- try {- status = await fireEngineCheckStatus(- meta,- logger.child({ method: "fireEngineCheckStatus" }),- scrape.jobId,- mock,- abort,- production,- );- } catch (error) {- if (error instanceof StillProcessingError) {- // nop- } else if (- error instanceof EngineError ||- error instanceof SiteError ||- error instanceof SSLError ||- error instanceof DNSResolutionError ||- error instanceof ActionError ||- error instanceof UnsupportedFileError ||- error instanceof FEPageLoadFailed- ) {+ while (status === undefined) {+ if (errors.length >= errorLimit) {+ logger.error("Error limit hit.", { errors });fireEngineDelete(logger.child({method: "performFireEngineScrape/fireEngineDelete",- afterError: error,+ afterErrors: errors,}),- scrape.jobId,+ (scrape as any).jobId,mock,undefined,production,);- logger.debug("Fire-engine scrape job failed.", {- error,- jobId: scrape.jobId,+ throw new Error("Error limit hit. See e.cause.errors for errors.", {+ cause: { errors },});- throw error;- } else if (error instanceof AbortManagerThrownError) {- fireEngineDelete(- logger.child({- method: "performFireEngineScrape/fireEngineDelete",- afterError: error,- }),- scrape.jobId,+ }++ meta.abort.throwIfAborted();++ try {+ status = await fireEngineCheckStatus(+ meta,+ logger.child({ method: "fireEngineCheckStatus" }),+ (scrape as any).jobId,mock,- undefined,+ abort,production,);- throw error;- } else {- errors.push(error);- logger.debug(- `An unexpeceted error occurred while calling checkStatus. Error counter is now at ${errors.length}.`,- { error, jobId: scrape.jobId },- );- Sentry.captureException(error);+ } catch (error) {+ if (error instanceof StillProcessingError) {+ // nop+ } else if (+ error instanceof EngineError ||+ error instanceof SiteError ||+ error instanceof SSLError ||+ error instanceof DNSResolutionError ||+ error instanceof ActionError ||+ error instanceof UnsupportedFileError ||+ error instanceof FEPageLoadFailed+ ) {+ fireEngineDelete(+ logger.child({+ method: "performFireEngineScrape/fireEngineDelete",+ afterError: error,+ }),+ (scrape as any).jobId,+ mock,+ undefined,+ production,+ );+ logger.debug("Fire-engine scrape job failed.", {+ error,+ jobId: (scrape as any).jobId,+ });+ throw error;+ } else if (error instanceof AbortManagerThrownError) {+ fireEngineDelete(+ logger.child({+ method: "performFireEngineScrape/fireEngineDelete",+ afterError: error,+ }),+ (scrape as any).jobId,+ mock,+ undefined,+ production,+ );+ throw error;+ } else {+ errors.push(error);+ logger.debug(+ `An unexpeceted error occurred while calling checkStatus. Error counter is now at ${errors.length}.`,+ { error, jobId: (scrape as any).jobId },+ );+ Sentry.captureException(error);+ }}}await new Promise((resolve) => setTimeout(resolve, 500));+ } else {+ status = scrape as FireEngineCheckStatusSuccess;}await specialtyScrapeCheck(@@ -166,7 +171,7 @@ async function performFireEngineScrape<logger.child({method: "performFireEngineScrape/fireEngineDelete",}),- scrape.jobId,+ (scrape as any).jobId,mock,undefined,production,@@ -214,7 +219,7 @@ export async function scrapeURLWithFireEngineChromeCDP(FireEngineScrapeRequestChromeCDP = {url: meta.rewrittenUrl ?? meta.url,engine: "chrome-cdp",- instantReturn: true,+ instantReturn: false,skipTlsVerification: meta.options.skipTlsVerification,headers: meta.options.headers,...(actions.length > 0@@ -302,7 +307,7 @@ export async function scrapeURLWithFireEnginePlaywright(FireEngineScrapeRequestPlaywright = {url: meta.rewrittenUrl ?? meta.url,engine: "playwright",- instantReturn: true,+ instantReturn: false,headers: meta.options.headers,priority: meta.internalOptions.priority,@@ -364,7 +369,7 @@ export async function scrapeURLWithFireEngineTLSClient(FireEngineScrapeRequestTLSClient = {url: meta.rewrittenUrl ?? meta.url,engine: "tlsclient",- instantReturn: true,+ instantReturn: false,headers: meta.options.headers,priority: meta.internalOptions.priority,diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/scrape.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/scrape.tsindex fed212dcf..bad00d0a4 100644--- a/apps/api/src/scraper/scrapeURL/engines/fire-engine/scrape.ts+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/scrape.ts@@ -5,6 +5,9 @@ import { z } from "zod";import { Action } from "../../../../controllers/v1/types";import { robustFetch } from "../../lib/fetch";import { MockState } from "../../lib/mock";+import { getDocFromGCS } from "../../../../lib/gcs-jobs";+import { ActionError, DNSResolutionError, EngineError, FEPageLoadFailed, SSLError, SiteError, UnsupportedFileError } from "../../error";+import { Meta } from "../..";export type FireEngineScrapeRequestCommon = {url: string;@@ -59,11 +62,98 @@ export type FireEngineScrapeRequestTLSClient = {disableJsDom?: boolean; // v0 only, default: false};-const schema = z.object({+const successSchema = z.object({+ timeTaken: z.number(),+ content: z.string(),+ url: z.string().optional(),++ pageStatusCode: z.number(),+ pageError: z.string().optional(),++ // TODO: this needs to be non-optional, might need fixes on f-e side to ensure reliability+ responseHeaders: z.record(z.string(), z.string()).optional(),++ // timeTakenCookie: z.number().optional(),+ // timeTakenRequest: z.number().optional(),++ // legacy: playwright only+ screenshot: z.string().optional(),++ // new: actions+ screenshots: z.string().array().optional(),+ actionContent: z+ .object({+ url: z.string(),+ html: z.string(),+ })+ .array()+ .optional(),+ actionResults: z.union([+ z.object({+ idx: z.number(),+ type: z.literal("screenshot"),+ result: z.object({+ path: z.string(),+ }),+ }),+ z.object({+ idx: z.number(),+ type: z.literal("scrape"),+ result: z.union([+ z.object({+ url: z.string(),+ html: z.string(),+ }),+ z.object({+ url: z.string(),+ accessibility: z.string(),+ }),+ ]),+ }),+ z.object({+ idx: z.number(),+ type: z.literal("executeJavascript"),+ result: z.object({+ return: z.string(),+ }),+ }),+ z.object({+ idx: z.number(),+ type: z.literal("pdf"),+ result: z.object({+ link: z.string(),+ }),+ }),+ ]).array().optional(),++ // chrome-cdp only -- file download handler+ file: z+ .object({+ name: z.string(),+ content: z.string(),+ })+ .optional()+ .or(z.null()),++ docUrl: z.string().optional(),++ usedMobileProxy: z.boolean().optional(),+});++export type FireEngineCheckStatusSuccess = z.infer<typeof successSchema>;++const processingSchema = z.object({jobId: z.string(),processing: z.boolean(),});+const failedSchema = z.object({+ jobId: z.string(),+ state: z.literal("failed"),+ processing: z.literal(false),+ error: z.string(),+});+export const fireEngineURL = process.env.FIRE_ENGINE_BETA_URL ?? "<mock-fire-engine-url>";export const fireEngineStagingURL = process.env.FIRE_ENGINE_STAGING_URL ?? "<mock-fire-engine-url>";@@ -73,23 +163,98 @@ export async function fireEngineScrape<| FireEngineScrapeRequestPlaywright| FireEngineScrapeRequestTLSClient,>(+ meta: Meta,logger: Logger,request: FireEngineScrapeRequestCommon & Engine,mock: MockState | null,abort?: AbortSignal,production = true,-): Promise<z.infer<typeof schema>> {- const scrapeRequest = await robustFetch({+): Promise<z.infer<typeof processingSchema> | FireEngineCheckStatusSuccess> {+ let status = await robustFetch({url: `${production ? fireEngineURL : fireEngineStagingURL}/scrape`,method: "POST",headers: {},body: request,logger: logger.child({ method: "fireEngineScrape/robustFetch" }),- schema,tryCount: 3,mock,abort,});- return scrapeRequest;+ // Fire-engine now saves the content to GCS+ if (!status.content && status.docUrl) {+ const doc = await getDocFromGCS(status.docUrl.split('/').pop() ?? "");+ if (doc) {+ status = { ...status, ...doc };+ delete status.docUrl;+ }+ }++ const successParse = successSchema.safeParse(status);+ const processingParse = processingSchema.safeParse(status);+ const failedParse = failedSchema.safeParse(status);++ if (successParse.success) {+ logger.debug("Scrape succeeded!");+ return successParse.data;+ } else if (processingParse.success) {+ return processingParse.data;+ } else if (failedParse.success) {+ logger.debug("Scrape job failed", { status, jobId: failedParse.data.jobId });+ if (+ typeof status.error === "string" &&+ status.error.includes("Chrome error: ")+ ) {+ const code = status.error.split("Chrome error: ")[1];++ if (code.includes("ERR_CERT_") || code.includes("ERR_SSL_") || code.includes("ERR_BAD_SSL_")) {+ throw new SSLError(meta.options.skipTlsVerification);+ } else {+ throw new SiteError(code);+ }+ } else if (+ typeof status.error === "string" &&+ status.error.includes("Dns resolution error for hostname: ")+ ) {+ throw new DNSResolutionError(status.error.split("Dns resolution error for hostname: ")[1]);+ } else if (+ typeof status.error === "string" &&+ status.error.includes("File size exceeds")+ ) {+ throw new UnsupportedFileError(+ "File size exceeds " + status.error.split("File size exceeds ")[1],+ );+ } else if (+ typeof status.error === "string" &&+ status.error.includes("failed to finish without timing out")+ ) {+ logger.warn("CDP timed out while loading the page", { status, jobId: failedParse.data.jobId });+ throw new FEPageLoadFailed();+ } else if (+ typeof status.error === "string" &&+ // TODO: improve this later+ (status.error.includes("Element") || status.error.includes("Javascript execution failed"))+ ) {+ throw new ActionError(status.error.split("Error: ")[1]);+ } else {+ throw new EngineError("Scrape job failed", {+ cause: {+ status,+ jobId: failedParse.data.jobId,+ },+ });+ }+ } else {+ logger.debug("Scrape returned response not matched by any schema", {+ status,+ });+ throw new Error(+ "Check status returned response not matched by any schema",+ {+ cause: {+ status,+ },+ },+ );+ }}diff --git a/apps/api/src/scraper/scrapeURL/lib/fetch.ts b/apps/api/src/scraper/scrapeURL/lib/fetch.tsindex 9c5798b5d..89a3db4ce 100644--- a/apps/api/src/scraper/scrapeURL/lib/fetch.ts+++ b/apps/api/src/scraper/scrapeURL/lib/fetch.ts@@ -18,6 +18,7 @@ export type RobustFetchParams<Schema extends z.Schema<any>> = {dontParseResponse?: boolean;ignoreResponse?: boolean;ignoreFailure?: boolean;+ ignoreFailureStatus?: boolean;requestId?: string;tryCount?: number;tryCooldown?: number;@@ -54,6 +55,7 @@ export async function robustFetch<schema,ignoreResponse = false,ignoreFailure = false,+ ignoreFailureStatus = false,requestId = crypto.randomUUID(),tryCount = 1,tryCooldown,@@ -203,7 +205,7 @@ export async function robustFetch<};}- if (response.status >= 300) {+ if (response.status >= 300 && !ignoreFailureStatus) {if (tryCount > 1) {logger.debug("Request sent failure status, trying " + (tryCount - 1) + " more times",