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

235 lines
6.6 KiB
TypeScript
Raw Normal View History

2024-04-23 15:28:32 -07:00
import { Request, Response } from "express";
2024-12-11 19:46:11 -03:00
import {
billTeam,
2024-12-11 19:51:08 -03:00
checkTeamCredits,
2024-12-11 19:46:11 -03:00
} 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-11-07 20:57:33 +01:00
import { logger } from "../../lib/logger";
import { getScrapeQueue, redisConnection } 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-11-07 20:57:33 +01:00
import { Job } from "bullmq";
2024-12-11 19:46:11 -03:00
import {
Document,
fromLegacyCombo,
fromLegacyScrapeOptions,
2024-12-11 19:51:08 -03:00
toLegacyDocument,
2024-12-11 19:46:11 -03:00
} from "../v1/types";
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-11-07 20:57:33 +01:00
subscription_id: string | null | undefined,
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-12-11 19:51:08 -03:00
plan: PlanType | undefined,
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-11-07 20:57:33 +01:00
const tbs = searchOptions.tbs ?? undefined;
const filter = searchOptions.filter ?? undefined;
2024-09-30 15:23:43 -03:00
let num_results = Math.min(searchOptions.limit ?? 7, 10);
if (team_id === "d97c4ceb-290b-4957-8432-2b2a02727d95") {
num_results = 1;
}
2024-05-25 00:12:26 +02:00
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",
2024-12-11 19:51:08 -03:00
location: searchOptions.location,
});
2024-04-23 15:28:32 -07:00
let justSearch = pageOptions.fetchPageContent === false;
2024-11-07 20:57:33 +01:00
2024-12-11 19:46:11 -03:00
const { scrapeOptions, internalOptions } = fromLegacyCombo(
pageOptions,
undefined,
60000,
2024-12-11 19:51:08 -03:00
crawlerOptions,
2024-12-11 19:46:11 -03:00
);
2024-04-23 15:28:32 -07:00
2024-04-23 15:44:11 -07:00
if (justSearch) {
2024-12-11 19:46:11 -03:00
billTeam(team_id, subscription_id, res.length).catch((error) => {
logger.error(
2024-12-11 19:51:08 -03:00
`Failed to bill team ${team_id} for ${res.length} credits: ${error}`,
2024-12-11 19:46:11 -03:00
);
2024-09-03 21:09:32 -03:00
// 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-12-11 19:46:11 -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-12-11 19:46:11 -03:00
const jobDatas = res.map((x) => {
2024-08-15 20:10:43 +02:00
const url = x.url;
const uuid = uuidv4();
return {
name: uuid,
data: {
url,
mode: "single_urls",
team_id: team_id,
2024-11-07 20:57:33 +01:00
scrapeOptions,
2024-12-11 19:51:08 -03:00
internalOptions,
2024-08-15 20:10:43 +02:00
},
opts: {
jobId: uuid,
2024-12-11 19:51:08 -03:00
priority: jobPriority,
},
2024-08-15 20:10:43 +02:00
};
2024-12-11 19:46:11 -03:00
});
2024-05-04 13:09:11 -07:00
2024-10-25 20:21:12 +02:00
// TODO: addScrapeJobs
for (const job of jobDatas) {
2024-12-11 19:46:11 -03:00
await addScrapeJob(job.data as any, {}, job.opts.jobId, job.opts.priority);
2024-08-22 19:17:51 +02:00
}
2024-05-04 13:09:11 -07:00
2024-12-11 19:46:11 -03:00
const docs = (
await Promise.all(
2024-12-11 19:51:08 -03:00
jobDatas.map((x) => waitForJob<Document>(x.opts.jobId, 60000)),
2024-12-11 19:46:11 -03:00
)
).map((x) => toLegacyDocument(x, internalOptions));
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-10-25 20:21:12 +02:00
const sq = getScrapeQueue();
2024-12-11 19:46:11 -03:00
await Promise.all(jobDatas.map((x) => sq.remove(x.opts.jobId)));
2024-08-20 20:29:08 +02:00
2024-04-23 15:28:32 -07:00
// make sure doc.content is not empty
const filteredDocs = docs.filter(
2024-12-11 19:51:08 -03:00
(doc: any) => doc && doc.content && doc.content.trim().length > 0,
2024-04-23 15:28:32 -07:00
);
if (filteredDocs.length === 0) {
2024-12-11 19:46:11 -03:00
return {
success: true,
error: "No page found",
returnCode: 200,
2024-12-11 19:51:08 -03:00
data: docs,
2024-12-11 19:46:11 -03:00
};
2024-04-23 15:28:32 -07:00
}
return {
success: true,
data: filteredDocs,
2024-12-11 19:51:08 -03:00
returnCode: 200,
2024-04-23 15:28:32 -07:00
};
}
export async function searchController(req: Request, res: Response) {
try {
// make sure to authenticate user first, Bearer <token>
2024-12-11 19:46:11 -03:00
const auth = await authenticateUser(req, res, RateLimiterMode.Search);
2024-11-07 20:57:33 +01:00
if (!auth.success) {
return res.status(auth.status).json({ error: auth.error });
2024-04-23 15:28:32 -07:00
}
2024-11-07 20:57:33 +01:00
const { team_id, plan, chunk } = auth;
redisConnection.sadd("teams_using_v0", team_id)
.catch(error => logger.error("Failed to add team to teams_using_v0", { error, team_id }));
2024-04-23 15:28:32 -07:00
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 ?? [],
2024-12-11 19:51:08 -03:00
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-12-11 19:46:11 -03:00
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-11-07 20:57:33 +01: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-12-11 19:51:08 -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,
2024-12-11 19:51:08 -03:00
origin: origin,
2024-04-23 15:28:32 -07:00
});
return res.status(result.returnCode).json(result);
} catch (error) {
2024-12-11 19:46:11 -03:00
if (
error instanceof Error &&
(error.message.startsWith("Job wait") || error.message === "timeout")
) {
return res.status(408).json({ error: "Request timed out" });
}
2024-09-24 10:27:49 +02:00
Sentry.captureException(error);
2024-11-07 20:57:33 +01:00
logger.error("Unhandled error occurred in search", { error });
2024-04-23 15:28:32 -07:00
return res.status(500).json({ error: error.message });
}
}