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
feat(search): remove NuQ queue and execute scrapes directly without concurrency limits (#2668)
Abimael Martell1f85a44a411a
diff --git a/apps/api/src/controllers/v1/search.ts b/apps/api/src/controllers/v1/search.tsindex 4f684acb3..88f322937 100644--- a/apps/api/src/controllers/v1/search.ts+++ b/apps/api/src/controllers/v1/search.ts@@ -6,33 +6,25 @@ import {SearchRequest,SearchResponse,searchRequestSchema,- ScrapeOptions,- TeamFlags,} from "./types";import { billTeam } from "../../services/billing/credit_billing";import { v7 as uuidv7 } from "uuid";-import { addScrapeJob, waitForJob } from "../../services/queue-jobs";import { logSearch, logRequest } from "../../services/logging/log_job";import { search } from "../../search";-import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";-import { BLOCKLISTED_URL_MESSAGE } from "../../lib/strings";import { logger as _logger } from "../../lib/logger";import type { Logger } from "winston";-import { getJobPriority } from "../../lib/job-priority";-import { CostTracking } from "../../lib/cost-tracking";-import { supabase_service } from "../../services/supabase";-import { fromV1ScrapeOptions } from "../v2/types";import { ScrapeJobTimeoutError } from "../../lib/error";-import { scrapeQueue } from "../../services/worker/nuq";+import { captureExceptionWithZdrCheck } from "../../services/sentry";+import { executeSearch } from "../../search/execute";import {- applyZdrScope,- captureExceptionWithZdrCheck,-} from "../../services/sentry";--interface DocumentWithCostTracking {- document: Document;- costTracking: ReturnType<typeof CostTracking.prototype.toJSON>;-}+ DocumentWithCostTracking,+ scrapeSearchResults,+} from "../../search/scrape";+import {+ transformToV1Response,+ filterDocumentsWithContent,+} from "../../search/transform";+import { fromV1ScrapeOptions } from "../v2/types";// Used for deep researchexport async function searchAndScrapeSearchResult(@@ -41,12 +33,12 @@ export async function searchAndScrapeSearchResult(teamId: string;origin: string;timeout: number;- scrapeOptions: ScrapeOptions;+ scrapeOptions: any;apiKeyId: number | null;requestId?: string;},logger: Logger,- flags: TeamFlags,+ flags: any,): Promise<DocumentWithCostTracking[]> {try {const searchResults = await search({@@ -55,174 +47,31 @@ export async function searchAndScrapeSearchResult(num_results: 5,});- const documentsWithCostTracking = await Promise.all(- searchResults.map(result =>- scrapeSearchResult(- {- url: result.url,- title: result.title,- description: result.description,- },- options,- logger,- flags,- ),- ),- );-- return documentsWithCostTracking;- } catch (error) {- return [];- }-}--async function scrapeSearchResult(- searchResult: { url: string; title: string; description: string },- options: {- teamId: string;- origin: string;- timeout: number;- scrapeOptions: ScrapeOptions;- apiKeyId: number | null;- requestId?: string;- },- logger: Logger,- flags: TeamFlags,- directToBullMQ: boolean = false,- isSearchPreview: boolean = false,-): Promise<DocumentWithCostTracking> {- const jobId = uuidv7();-- const costTracking = new CostTracking();-- const zeroDataRetention = flags?.forceZDR ?? false;- applyZdrScope(zeroDataRetention);-- try {- if (isUrlBlocked(searchResult.url, flags)) {- throw new Error("Could not scrape url: " + BLOCKLISTED_URL_MESSAGE);- }- logger.info("Adding scrape job", {- scrapeId: jobId,- url: searchResult.url,- teamId: options.teamId,- origin: options.origin,- zeroDataRetention,- });-- const { scrapeOptions, internalOptions } = fromV1ScrapeOptions(+ const { scrapeOptions } = fromV1ScrapeOptions(options.scrapeOptions,options.timeout,options.teamId,);- const jobPriority = await getJobPriority({- team_id: options.teamId,- basePriority: 10,- });-- await addScrapeJob(+ return await scrapeSearchResults(+ searchResults.map(r => ({+ url: r.url,+ title: r.title,+ description: r.description,+ })),{- url: searchResult.url,- mode: "single_urls",- team_id: options.teamId,- scrapeOptions: {- ...scrapeOptions,- maxAge:- scrapeOptions.maxAge === 0- ? 3 * 24 * 60 * 60 * 1000- : scrapeOptions.maxAge,- },- internalOptions: {- ...internalOptions,- teamId: options.teamId,- bypassBilling: false, // Scrape jobs always bill themselves- zeroDataRetention,- },+ teamId: options.teamId,origin: options.origin,- startTime: Date.now(),- zeroDataRetention,+ timeout: options.timeout,+ scrapeOptions,apiKeyId: options.apiKeyId,requestId: options.requestId,},- jobId,- jobPriority,- directToBullMQ,- true,- );-- const doc: Document = await waitForJob(- jobId,- options.timeout,- zeroDataRetention,+ logger,+ flags,);-- logger.info("Scrape job completed", {- scrapeId: jobId,- url: searchResult.url,- teamId: options.teamId,- origin: options.origin,- });- await scrapeQueue.removeJob(jobId, logger);-- const document = {- title: searchResult.title,- description: searchResult.description,- url: searchResult.url,- ...doc,- };-- let costTracking: ReturnType<typeof CostTracking.prototype.toJSON>;- if (config.USE_DB_AUTHENTICATION) {- const { data: costTrackingResponse, error: costTrackingError } =- await supabase_service- .from("scrapes")- .select("cost_tracking")- .eq("id", jobId);-- if (costTrackingError) {- logger.error("Error getting cost tracking", {- error: costTrackingError,- });- throw costTrackingError;- }-- costTracking = costTrackingResponse?.[0]?.cost_tracking;- } else {- costTracking = new CostTracking().toJSON();- }-- return {- document,- costTracking,- };} catch (error) {- logger.error(`Error in scrapeSearchResult: ${error}`, {- scrapeId: jobId,- url: searchResult.url,- teamId: options.teamId,- });-- let statusCode = 0;- if (error?.message?.includes("Could not scrape url")) {- statusCode = 403;- }-- const document: Document = {- title: searchResult.title,- description: searchResult.description,- url: searchResult.url,- metadata: {- statusCode,- error: error.message,- proxyUsed: "basic",- },- };-- return {- document,- costTracking: new CostTracking().toJSON(),- };+ return [];}}@@ -230,7 +79,6 @@ export async function searchController(req: RequestWithAuth<{}, SearchResponse, SearchRequest>,res: Response<SearchResponse>,) {- // Get timing data from middleware (includes all middleware processing time)const middlewareStartTime =(req as any).requestTiming?.startTime || new Date().getTime();const controllerStartTime = new Date().getTime();@@ -263,9 +111,6 @@ export async function searchController(config.SEARCH_PREVIEW_TOKEN !== undefined &&config.SEARCH_PREVIEW_TOKEN === req.body.__searchPreviewToken;- let credits_billed = 0;- let allDocsWithCostTracking: DocumentWithCostTracking[] = [];-try {req.body = searchRequestSchema.parse(req.body);@@ -283,91 +128,57 @@ export async function searchController(origin: req.body.origin ?? "api",integration: req.body.integration,target_hint: req.body.query,- zeroDataRetention: false, // not supported for search+ zeroDataRetention: false,api_key_id: req.acuc?.api_key_id ?? null,});- let limit = req.body.limit;-- // Buffer results by 50% to account for filtered URLs- const num_results_buffer = Math.floor(limit * 2);+ // Convert v1 scrape options to v2 format+ const { scrapeOptions } = fromV1ScrapeOptions(+ req.body.scrapeOptions,+ req.body.timeout,+ req.auth.team_id,+ );- logger.info("Searching for results");+ // Check if scraping is requested+ const shouldScrape =+ req.body.scrapeOptions.formats &&+ req.body.scrapeOptions.formats.length > 0;- let searchResults = await search({- query: req.body.query,+ // Execute search using v2 logic+ const result = await executeSearch(+ {+ query: req.body.query,+ limit: req.body.limit,+ tbs: req.body.tbs,+ filter: req.body.filter,+ lang: req.body.lang,+ country: req.body.country,+ location: req.body.location,+ sources: [{ type: "web" }], // v1 only supports web+ scrapeOptions: shouldScrape ? scrapeOptions : undefined,+ timeout: req.body.timeout,+ },+ {+ teamId: req.auth.team_id,+ origin: req.body.origin,+ apiKeyId: req.acuc?.api_key_id ?? null,+ flags: req.acuc?.flags ?? null,+ requestId: jobId,+ bypassBilling: false,+ zeroDataRetention: false,+ },logger,- advanced: false,- num_results: num_results_buffer,- tbs: req.body.tbs,- filter: req.body.filter,- lang: req.body.lang,- country: req.body.country,- location: req.body.location,- });-- if (req.body.ignoreInvalidURLs) {- searchResults = searchResults.filter(- result => !isUrlBlocked(result.url, req.acuc?.flags ?? null),- );- }-- logger.info("Searching completed", {- num_results: searchResults.length,- });+ );- // Filter blocked URLs early to avoid unnecessary billing- if (searchResults.length > limit) {- searchResults = searchResults.slice(0, limit);- }+ // Transform v2 response to v1 format (flat array)+ const docs = transformToV1Response(result.response);- if (searchResults.length === 0) {+ if (docs.length === 0) {logger.info("No search results found");responseData.warning = "No search results found";- } else if (- !req.body.scrapeOptions.formats ||- req.body.scrapeOptions.formats.length === 0- ) {- responseData.data = searchResults.map(r => ({- url: r.url,- title: r.title,- description: r.description,- })) as Document[];- credits_billed = Math.ceil(responseData.data.length / 10) * 2;- } else {- logger.info("Scraping search results");- const scrapePromises = searchResults.map(result =>- scrapeSearchResult(- result,- {- teamId: req.auth.team_id,- origin: req.body.origin,- timeout: req.body.timeout,- scrapeOptions: req.body.scrapeOptions,- apiKeyId: req.acuc?.api_key_id ?? null,- requestId: jobId,- },- logger,- req.acuc?.flags ?? null,- (req.acuc?.price_credits ?? 0) <= 3000,- isSearchPreview,- ),- );-- const docsWithCostTracking = await Promise.all(scrapePromises);- logger.info("Scraping completed", {- num_docs: docsWithCostTracking.length,- });-- const docs = docsWithCostTracking.map(item => item.document);- const filteredDocs = docs.filter(- doc =>- doc.serpResults || (doc.markdown && doc.markdown.trim().length > 0),- );-- logger.info("Filtering completed", {- num_docs: filteredDocs.length,- });+ } else if (shouldScrape) {+ // Filter documents that have content+ const filteredDocs = filterDocumentsWithContent(docs);if (filteredDocs.length === 0) {responseData.data = docs;@@ -375,23 +186,25 @@ export async function searchController(} else {responseData.data = filteredDocs;}-- // Calculate search credits only - scrape jobs bill themselves- credits_billed = Math.ceil(responseData.data.length / 10) * 2;-- allDocsWithCostTracking = docsWithCostTracking;+ } else {+ // No scraping - just return basic info+ responseData.data = docs.map(d => ({+ url: d.url,+ title: d.title,+ description: d.description,+ })) as Document[];}- // Bill team for search credits only - scrape jobs handle their own billing+ // Bill team for search credits onlyif (!isSearchPreview) {billTeam(req.auth.team_id,req.acuc?.sub_id ?? undefined,- credits_billed,+ result.searchCredits,req.acuc?.api_key_id ?? null,).catch(error => {logger.error(- `Failed to bill team ${req.auth.team_id} for ${responseData.data.length} credits: ${error}`,+ `Failed to bill team ${req.auth.team_id} for ${result.searchCredits} credits: ${error}`,);});}@@ -399,11 +212,6 @@ export async function searchController(const endTime = new Date().getTime();const timeTakenInSeconds = (endTime - middlewareStartTime) / 1000;- logger.info("Logging job", {- num_docs: responseData.data.length,- time_taken: timeTakenInSeconds,- });-logSearch({id: jobId,@@ -420,19 +228,15 @@ export async function searchController(query: undefined,scrapeOptions: undefined,},- credits_cost: credits_billed,- zeroDataRetention: false, // not supported+ credits_cost: result.searchCredits,+ zeroDataRetention: false,},false,);- // Log final timing informationconst totalRequestTime = new Date().getTime() - middlewareStartTime;const controllerTime = new Date().getTime() - controllerStartTime;- const scrapeful = !!(- req.body.scrapeOptions.formats &&- req.body.scrapeOptions.formats.length > 0- );+logger.info("Request metrics", {version: "v1",mode: "search",@@ -442,8 +246,8 @@ export async function searchController(middlewareTime,controllerTime,totalRequestTime,- creditsUsed: credits_billed,- scrapeful,+ creditsUsed: result.searchCredits,+ scrapeful: shouldScrape,});return res.status(200).json(responseData);diff --git a/apps/api/src/controllers/v2/search.ts b/apps/api/src/controllers/v2/search.tsindex 37334c5c0..44d738aab 100644--- a/apps/api/src/controllers/v2/search.ts+++ b/apps/api/src/controllers/v2/search.ts@@ -1,221 +1,28 @@import { Response } from "express";import { config } from "../../config";import {- Document,RequestWithAuth,SearchRequest,SearchResponse,searchRequestSchema,- ScrapeOptions,- TeamFlags,} from "./types";import { billTeam } from "../../services/billing/credit_billing";import { v7 as uuidv7 } from "uuid";-import { addScrapeJob, waitForJob } from "../../services/queue-jobs";import { logSearch, logRequest } from "../../services/logging/log_job";-import { search } from "../../search/v2";-import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";import { logger as _logger } from "../../lib/logger";-import type { Logger } from "winston";-import { getJobPriority } from "../../lib/job-priority";-import { CostTracking } from "../../lib/cost-tracking";-import { supabase_service } from "../../services/supabase";-import { SearchV2Response } from "../../lib/entities";import { ScrapeJobTimeoutError } from "../../lib/error";-import { scrapeQueue } from "../../services/worker/nuq";import { z } from "zod";-import {- buildSearchQuery,- getCategoryFromUrl,- CategoryOption,-} from "../../lib/search-query-builder";+import { CategoryOption } from "../../lib/search-query-builder";import {applyZdrScope,captureExceptionWithZdrCheck,} from "../../services/sentry";--interface DocumentWithCostTracking {- document: Document;- costTracking: ReturnType<typeof CostTracking.prototype.toJSON>;-}--interface ScrapeJobInput {- url: string;- title: string;- description: string;-}--async function startScrapeJob(- searchResult: { url: string; title: string; description: string },- options: {- teamId: string;- origin: string;- timeout: number;- scrapeOptions: ScrapeOptions;- bypassBilling?: boolean;- apiKeyId: number | null;- zeroDataRetention?: boolean;- requestId?: string;- },- logger: Logger,- flags: TeamFlags,- directToBullMQ: boolean = false,- isSearchPreview: boolean = false,-): Promise<string> {- const jobId = uuidv7();-- const zeroDataRetention =- flags?.forceZDR || (options.zeroDataRetention ?? false);-- logger.info("Adding scrape job", {- scrapeId: jobId,- url: searchResult.url,- teamId: options.teamId,- origin: options.origin,- zeroDataRetention,- });-- const jobPriority = await getJobPriority({- team_id: options.teamId,- basePriority: 10,- });-- await addScrapeJob(- {- url: searchResult.url,- mode: "single_urls",- team_id: options.teamId,- scrapeOptions: {- ...options.scrapeOptions,- // TODO: fix this- maxAge: 3 * 24 * 60 * 60 * 1000, // 3 days- },- internalOptions: {- teamId: options.teamId,- bypassBilling: options.bypassBilling ?? true,- zeroDataRetention,- },- origin: options.origin,- // Do not touch this flag- is_scrape: options.bypassBilling ?? false,- startTime: Date.now(),- zeroDataRetention,- apiKeyId: options.apiKeyId,- requestId: options.requestId,- },- jobId,- jobPriority,- directToBullMQ,- true,- );-- return jobId;-}--async function scrapeSearchResult(- searchResult: { url: string; title: string; description: string },- options: {- teamId: string;- origin: string;- timeout: number;- scrapeOptions: ScrapeOptions;- bypassBilling?: boolean;- apiKeyId: number | null;- zeroDataRetention?: boolean;- requestId?: string;- },- logger: Logger,- flags: TeamFlags,- directToBullMQ: boolean = false,- isSearchPreview: boolean = false,-): Promise<DocumentWithCostTracking> {- try {- // Start the scrape job- const jobId = await startScrapeJob(- searchResult,- options,- logger,- flags,- directToBullMQ,- isSearchPreview,- );-- const doc: Document = await waitForJob(- jobId,- options.timeout,- options.zeroDataRetention ?? false,- logger,- );-- logger.info("Scrape job completed", {- scrapeId: jobId,- url: searchResult.url,- teamId: options.teamId,- origin: options.origin,- });-- await scrapeQueue.removeJob(jobId, logger);-- const document = {- title: searchResult.title,- description: searchResult.description,- url: searchResult.url,- ...doc,- };-- let costTracking: ReturnType<typeof CostTracking.prototype.toJSON>;- if (config.USE_DB_AUTHENTICATION) {- const { data: costTrackingResponse, error: costTrackingError } =- await supabase_service- .from("scrapes")- .select("cost_tracking")- .eq("id", jobId);-- if (costTrackingError) {- logger.error("Error getting cost tracking", {- error: costTrackingError,- });- throw costTrackingError;- }-- costTracking = costTrackingResponse?.[0]?.cost_tracking;- } else {- costTracking = new CostTracking().toJSON();- }-- return {- document,- costTracking,- };- } catch (error) {- logger.error(`Error in scrapeSearchResult: ${error}`, {- url: searchResult.url,- teamId: options.teamId,- });-- const document: Document = {- title: searchResult.title,- description: searchResult.description,- url: searchResult.url,- metadata: {- statusCode: 500,- error: error.message,- proxyUsed: "basic",- },- };-- return {- document,- costTracking: new CostTracking().toJSON(),- };- }-}+import { executeSearch } from "../../search/execute";export async function searchController(req: RequestWithAuth<{}, SearchResponse, SearchRequest>,res: Response<SearchResponse>,) {- // Get timing data from middleware (includes all middleware processing time)const middlewareStartTime =(req as any).requestTiming?.startTime || new Date().getTime();const controllerStartTime = new Date().getTime();@@ -242,8 +49,6 @@ export async function searchController(config.SEARCH_PREVIEW_TOKEN !== undefined &&config.SEARCH_PREVIEW_TOKEN === req.body.__searchPreviewToken;- let credits_billed = 0;-let zeroDataRetention = false;try {@@ -289,411 +94,55 @@ export async function searchController(origin: req.body.origin ?? "api",integration: req.body.integration,target_hint: req.body.query,- zeroDataRetention: isZDROrAnon ?? false, // not supported for search+ zeroDataRetention: isZDROrAnon ?? false,api_key_id: req.acuc?.api_key_id ?? null,});}- let limit = req.body.limit;-- // Buffer results by 50% to account for filtered URLs- const num_results_buffer = Math.floor(limit * 2);-- logger.info("Searching for results");-- // Extract unique types from sources for the search function- // After transformation, sources is always an array of objects- const searchTypes = [...new Set(req.body.sources.map((s: any) => s.type))];-- // Build search query with category filters- const { query: searchQuery, categoryMap } = buildSearchQuery(- req.body.query,- req.body.categories as CategoryOption[],- );-- const searchResponse = (await search({- query: searchQuery,- logger,- advanced: false,- num_results: num_results_buffer,- tbs: req.body.tbs,- filter: req.body.filter,- lang: req.body.lang,- country: req.body.country,- location: req.body.location,- type: searchTypes,- enterprise: req.body.enterprise,- })) as SearchV2Response;-- // Add category labels to web results- if (searchResponse.web && searchResponse.web.length > 0) {- searchResponse.web = searchResponse.web.map(result => ({- ...result,- category: getCategoryFromUrl(result.url, categoryMap),- }));- }-- // Add category labels to news results- if (searchResponse.news && searchResponse.news.length > 0) {- searchResponse.news = searchResponse.news.map(result => ({- ...result,- category: result.url- ? getCategoryFromUrl(result.url, categoryMap)- : undefined,- }));- }-- // Apply limit to each result type separately- let totalResultsCount = 0;-- // Apply limit to web results- if (searchResponse.web && searchResponse.web.length > 0) {- if (searchResponse.web.length > limit) {- searchResponse.web = searchResponse.web.slice(0, limit);- }- totalResultsCount += searchResponse.web.length;- }-- // Apply limit to images- if (searchResponse.images && searchResponse.images.length > 0) {- if (searchResponse.images.length > limit) {- searchResponse.images = searchResponse.images.slice(0, limit);- }- totalResultsCount += searchResponse.images.length;- }-- // Apply limit to news- if (searchResponse.news && searchResponse.news.length > 0) {- if (searchResponse.news.length > limit) {- searchResponse.news = searchResponse.news.slice(0, limit);- }- totalResultsCount += searchResponse.news.length;- }-- // Check if scraping is requested- const shouldScrape =- req.body.scrapeOptions?.formats &&- req.body.scrapeOptions.formats.length > 0;- const isAsyncScraping = req.body.asyncScraping && shouldScrape;-- if (!shouldScrape) {- const creditsPerTenResults = isZDR ? 10 : 2;- credits_billed = Math.ceil(totalResultsCount / 10) * creditsPerTenResults;- } else {- // Common setup for both async and sync scraping- logger.info(- `Starting ${isAsyncScraping ? "async" : "sync"} search scraping`,- );-- // Safely extract scrapeOptions with runtime check- if (!req.body.scrapeOptions) {- logger.error(- "scrapeOptions is undefined despite shouldScrape being true",- );- return res.status(500).json({- success: false,- error: "Internal server error: scrapeOptions is missing",- });- }-- const bodyScrapeOptions = req.body.scrapeOptions;-- // Create common options- const scrapeOptions = {+ const result = await executeSearch(+ {+ query: req.body.query,+ limit: req.body.limit,+ tbs: req.body.tbs,+ filter: req.body.filter,+ lang: req.body.lang,+ country: req.body.country,+ location: req.body.location,+ sources: req.body.sources as Array<{ type: string }>,+ categories: req.body.categories as CategoryOption[],+ enterprise: req.body.enterprise,+ scrapeOptions: req.body.scrapeOptions,+ timeout: req.body.timeout,+ },+ {teamId: req.auth.team_id,origin: req.body.origin,- timeout: req.body.timeout,- scrapeOptions: bodyScrapeOptions,- bypassBilling: !shouldBill, // Scrape jobs always bill themselvesapiKeyId: req.acuc?.api_key_id ?? null,- zeroDataRetention: isZDROrAnon,+ flags: req.acuc?.flags ?? null,requestId: agentRequestId ?? jobId,- };-- const directToBullMQ = (req.acuc?.price_credits ?? 0) <= 3000;-- // Prepare all items to scrape with their original data- const itemsToScrape: Array<{- item: any;- type: "web" | "news" | "image";- scrapeInput: ScrapeJobInput;- }> = [];-- // Add web results (skip blocked URLs)- if (searchResponse.web) {- searchResponse.web.forEach(item => {- if (!isUrlBlocked(item.url, req.acuc?.flags ?? null)) {- itemsToScrape.push({- item,- type: "web",- scrapeInput: {- url: item.url,- title: item.title,- description: item.description,- },- });- } else {- logger.info(`Skipping blocked URL: ${item.url}`);- }- });- }-- // Add news results (only those with URLs and not blocked)- if (searchResponse.news) {- searchResponse.news- .filter(item => item.url)- .forEach(item => {- if (!isUrlBlocked(item.url!, req.acuc?.flags ?? null)) {- itemsToScrape.push({- item,- type: "news",- scrapeInput: {- url: item.url!,- title: item.title || "",- description: item.snippet || "",- },- });- } else {- logger.info(`Skipping blocked URL: ${item.url}`);- }- });- }-- // Add image results (only those with URLs and not blocked)- if (searchResponse.images) {- searchResponse.images- .filter(item => item.url)- .forEach(item => {- if (!isUrlBlocked(item.url!, req.acuc?.flags ?? null)) {- itemsToScrape.push({- item,- type: "image",- scrapeInput: {- url: item.url!,- title: item.title || "",- description: "",- },- });- } else {- logger.info(`Skipping blocked URL: ${item.url}`);- }- });- }-- // Create all promises based on mode (async vs sync)- const allPromises = itemsToScrape.map(({ scrapeInput }) =>- isAsyncScraping- ? startScrapeJob(- scrapeInput,- scrapeOptions,- logger,- req.acuc?.flags ?? null,- directToBullMQ,- isSearchPreview,- )- : scrapeSearchResult(- scrapeInput,- scrapeOptions,- logger,- req.acuc?.flags ?? null,- directToBullMQ,- isSearchPreview,- ),- );-- // Execute all operations in parallel- const results = await Promise.all(allPromises);-- if (isAsyncScraping) {- // Async mode: organize job IDs and return immediately- const allJobIds = results as string[];- const scrapeIds: {- web?: string[];- news?: string[];- images?: string[];- } = {};-- // Organize job IDs by type- const webItems = itemsToScrape.filter(i => i.type === "web");- const newsItems = itemsToScrape.filter(i => i.type === "news");- const imageItems = itemsToScrape.filter(i => i.type === "image");-- let currentIndex = 0;-- if (webItems.length > 0) {- scrapeIds.web = allJobIds.slice(- currentIndex,- currentIndex + webItems.length,- );- currentIndex += webItems.length;- }-- if (newsItems.length > 0) {- scrapeIds.news = allJobIds.slice(- currentIndex,- currentIndex + newsItems.length,- );- currentIndex += newsItems.length;- }-- if (imageItems.length > 0) {- scrapeIds.images = allJobIds.slice(- currentIndex,- currentIndex + imageItems.length,- );- }-- const creditsPerTenResults = isZDR ? 10 : 2;- credits_billed =- Math.ceil(totalResultsCount / 10) * creditsPerTenResults;-- // Bill for search results now (scrape jobs will bill themselves when they complete)- if (!isSearchPreview) {- billTeam(- req.auth.team_id,- req.acuc?.sub_id ?? undefined,- credits_billed,- req.acuc?.api_key_id ?? null,- ).catch(error => {- logger.error(- `Failed to bill team ${req.acuc?.sub_id} for ${credits_billed} credits: ${error}`,- );- });- }-- const endTime = new Date().getTime();- const timeTakenInSeconds = (endTime - middlewareStartTime) / 1000;-- logger.info("Logging job (async scraping)", {- num_docs: credits_billed,- time_taken: timeTakenInSeconds,- scrapeIds,- });-- logSearch(- {- id: jobId,- request_id: jobId,- query: req.body.query,- is_successful: true,- error: undefined,- results: searchResponse as any,- num_results: totalResultsCount,- time_taken: timeTakenInSeconds,- team_id: req.auth.team_id,- options: req.body,- credits_cost: credits_billed,- zeroDataRetention: isZDROrAnon ?? false,- },- false,- );-- // Log final timing information for async mode- const totalRequestTime = new Date().getTime() - middlewareStartTime;- const controllerTime = new Date().getTime() - controllerStartTime;- logger.info("Search completed successfully (async)", {- version: "v2",- jobId,- middlewareStartTime,- controllerStartTime,- middlewareTime,- controllerTime,- totalRequestTime,- creditsUsed: credits_billed,- scrapeful: shouldScrape,- });-- return res.status(200).json({- success: true,- data: searchResponse,- scrapeIds,- creditsUsed: credits_billed,- id: jobId,- });- } else {- // Sync mode: process scraped documents- const allDocsWithCostTracking = results as DocumentWithCostTracking[];- const scrapedResponse: SearchV2Response = {};-- // Create a map of results indexed by URL for easy lookup- const resultsMap = new Map<string, Document>();- itemsToScrape.forEach((item, index) => {- resultsMap.set(- item.scrapeInput.url,- allDocsWithCostTracking[index].document,- );- });-- // Process web results - preserve all original fields and add scraped content- if (searchResponse.web && searchResponse.web.length > 0) {- scrapedResponse.web = searchResponse.web.map(item => {- const doc = resultsMap.get(item.url);- return {- ...item, // Preserve ALL original fields- ...doc, // Override/add scraped content- };- });- }-- // Process news results - preserve all original fields and add scraped content- if (searchResponse.news && searchResponse.news.length > 0) {- scrapedResponse.news = searchResponse.news.map(item => {- const doc = item.url ? resultsMap.get(item.url) : undefined;- return {- ...item, // Preserve ALL original fields- ...doc, // Override/add scraped content- };- });- }-- // Process image results - preserve all original fields and add scraped content- if (searchResponse.images && searchResponse.images.length > 0) {- scrapedResponse.images = searchResponse.images.map(item => {- const doc = item.url ? resultsMap.get(item.url) : undefined;- return {- ...item, // Preserve ALL original fields- ...doc, // Override/add scraped content- };- });- }-- // Calculate search credits only - scrape jobs bill themselves- const creditsPerTenResults = isZDR ? 10 : 2;- credits_billed =- Math.ceil(totalResultsCount / 10) * creditsPerTenResults;-- // Update response with scraped data- Object.assign(searchResponse, scrapedResponse);- }- }+ bypassBilling: !shouldBill,+ zeroDataRetention: isZDROrAnon,+ },+ logger,+ );- // Bill team for search credits only- // - Scrape jobs always handle their own billing (both sync and async)- // - Search job only bills for search costs (credits per 10 results)- if (- !isSearchPreview &&- (!shouldScrape || (shouldScrape && !isAsyncScraping))- ) {+ // Bill team for search credits only (scrape jobs bill themselves)+ if (!isSearchPreview && shouldBill) {billTeam(req.auth.team_id,req.acuc?.sub_id ?? undefined,- credits_billed,+ result.searchCredits,req.acuc?.api_key_id ?? null,- ).catch(error => {+ ).catch(error =>logger.error(- `Failed to bill team ${req.acuc?.sub_id} for ${credits_billed} credits: ${error}`,- );- });+ `Failed to bill team ${req.acuc?.sub_id} for ${result.searchCredits} credits: ${error}`,+ ),+ );}const endTime = new Date().getTime();const timeTakenInSeconds = (endTime - middlewareStartTime) / 1000;- logger.info("Logging job", {- num_docs: credits_billed,- time_taken: timeTakenInSeconds,- });-logSearch({id: jobId,@@ -701,18 +150,17 @@ export async function searchController(query: req.body.query,is_successful: true,error: undefined,- results: searchResponse as any,- num_results: totalResultsCount,+ results: result.response as any,+ num_results: result.totalResultsCount,time_taken: timeTakenInSeconds,team_id: req.auth.team_id,options: req.body,- credits_cost: shouldBill ? credits_billed : 0,- zeroDataRetention: isZDROrAnon ?? false, // not supported+ credits_cost: shouldBill ? result.searchCredits : 0,+ zeroDataRetention: isZDROrAnon ?? false,},false,);- // Log final timing informationconst totalRequestTime = new Date().getTime() - middlewareStartTime;const controllerTime = new Date().getTime() - controllerStartTime;@@ -725,15 +173,16 @@ export async function searchController(middlewareTime,controllerTime,totalRequestTime,- creditsUsed: credits_billed,- scrapeful: shouldScrape,+ searchCredits: result.searchCredits,+ scrapeCredits: result.scrapeCredits,+ totalCredits: result.totalCredits,+ scrapeful: result.shouldScrape,});- // For sync scraping or no scraping, don't include scrapeIdsreturn res.status(200).json({success: true,- data: searchResponse,- creditsUsed: credits_billed,+ data: result.response,+ creditsUsed: result.totalCredits,id: jobId,});} catch (error) {diff --git a/apps/api/src/search/execute.ts b/apps/api/src/search/execute.tsnew file mode 100644index 000000000..1f790358f--- /dev/null+++ b/apps/api/src/search/execute.ts@@ -0,0 +1,178 @@+import type { Logger } from "winston";+import { search } from "./v2";+import { SearchV2Response } from "../lib/entities";+import {+ buildSearchQuery,+ getCategoryFromUrl,+ CategoryOption,+} from "../lib/search-query-builder";+import { ScrapeOptions, TeamFlags } from "../controllers/v2/types";+import {+ getItemsToScrape,+ scrapeSearchResults,+ mergeScrapedContent,+ calculateScrapeCredits,+} from "./scrape";++interface SearchOptions {+ query: string;+ limit: number;+ tbs?: string;+ filter?: string;+ lang?: string;+ country?: string;+ location?: string;+ sources: Array<{ type: string }>;+ categories?: CategoryOption[];+ enterprise?: ("default" | "anon" | "zdr")[];+ scrapeOptions?: ScrapeOptions;+ timeout: number;+}++interface SearchContext {+ teamId: string;+ origin: string;+ apiKeyId: number | null;+ flags: TeamFlags;+ requestId: string;+ bypassBilling?: boolean;+ zeroDataRetention?: boolean;+}++interface SearchExecuteResult {+ response: SearchV2Response;+ totalResultsCount: number;+ searchCredits: number;+ scrapeCredits: number;+ totalCredits: number;+ shouldScrape: boolean;+}++export async function executeSearch(+ options: SearchOptions,+ context: SearchContext,+ logger: Logger,+): Promise<SearchExecuteResult> {+ const { query, limit, sources, categories, scrapeOptions } = options;+ const {+ teamId,+ origin,+ apiKeyId,+ flags,+ requestId,+ bypassBilling,+ zeroDataRetention,+ } = context;++ const num_results_buffer = Math.floor(limit * 2);++ logger.info("Searching for results");++ const searchTypes = [...new Set(sources.map((s: any) => s.type))];+ const { query: searchQuery, categoryMap } = buildSearchQuery(+ query,+ categories,+ );++ const searchResponse = (await search({+ query: searchQuery,+ logger,+ advanced: false,+ num_results: num_results_buffer,+ tbs: options.tbs,+ filter: options.filter,+ lang: options.lang,+ country: options.country,+ location: options.location,+ type: searchTypes,+ enterprise: options.enterprise,+ })) as SearchV2Response;++ if (searchResponse.web && searchResponse.web.length > 0) {+ searchResponse.web = searchResponse.web.map(result => ({+ ...result,+ category: getCategoryFromUrl(result.url, categoryMap),+ }));+ }++ if (searchResponse.news && searchResponse.news.length > 0) {+ searchResponse.news = searchResponse.news.map(result => ({+ ...result,+ category: result.url+ ? getCategoryFromUrl(result.url, categoryMap)+ : undefined,+ }));+ }++ let totalResultsCount = 0;++ if (searchResponse.web && searchResponse.web.length > 0) {+ if (searchResponse.web.length > limit) {+ searchResponse.web = searchResponse.web.slice(0, limit);+ }+ totalResultsCount += searchResponse.web.length;+ }++ if (searchResponse.images && searchResponse.images.length > 0) {+ if (searchResponse.images.length > limit) {+ searchResponse.images = searchResponse.images.slice(0, limit);+ }+ totalResultsCount += searchResponse.images.length;+ }++ if (searchResponse.news && searchResponse.news.length > 0) {+ if (searchResponse.news.length > limit) {+ searchResponse.news = searchResponse.news.slice(0, limit);+ }+ totalResultsCount += searchResponse.news.length;+ }++ const isZDR = options.enterprise?.includes("zdr");+ const creditsPerTenResults = isZDR ? 10 : 2;+ const searchCredits =+ Math.ceil(totalResultsCount / 10) * creditsPerTenResults;+ let scrapeCredits = 0;++ const shouldScrape =+ scrapeOptions?.formats && scrapeOptions.formats.length > 0;++ if (shouldScrape && scrapeOptions) {+ const itemsToScrape = getItemsToScrape(searchResponse, flags);++ if (itemsToScrape.length > 0) {+ const scrapeOpts = {+ teamId,+ origin,+ timeout: options.timeout,+ scrapeOptions,+ bypassBilling: bypassBilling ?? false,+ apiKeyId,+ zeroDataRetention,+ requestId,+ };++ const allDocsWithCostTracking = await scrapeSearchResults(+ itemsToScrape.map(i => i.scrapeInput),+ scrapeOpts,+ logger,+ flags,+ );++ mergeScrapedContent(+ searchResponse,+ itemsToScrape,+ allDocsWithCostTracking,+ );+ scrapeCredits = calculateScrapeCredits(allDocsWithCostTracking);+ }+ }++ return {+ response: searchResponse,+ totalResultsCount,+ searchCredits,+ scrapeCredits,+ totalCredits: searchCredits + scrapeCredits,+ shouldScrape: shouldScrape ?? false,+ };+}diff --git a/apps/api/src/search/scrape.ts b/apps/api/src/search/scrape.tsnew file mode 100644index 000000000..731b7eb98--- /dev/null+++ b/apps/api/src/search/scrape.ts@@ -0,0 +1,260 @@+import { v7 as uuidv7 } from "uuid";+import type { Logger } from "winston";+import { Document, ScrapeOptions, TeamFlags } from "../controllers/v2/types";+import { CostTracking } from "../lib/cost-tracking";+import { getJobPriority } from "../lib/job-priority";+import { isUrlBlocked } from "../scraper/WebScraper/utils/blocklist";+import { NuQJob } from "../services/worker/nuq";+import { processJobInternal } from "../services/worker/scrape-worker";+import { ScrapeJobData } from "../types";+import { SearchV2Response } from "../lib/entities";++export interface DocumentWithCostTracking {+ document: Document;+ costTracking: ReturnType<typeof CostTracking.prototype.toJSON>;+}++interface ScrapeJobInput {+ url: string;+ title: string;+ description: string;+}++interface ScrapeItem {+ item: any;+ type: "web" | "news" | "image";+ scrapeInput: ScrapeJobInput;+}++interface ScrapeSearchOptions {+ teamId: string;+ origin: string;+ timeout: number;+ scrapeOptions: ScrapeOptions;+ bypassBilling?: boolean;+ apiKeyId: number | null;+ zeroDataRetention?: boolean;+ requestId?: string;+}++async function scrapeSearchResultDirect(+ searchResult: ScrapeJobInput,+ options: ScrapeSearchOptions,+ logger: Logger,+ flags: TeamFlags,+ jobPriority: number,+): Promise<DocumentWithCostTracking> {+ const jobId = uuidv7();+ const zeroDataRetention =+ flags?.forceZDR || (options.zeroDataRetention ?? false);++ logger.debug("Starting direct scrape for search result", {+ scrapeId: jobId,+ url: searchResult.url,+ teamId: options.teamId,+ origin: options.origin,+ zeroDataRetention,+ });++ try {+ const job: NuQJob<ScrapeJobData> = {+ id: jobId,+ status: "active",+ createdAt: new Date(),+ priority: jobPriority,+ data: {+ url: searchResult.url,+ mode: "single_urls",+ team_id: options.teamId,+ scrapeOptions: {+ ...options.scrapeOptions,+ maxAge: 3 * 24 * 60 * 60 * 1000, // 3 days+ },+ internalOptions: {+ teamId: options.teamId,+ bypassBilling: options.bypassBilling ?? true,+ zeroDataRetention,+ teamFlags: flags,+ },+ skipNuq: true,+ origin: options.origin,+ is_scrape: false,+ startTime: Date.now(),+ zeroDataRetention,+ apiKeyId: options.apiKeyId,+ requestId: options.requestId,+ },+ };++ const doc = await processJobInternal(job);++ logger.debug("Direct scrape completed for search result", {+ scrapeId: jobId,+ url: searchResult.url,+ });++ const document: Document = {+ title: searchResult.title,+ description: searchResult.description,+ url: searchResult.url,+ ...doc,+ metadata: doc?.metadata ?? {+ statusCode: 200,+ proxyUsed: "basic",+ },+ };++ return {+ document,+ costTracking: new CostTracking().toJSON(),+ };+ } catch (error) {+ logger.error(`Error in scrapeSearchResultDirect: ${error}`, {+ url: searchResult.url,+ teamId: options.teamId,+ scrapeId: jobId,+ });++ const document: Document = {+ title: searchResult.title,+ description: searchResult.description,+ url: searchResult.url,+ metadata: {+ statusCode: 500,+ error: error.message,+ proxyUsed: "basic",+ },+ };++ return {+ document,+ costTracking: new CostTracking().toJSON(),+ };+ }+}++export function getItemsToScrape(+ searchResponse: SearchV2Response,+ flags: TeamFlags,+): ScrapeItem[] {+ const items: ScrapeItem[] = [];++ if (searchResponse.web) {+ for (const item of searchResponse.web) {+ if (!isUrlBlocked(item.url, flags)) {+ items.push({+ item,+ type: "web",+ scrapeInput: {+ url: item.url,+ title: item.title,+ description: item.description,+ },+ });+ }+ }+ }++ if (searchResponse.news) {+ for (const item of searchResponse.news) {+ if (item.url && !isUrlBlocked(item.url, flags)) {+ items.push({+ item,+ type: "news",+ scrapeInput: {+ url: item.url,+ title: item.title || "",+ description: item.snippet || "",+ },+ });+ }+ }+ }++ if (searchResponse.images) {+ for (const item of searchResponse.images) {+ if (item.url && !isUrlBlocked(item.url, flags)) {+ items.push({+ item,+ type: "image",+ scrapeInput: {+ url: item.url,+ title: item.title || "",+ description: "",+ },+ });+ }+ }+ }++ return items;+}++export async function scrapeSearchResults(+ items: ScrapeJobInput[],+ options: ScrapeSearchOptions,+ logger: Logger,+ flags: TeamFlags,+): Promise<DocumentWithCostTracking[]> {+ if (items.length === 0) {+ return [];+ }++ const jobPriority = await getJobPriority({+ team_id: options.teamId,+ basePriority: 10,+ });++ logger.info(`Starting ${items.length} concurrent scrapes for search results`);++ const results = await Promise.all(+ items.map(item =>+ scrapeSearchResultDirect(item, options, logger, flags, jobPriority),+ ),+ );++ logger.info(+ `Completed ${results.length} concurrent scrapes for search results`,+ );++ return results;+}++export function calculateScrapeCredits(+ docs: DocumentWithCostTracking[],+): number {+ return docs.reduce(+ (total, { document }) => total + (document.metadata?.creditsUsed ?? 0),+ 0,+ );+}++export function mergeScrapedContent(+ searchResponse: SearchV2Response,+ items: ScrapeItem[],+ docs: DocumentWithCostTracking[],+): void {+ const resultsMap = new Map<string, Document>();+ items.forEach((item, index) => {+ resultsMap.set(item.scrapeInput.url, docs[index].document);+ });++ if (searchResponse.web?.length) {+ searchResponse.web = searchResponse.web.map(item => ({+ ...item,+ ...resultsMap.get(item.url),+ }));+ }+ if (searchResponse.news?.length) {+ searchResponse.news = searchResponse.news.map(item => ({+ ...item,+ ...(item.url ? resultsMap.get(item.url) : {}),+ }));+ }+ if (searchResponse.images?.length) {+ searchResponse.images = searchResponse.images.map(item => ({+ ...item,+ ...(item.url ? resultsMap.get(item.url) : {}),+ }));+ }+}diff --git a/apps/api/src/search/transform.ts b/apps/api/src/search/transform.tsnew file mode 100644index 000000000..219674959--- /dev/null+++ b/apps/api/src/search/transform.ts@@ -0,0 +1,53 @@+import { Document } from "../controllers/v2/types";+import { SearchV2Response } from "../lib/entities";++export function transformToV1Response(+ searchResponse: SearchV2Response,+): Document[] {+ const documents: Document[] = [];++ if (searchResponse.web && searchResponse.web.length > 0) {+ for (const item of searchResponse.web) {+ documents.push({+ ...item,+ url: item.url,+ title: item.title,+ description: item.description,+ } as Document);+ }+ }++ if (searchResponse.news && searchResponse.news.length > 0) {+ for (const item of searchResponse.news) {+ if (item.url) {+ documents.push({+ ...item,+ url: item.url,+ title: item.title || "",+ description: item.snippet || "",+ } as Document);+ }+ }+ }++ if (searchResponse.images && searchResponse.images.length > 0) {+ for (const item of searchResponse.images) {+ if (item.url) {+ documents.push({+ ...item,+ url: item.url,+ title: item.title || "",+ description: "",+ } as Document);+ }+ }+ }++ return documents;+}++export function filterDocumentsWithContent(documents: Document[]): Document[] {+ return documents.filter(+ doc => doc.serpResults || (doc.markdown && doc.markdown.trim().length > 0),+ );+}