Files
firecrawl/apps/api/src/services/queue-jobs.ts
T

271 lines
7.9 KiB
TypeScript
Raw Normal View History

2024-08-13 21:03:24 +02:00
import { getScrapeQueue } from "./queue-service";
2024-04-15 17:01:47 -04:00
import { v4 as uuidv4 } from "uuid";
import { PlanType, WebScraperOptions } from "../types";
import * as Sentry from "@sentry/node";
2024-12-11 19:46:11 -03:00
import {
cleanOldConcurrencyLimitEntries,
getConcurrencyLimitActiveJobs,
getConcurrencyQueueJobsCount,
2024-12-11 19:46:11 -03:00
pushConcurrencyLimitActiveJob,
2024-12-11 19:51:08 -03:00
pushConcurrencyLimitedJob,
2024-12-11 19:46:11 -03:00
} from "../lib/concurrency-limit";
import { logger } from "../lib/logger";
import { getConcurrencyLimitMax } from "./rate-limiter";
2024-04-15 17:01:47 -04:00
2024-12-15 23:54:52 +01:00
async function _addScrapeJobToConcurrencyQueue(
webScraperOptions: any,
options: any,
jobId: string,
jobPriority: number,
) {
await pushConcurrencyLimitedJob(webScraperOptions.team_id, {
id: jobId,
data: webScraperOptions,
opts: {
...options,
priority: jobPriority,
jobId: jobId,
},
priority: jobPriority,
});
}
2024-12-27 19:59:26 +01:00
export async function _addScrapeJobToBullMQ(
2024-12-15 23:54:52 +01:00
webScraperOptions: any,
options: any,
jobId: string,
jobPriority: number,
) {
if (
webScraperOptions &&
webScraperOptions.team_id &&
webScraperOptions.plan
) {
await pushConcurrencyLimitActiveJob(webScraperOptions.team_id, jobId, 60 * 1000); // 60s default timeout
2024-12-15 23:54:52 +01:00
}
await getScrapeQueue().add(jobId, webScraperOptions, {
...options,
priority: jobPriority,
jobId,
});
}
async function addScrapeJobRaw(
webScraperOptions: any,
options: any,
jobId: string,
2024-12-15 23:54:52 +01:00
jobPriority: number,
2024-10-25 20:21:12 +02:00
) {
let concurrencyLimited = false;
let currentActiveConcurrency = 0;
let maxConcurrency = 0;
2024-10-25 20:21:12 +02:00
2024-12-11 19:46:11 -03:00
if (
webScraperOptions &&
webScraperOptions.team_id
2024-12-11 19:46:11 -03:00
) {
2024-10-25 20:21:12 +02:00
const now = Date.now();
maxConcurrency = getConcurrencyLimitMax(webScraperOptions.plan ?? "free", webScraperOptions.team_id);
2024-10-25 20:21:12 +02:00
cleanOldConcurrencyLimitEntries(webScraperOptions.team_id, now);
currentActiveConcurrency = (await getConcurrencyLimitActiveJobs(webScraperOptions.team_id, now)).length;
concurrencyLimited = currentActiveConcurrency >= maxConcurrency;
2024-10-25 20:21:12 +02:00
}
const concurrencyQueueJobs = await getConcurrencyQueueJobsCount(webScraperOptions.team_id);
2024-10-25 20:21:12 +02:00
if (concurrencyLimited) {
// Detect if they hit their concurrent limit
// If above by 2x, send them an email
// No need to 2x as if there are more than the max concurrency in the concurrency queue, it is already 2x
if(concurrencyQueueJobs > maxConcurrency) {
2025-03-13 13:05:12 -04:00
logger.info("Concurrency limited 2x (single) - ", "Concurrency queue jobs: ", concurrencyQueueJobs, "Max concurrency: ", maxConcurrency, "Team ID: ", webScraperOptions.team_id);
// sendNotificationWithCustomDays(webScraperOptions.team_id, NotificationType.CONCURRENCY_LIMIT_REACHED, 10, false).catch((error) => {
// logger.error("Error sending notification (concurrency limit reached): ", error);
// });
}
webScraperOptions.concurrencyLimited = true;
2024-12-17 16:58:57 -03:00
await _addScrapeJobToConcurrencyQueue(
webScraperOptions,
options,
jobId,
jobPriority,
);
2024-10-25 20:21:12 +02:00
} else {
2024-12-15 23:54:52 +01:00
await _addScrapeJobToBullMQ(webScraperOptions, options, jobId, jobPriority);
2024-10-25 20:21:12 +02:00
}
2024-07-30 14:44:13 -04:00
}
export async function addScrapeJob(
webScraperOptions: WebScraperOptions,
options: any = {},
jobId: string = uuidv4(),
2024-12-11 19:51:08 -03:00
jobPriority: number = 10,
2024-10-25 20:21:12 +02:00
) {
if (Sentry.isInitialized()) {
const size = JSON.stringify(webScraperOptions).length;
2024-12-11 19:46:11 -03:00
return await Sentry.startSpan(
{
name: "Add scrape job",
op: "queue.publish",
attributes: {
"messaging.message.id": jobId,
"messaging.destination.name": getScrapeQueue().name,
2024-12-11 19:51:08 -03:00
"messaging.message.body.size": size,
},
},
2024-12-11 19:46:11 -03:00
async (span) => {
await addScrapeJobRaw(
{
...webScraperOptions,
sentry: {
trace: Sentry.spanToTraceHeader(span),
baggage: Sentry.spanToBaggageHeader(span),
2024-12-11 19:51:08 -03:00
size,
},
2024-12-11 19:46:11 -03:00
},
options,
jobId,
2024-12-11 19:51:08 -03:00
jobPriority,
2024-12-11 19:46:11 -03:00
);
2024-12-11 19:51:08 -03:00
},
2024-12-11 19:46:11 -03:00
);
} else {
2024-10-25 20:21:12 +02:00
await addScrapeJobRaw(webScraperOptions, options, jobId, jobPriority);
}
}
2024-10-25 20:21:12 +02:00
export async function addScrapeJobs(
jobs: {
2024-12-11 19:46:11 -03:00
data: WebScraperOptions;
2024-10-25 20:21:12 +02:00
opts: {
2024-12-11 19:46:11 -03:00
jobId: string;
priority: number;
};
2024-12-11 19:51:08 -03:00
}[],
2024-10-25 20:21:12 +02:00
) {
if (jobs.length === 0) return true;
2024-12-15 23:54:52 +01:00
let countCanBeDirectlyAdded = Infinity;
let currentActiveConcurrency = 0;
let maxConcurrency = 0;
2024-12-15 23:54:52 +01:00
2024-12-17 16:58:57 -03:00
if (jobs[0].data && jobs[0].data.team_id && jobs[0].data.plan) {
2024-12-15 23:54:52 +01:00
const now = Date.now();
maxConcurrency = getConcurrencyLimitMax(jobs[0].data.plan as PlanType, jobs[0].data.team_id);
2024-12-15 23:54:52 +01:00
cleanOldConcurrencyLimitEntries(jobs[0].data.team_id, now);
currentActiveConcurrency = (await getConcurrencyLimitActiveJobs(jobs[0].data.team_id, now)).length;
2024-12-17 16:58:57 -03:00
countCanBeDirectlyAdded = Math.max(
maxConcurrency - currentActiveConcurrency,
2024-12-17 16:58:57 -03:00
0,
);
2024-12-15 23:54:52 +01:00
}
const addToBull = jobs.slice(0, countCanBeDirectlyAdded);
const addToCQ = jobs.slice(countCanBeDirectlyAdded);
// equals 2x the max concurrency
if(addToCQ.length > maxConcurrency) {
2025-03-13 13:05:12 -04:00
logger.info("Concurrency limited 2x (multiple) - ", "Concurrency queue jobs: ", addToCQ.length, "Max concurrency: ", maxConcurrency, "Team ID: ", jobs[0].data.team_id);
// sendNotificationWithCustomDays(jobs[0].data.team_id, NotificationType.CONCURRENCY_LIMIT_REACHED, 10, false).catch((error) => {
// logger.error("Error sending notification (concurrency limit reached): ", error);
// });
}
2024-12-15 23:54:52 +01:00
await Promise.all(
addToBull.map(async (job) => {
const size = JSON.stringify(job.data).length;
return await Sentry.startSpan(
{
name: "Add scrape job",
op: "queue.publish",
attributes: {
"messaging.message.id": job.opts.jobId,
"messaging.destination.name": getScrapeQueue().name,
"messaging.message.body.size": size,
},
},
async (span) => {
await _addScrapeJobToBullMQ(
{
...job.data,
sentry: {
trace: Sentry.spanToTraceHeader(span),
baggage: Sentry.spanToBaggageHeader(span),
size,
},
},
job.opts,
job.opts.jobId,
job.opts.priority,
);
},
);
}),
);
2024-12-11 19:46:11 -03:00
await Promise.all(
2024-12-15 23:54:52 +01:00
addToCQ.map(async (job) => {
const size = JSON.stringify(job.data).length;
return await Sentry.startSpan(
{
name: "Add scrape job",
op: "queue.publish",
attributes: {
"messaging.message.id": job.opts.jobId,
"messaging.destination.name": getScrapeQueue().name,
"messaging.message.body.size": size,
},
},
async (span) => {
await _addScrapeJobToConcurrencyQueue(
{
...job.data,
sentry: {
trace: Sentry.spanToTraceHeader(span),
baggage: Sentry.spanToBaggageHeader(span),
size,
},
},
job.opts,
job.opts.jobId,
job.opts.priority,
);
},
);
}),
2024-12-11 19:46:11 -03:00
);
2024-10-25 20:21:12 +02:00
}
2024-12-11 19:46:11 -03:00
export function waitForJob<T = unknown>(
jobId: string,
2024-12-11 19:51:08 -03:00
timeout: number,
2024-12-11 19:46:11 -03:00
): Promise<T> {
2024-08-23 18:27:00 +02:00
return new Promise((resolve, reject) => {
const start = Date.now();
const int = setInterval(async () => {
if (Date.now() >= start + timeout) {
clearInterval(int);
reject(new Error("Job wait "));
2024-08-23 19:14:49 +02:00
} else {
const state = await getScrapeQueue().getJobState(jobId);
if (state === "completed") {
clearInterval(int);
2024-11-07 20:57:33 +01:00
resolve((await getScrapeQueue().getJob(jobId))!.returnvalue);
2024-08-23 19:14:49 +02:00
} else if (state === "failed") {
// console.log("failed", (await getScrapeQueue().getJob(jobId)).failedReason);
2024-09-26 20:39:19 +02:00
const job = await getScrapeQueue().getJob(jobId);
if (job && job.failedReason !== "Concurrency limit hit") {
2024-09-26 20:39:19 +02:00
clearInterval(int);
reject(job.failedReason);
}
2024-08-23 19:14:49 +02:00
}
2024-08-23 18:27:00 +02:00
}
2024-11-24 19:48:57 -08:00
}, 250);
2024-12-11 19:46:11 -03:00
});
2024-08-23 18:27:00 +02:00
}