Files
firecrawl/apps/api/src/controllers/v0/search.ts
T

206 lines
6.1 KiB
TypeScript
Raw Normal View History

2024-04-23 15:28:32 -07:00
import { Request, Response } from "express";
2024-08-15 21:51:59 +02:00
import { WebScraperDataProvider } from "../../scraper/WebScraper";
import { billTeam, checkTeamCredits } from "../../services/billing/credit_billing";
2024-08-26 18:48:00 -03:00
import { authenticateUser } from "../auth";
2024-08-28 12:42:23 -03:00
import { PlanType, RateLimiterMode } from "../../types";
2024-08-15 21:51:59 +02:00
import { logJob } from "../../services/logging/log_job";
import { PageOptions, SearchOptions } from "../../lib/entities";
import { search } from "../../search";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
2024-07-24 14:31:25 +02:00
import { v4 as uuidv4 } from "uuid";
2024-08-15 21:51:59 +02:00
import { Logger } from "../../lib/logger";
2024-08-23 17:21:54 +02:00
import { getScrapeQueue } from "../../services/queue-service";
2024-08-23 18:27:00 +02:00
import { addScrapeJob, waitForJob } from "../../services/queue-jobs";
import * as Sentry from "@sentry/node";
2024-08-28 12:42:23 -03:00
import { getJobPriority } from "../../lib/job-priority";
2024-04-23 15:28:32 -07:00
export async function searchHelper(
2024-07-24 14:31:25 +02:00
jobId: string,
2024-04-23 15:28:32 -07:00
req: Request,
team_id: string,
2024-09-25 20:57:45 +02:00
subscription_id: string,
2024-04-23 15:28:32 -07:00
crawlerOptions: any,
2024-04-23 15:44:11 -07:00
pageOptions: PageOptions,
2024-05-06 19:45:56 -03:00
searchOptions: SearchOptions,
2024-08-21 22:53:33 -03:00
plan: PlanType
2024-04-23 15:28:32 -07:00
): Promise<{
success: boolean;
error?: string;
data?: any;
returnCode: number;
}> {
const query = req.body.query;
2024-04-23 15:44:11 -07:00
const advanced = false;
2024-04-23 15:28:32 -07:00
if (!query) {
return { success: false, error: "Query is required", returnCode: 400 };
}
2024-04-23 16:45:06 -07:00
const tbs = searchOptions.tbs ?? null;
const filter = searchOptions.filter ?? null;
2024-05-25 00:12:26 +02:00
const num_results = searchOptions.limit ?? 7;
const num_results_buffer = Math.floor(num_results * 1.5);
2024-04-23 16:45:06 -07:00
let res = await search({
query: query,
advanced: advanced,
2024-05-25 00:12:26 +02:00
num_results: num_results_buffer,
tbs: tbs,
filter: filter,
lang: searchOptions.lang ?? "en",
country: searchOptions.country ?? "us",
location: searchOptions.location,
});
2024-04-23 15:28:32 -07:00
let justSearch = pageOptions.fetchPageContent === false;
2024-06-06 20:02:21 -07:00
2024-04-23 15:28:32 -07:00
2024-04-23 15:44:11 -07:00
if (justSearch) {
2024-09-25 20:57:45 +02:00
billTeam(team_id, subscription_id, res.length).catch(error => {
2024-09-03 21:09:32 -03:00
Logger.error(`Failed to bill team ${team_id} for ${res.length} credits: ${error}`);
// Optionally, you could notify an admin or add to a retry queue here
});
2024-04-23 15:28:32 -07:00
return { success: true, data: res, returnCode: 200 };
}
2024-04-24 10:11:01 -07:00
res = res.filter((r) => !isUrlBlocked(r.url));
2024-05-25 00:12:26 +02:00
if (res.length > num_results) {
res = res.slice(0, num_results);
}
2024-04-23 17:06:48 -07:00
2024-04-23 16:45:06 -07:00
if (res.length === 0) {
2024-04-23 15:28:32 -07:00
return { success: true, error: "No search results found", returnCode: 200 };
}
2024-08-21 22:53:33 -03:00
const jobPriority = await getJobPriority({plan, team_id, basePriority: 20});
2024-04-23 17:05:58 -07:00
// filter out social media links
2024-08-15 20:10:43 +02:00
const jobDatas = res.map(x => {
const url = x.url;
const uuid = uuidv4();
return {
name: uuid,
data: {
url,
mode: "single_urls",
crawlerOptions: crawlerOptions,
team_id: team_id,
pageOptions: pageOptions,
},
opts: {
jobId: uuid,
2024-08-21 22:53:33 -03:00
priority: jobPriority,
2024-08-15 20:10:43 +02:00
}
};
})
2024-05-04 13:09:11 -07:00
2024-08-22 19:17:51 +02:00
let jobs = [];
if (Sentry.isInitialized()) {
for (const job of jobDatas) {
// add with sentry instrumentation
2024-09-30 19:20:24 +02:00
jobs.push(await addScrapeJob(job.data as any, {}, job.opts.jobId, job.opts.priority));
2024-08-22 19:17:51 +02:00
}
} else {
jobs = await getScrapeQueue().addBulk(jobDatas);
await getScrapeQueue().addBulk(jobs);
}
2024-05-04 13:09:11 -07:00
2024-08-23 18:27:00 +02:00
const docs = (await Promise.all(jobs.map(x => waitForJob(x.id, 60000)))).map(x => x[0]);
2024-06-18 13:21:50 -04:00
2024-04-23 15:44:11 -07:00
if (docs.length === 0) {
2024-04-23 15:28:32 -07:00
return { success: true, error: "No search results found", returnCode: 200 };
}
2024-08-20 20:29:08 +02:00
await Promise.all(jobs.map(x => x.remove()));
2024-04-23 15:28:32 -07:00
// make sure doc.content is not empty
const filteredDocs = docs.filter(
2024-08-22 18:46:56 +02:00
(doc: { content?: string }) => doc && doc.content && doc.content.trim().length > 0
2024-04-23 15:28:32 -07:00
);
if (filteredDocs.length === 0) {
2024-06-14 09:46:55 -03:00
return { success: true, error: "No page found", returnCode: 200, data: docs };
2024-04-23 15:28:32 -07:00
}
return {
success: true,
data: filteredDocs,
returnCode: 200,
};
}
export async function searchController(req: Request, res: Response) {
try {
// make sure to authenticate user first, Bearer <token>
const { success, team_id, error, status, plan, chunk } = await authenticateUser(
2024-04-23 15:28:32 -07:00
req,
res,
RateLimiterMode.Search
);
if (!success) {
return res.status(status).json({ error });
}
const crawlerOptions = req.body.crawlerOptions ?? {};
2024-04-23 15:44:11 -07:00
const pageOptions = req.body.pageOptions ?? {
2024-08-22 15:15:45 -03:00
includeHtml: req.body.pageOptions?.includeHtml ?? false,
onlyMainContent: req.body.pageOptions?.onlyMainContent ?? false,
fetchPageContent: req.body.pageOptions?.fetchPageContent ?? true,
removeTags: req.body.pageOptions?.removeTags ?? [],
fallback: req.body.pageOptions?.fallback ?? false,
2024-04-23 15:44:11 -07:00
};
2024-04-23 15:28:32 -07:00
const origin = req.body.origin ?? "api";
2024-08-12 16:51:43 -04:00
const searchOptions = req.body.searchOptions ?? { limit: 5 };
2024-07-24 14:31:25 +02:00
const jobId = uuidv4();
2024-04-23 15:28:32 -07:00
try {
const { success: creditsCheckSuccess, message: creditsCheckMessage } =
await checkTeamCredits(chunk, team_id, 1);
2024-04-23 15:28:32 -07:00
if (!creditsCheckSuccess) {
return res.status(402).json({ error: "Insufficient credits" });
}
} catch (error) {
Sentry.captureException(error);
2024-07-25 09:48:06 -03:00
Logger.error(error);
2024-04-23 15:28:32 -07:00
return res.status(500).json({ error: "Internal server error" });
}
const startTime = new Date().getTime();
const result = await searchHelper(
2024-07-24 14:31:25 +02:00
jobId,
2024-04-23 15:28:32 -07:00
req,
team_id,
2024-09-26 22:28:14 +02:00
chunk?.sub_id,
2024-04-23 15:28:32 -07:00
crawlerOptions,
2024-04-23 15:44:11 -07:00
pageOptions,
2024-05-06 19:45:56 -03:00
searchOptions,
2024-08-21 22:53:33 -03:00
plan
2024-04-23 15:28:32 -07:00
);
const endTime = new Date().getTime();
const timeTakenInSeconds = (endTime - startTime) / 1000;
logJob({
2024-07-24 14:31:25 +02:00
job_id: jobId,
2024-04-23 15:28:32 -07:00
success: result.success,
message: result.error,
2024-05-04 12:30:12 -07:00
num_docs: result.data ? result.data.length : 0,
2024-04-24 10:23:26 -07:00
docs: result.data,
2024-04-23 15:28:32 -07:00
time_taken: timeTakenInSeconds,
team_id: team_id,
mode: "search",
2024-04-24 10:23:26 -07:00
url: req.body.query,
2024-04-23 15:28:32 -07:00
crawlerOptions: crawlerOptions,
pageOptions: pageOptions,
origin: origin,
});
return res.status(result.returnCode).json(result);
} catch (error) {
if (error instanceof Error && error.message.startsWith("Job wait")) {
return res.status(408).json({ error: "Request timed out" });
}
2024-09-24 10:27:49 +02:00
Sentry.captureException(error);
2024-07-25 09:48:06 -03:00
Logger.error(error);
2024-04-23 15:28:32 -07:00
return res.status(500).json({ error: error.message });
}
}