Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

Merge branch 'main' into nsc/job-priority

Nicolas1e08e6d31750
diff --cc apps/api/src/controllers/crawl.ts
index 7bd9b373f,c5f440e2d..d2123d827
--- a/apps/api/src/controllers/crawl.ts
+++ b/apps/api/src/controllers/crawl.ts
@@@ -144,16 -163,7 +165,15 @@@ export async function crawlController(r
? null
: await crawler.tryGetSitemap();
- if (sitemap !== null) {
-
++
+ if (sitemap !== null && sitemap.length > 0) {
+ let jobPriority = 20;
+ // If it is over 1000, we need to get the job priority,
+ // otherwise we can use the default priority of 20
+ if(sitemap.length > 1000){
+ // set base to 21
+ jobPriority = await getJobPriority({plan, team_id, basePriority: 21})
+ }
-
const jobs = sitemap.map((x) => {
const url = x.url;
const uuid = uuidv4();
@@@ -184,13 -194,16 +204,20 @@@
id,
jobs.map((x) => x.opts.jobId)
);
- await getScrapeQueue().addBulk(jobs);
+ if (Sentry.isInitialized()) {
+ for (const job of jobs) {
+ // add with sentry instrumentation
+ await addScrapeJob(job.data as any, {}, job.opts.jobId);
+ }
+ } else {
+ await getScrapeQueue().addBulk(jobs);
+ }
} else {
await lockURL(id, sc, url);
+
+ // Not needed, first one should be 15.
+ // const jobPriority = await getJobPriority({plan, team_id, basePriority: 10})
+
const job = await addScrapeJob(
{
url,
diff --cc apps/api/src/controllers/scrape.ts
index f33aa058f,0b4df13cc..1ff9a4268
--- a/apps/api/src/controllers/scrape.ts
+++ b/apps/api/src/controllers/scrape.ts
@@@ -9,10 -9,9 +9,10 @@@ import { isUrlBlocked } from "../scrape
import { numTokensFromString } from '../lib/LLM-extraction/helpers';
import { defaultPageOptions, defaultExtractorOptions, defaultTimeout, defaultOrigin } from '../lib/default-values';
import { addScrapeJob } from '../services/queue-jobs';
- import { scrapeQueueEvents } from '../services/queue-service';
+ import { getScrapeQueue } from '../services/queue-service';
import { v4 as uuidv4 } from "uuid";
import { Logger } from '../lib/logger';
+import { getJobPriority } from '../lib/job-priority';
import * as Sentry from "@sentry/node";
export async function scrapeHelper(
@@@ -49,21 -46,54 +49,54 @@@
pageOptions,
extractorOptions,
origin: req.body.origin ?? defaultOrigin,
- }, {}, jobId);
+ }, {}, jobId, jobPriority);
let doc;
- try {
- doc = (await job.waitUntilFinished(scrapeQueueEvents, timeout))[0]; //60 seconds timeout
- } catch (e) {
- if (e instanceof Error && e.message.startsWith("Job wait")) {
- return {
- success: false,
- error: "Request timed out",
- returnCode: 408,
+
+ const err = await Sentry.startSpan({ name: "Wait for job to finish", op: "bullmq.wait", attributes: { job: jobId } }, async (span) => {
+ try {
+ doc = (await new Promise((resolve, reject) => {
+ const start = Date.now();
+ const int = setInterval(async () => {
+ if (Date.now() >= start + timeout) {
+ clearInterval(int);
+ reject(new Error("Job wait "));
+ } else {
+ const state = await job.getState();
+ if (state === "completed") {
+ clearInterval(int);
+ resolve((await getScrapeQueue().getJob(job.id)).returnvalue);
+ } else if (state === "failed") {
+ clearInterval(int);
+ reject((await getScrapeQueue().getJob(job.id)).failedReason);
+ }
+ }
+ }, 1000);
+ }))[0]
+ } catch (e) {
+ if (e instanceof Error && e.message.startsWith("Job wait")) {
+ span.setAttribute("timedOut", true);
+ return {
+ success: false,
+ error: "Request timed out",
+ returnCode: 408,
+ }
+ } else if (typeof e === "string" && (e.includes("Error generating completions: ") || e.includes("Invalid schema for function") || e.includes("LLM extraction did not match the extraction schema you provided."))) {
+ return {
+ success: false,
+ error: e,
+ returnCode: 500,
+ };
+ } else {
+ throw e;
}
- } else {
- throw e;
}
+ span.setAttribute("result", JSON.stringify(doc));
+ return null;
+ });
+
+ if (err !== null) {
+ return err;
}
await job.remove();
diff --cc apps/api/src/controllers/search.ts
index a8bf3a696,aeb044d89..92efe1df2
--- a/apps/api/src/controllers/search.ts
+++ b/apps/api/src/controllers/search.ts
@@@ -9,9 -9,9 +9,10 @@@ import { search } from "../search"
import { isUrlBlocked } from "../scraper/WebScraper/utils/blocklist";
import { v4 as uuidv4 } from "uuid";
import { Logger } from "../lib/logger";
- import { getScrapeQueue, scrapeQueueEvents } from "../services/queue-service";
+import { getJobPriority } from "../lib/job-priority";
+ import { getScrapeQueue } from "../services/queue-service";
import * as Sentry from "@sentry/node";
+ import { addScrapeJob } from "../services/queue-jobs";
export async function searchHelper(
jobId: string,
diff --cc apps/api/src/services/queue-jobs.ts
index eb7e47272,888cdefc7..740f48a22
--- a/apps/api/src/services/queue-jobs.ts
+++ b/apps/api/src/services/queue-jobs.ts
@@@ -2,19 -2,47 +2,52 @@@ import { Job, Queue } from "bullmq"
import { getScrapeQueue } from "./queue-service";
import { v4 as uuidv4 } from "uuid";
import { WebScraperOptions } from "../types";
+ import * as Sentry from "@sentry/node";
- export async function addScrapeJob(
- webScraperOptions: WebScraperOptions,
- options: any = {},
- jobId: string = uuidv4(),
+ async function addScrapeJobRaw(
+ webScraperOptions: any,
+ options: any,
+ jobId: string,
+ jobPriority: number = 10
): Promise<Job> {
return await getScrapeQueue().add(jobId, webScraperOptions, {
- priority: jobPriority,
...options,
- priority: webScraperOptions.crawl_id ? 20 : 10,
++ priority: jobPriority,
jobId,
});
}
+ export async function addScrapeJob(
+ webScraperOptions: WebScraperOptions,
+ options: any = {},
+ jobId: string = uuidv4(),
++ jobPriority: number = 10
+ ): Promise<Job> {
++
+ if (Sentry.isInitialized()) {
+ const size = JSON.stringify(webScraperOptions).length;
+ return await Sentry.startSpan({
+ name: "Add scrape job",
+ op: "queue.publish",
+ attributes: {
+ "messaging.message.id": jobId,
+ "messaging.destination.name": getScrapeQueue().name,
+ "messaging.message.body.size": size,
+ },
+ }, async (span) => {
+ return await addScrapeJobRaw({
+ ...webScraperOptions,
+ sentry: {
+ trace: Sentry.spanToTraceHeader(span),
+ baggage: Sentry.spanToBaggageHeader(span),
+ size,
+ },
- }, options, jobId);
++ }, options, jobId, jobPriority);
+ });
+ } else {
- return await addScrapeJobRaw(webScraperOptions, options, jobId);
++ return await addScrapeJobRaw(webScraperOptions, options, jobId, jobPriority);
+ }
+ }
+
+
+
diff --cc apps/api/src/services/queue-worker.ts
index 1a61e02cd,a7d20383e..ca1a4cbd8
--- a/apps/api/src/services/queue-worker.ts
+++ b/apps/api/src/services/queue-worker.ts
@@@ -52,7 -50,7 +52,8 @@@ const processJobInternal = async (token
await job.extendLock(token, jobLockExtensionTime);
}, jobLockExtendInterval);
+ await addJobPriority(job.data.team_id, job.id );
+ let err = null;
try {
const result = await processJob(job, token);
try{
@@@ -65,11 -63,14 +66,15 @@@
}
} catch (error) {
console.log("Job failed, error:", error);
+ Sentry.captureException(error);
+ err = error;
await job.moveToFailed(error, token, false);
} finally {
+ await deleteJobPriority(job.data.team_id, job.id );
clearInterval(extendLockInterval);
}
+
+ return err;
};
let isShuttingDown = false;