Spaces:
Sleeping
Sleeping
File size: 7,788 Bytes
097eaf0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | import { Response } from "express";
import { config } from "../../config";
import { v7 as uuidv7 } from "uuid";
import {
BatchScrapeRequest,
batchScrapeRequestSchema,
batchScrapeRequestSchemaNoURLValidation,
URL as urlSchema,
RequestWithAuth,
ScrapeOptions,
BatchScrapeResponse,
} from "./types";
import {
addCrawlJobs,
finishCrawlKickoff,
getCrawl,
lockURLs,
markCrawlActive,
saveCrawl,
StoredCrawl,
} from "../../lib/crawl-redis";
import { getJobPriority } from "../../lib/job-priority";
import { addScrapeJobs } from "../../services/queue-jobs";
import { createWebhookSender, WebhookEvent } from "../../services/webhook";
import { logger as _logger } from "../../lib/logger";
import { UNSUPPORTED_SITE_MESSAGE } from "../../lib/strings";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import { checkPermissions } from "../../lib/permissions";
import { crawlGroup } from "../../services/worker/nuq";
import { logRequest } from "../../services/logging/log_job";
import type { BillingMetadata } from "../../services/billing/types";
import { getScrapeZDR } from "../../lib/zdr-helpers";
export async function batchScrapeController(
req: RequestWithAuth<{}, BatchScrapeResponse, BatchScrapeRequest>,
res: Response<BatchScrapeResponse>,
) {
const preNormalizedBody = { ...req.body };
if (req.body?.ignoreInvalidURLs === true) {
req.body = batchScrapeRequestSchemaNoURLValidation.parse(req.body);
} else {
req.body = batchScrapeRequestSchema.parse(req.body);
}
const permissions = checkPermissions(req.body, req.acuc?.flags);
if (permissions.error) {
return res.status(403).json({
success: false,
error: permissions.error,
});
}
const zeroDataRetention =
getScrapeZDR(req.acuc?.flags) === "forced" || (req.body.zeroDataRetention ?? false);
if (
req.body.__agentInterop &&
config.AGENT_INTEROP_SECRET &&
req.body.__agentInterop.auth !== config.AGENT_INTEROP_SECRET
) {
return res.status(403).json({
success: false,
error: "Invalid agent interop.",
});
} else if (req.body.__agentInterop && !config.AGENT_INTEROP_SECRET) {
return res.status(403).json({
success: false,
error: "Agent interop is not enabled.",
});
}
const id = req.body.appendToId ?? uuidv7();
const billing: BillingMetadata = req.body.__agentInterop
? { endpoint: "agent" as const, jobId: id }
: { endpoint: "batch_scrape" as const, jobId: id };
const logger = _logger.child({
crawlId: id,
batchScrapeId: id,
module: "api/v2",
method: "batchScrapeController",
teamId: req.auth.team_id,
zeroDataRetention,
});
let urls: string[] = req.body.urls;
let unnormalizedURLs = preNormalizedBody.urls;
let invalidURLs: string[] | undefined = undefined;
if (req.body.ignoreInvalidURLs) {
invalidURLs = [];
let pendingURLs = urls;
urls = [];
unnormalizedURLs = [];
for (const u of pendingURLs) {
try {
const nu = urlSchema.parse(u);
if (
!isUrlBlocked(nu, req.acuc?.flags ?? null, {
team_id: req.auth.team_id,
origin: req.body.origin ?? null,
})
) {
urls.push(nu);
unnormalizedURLs.push(u);
} else {
invalidURLs.push(u);
}
} catch (_) {
invalidURLs.push(u);
}
}
} else {
if (
req.body.urls?.some((url: string) =>
isUrlBlocked(url, req.acuc?.flags ?? null, {
team_id: req.auth.team_id,
origin: req.body.origin ?? null,
}),
)
) {
if (!res.headersSent) {
return res.status(403).json({
success: false,
error: UNSUPPORTED_SITE_MESSAGE,
});
}
}
}
if (urls.length === 0) {
return res.status(400).json({
success: false,
error: "No valid URLs provided",
});
}
logger.debug("Batch scrape " + id + " starting", {
urlsLength: urls.length,
appendToId: req.body.appendToId,
account: req.account,
});
if (!req.body.appendToId && !req.body.__agentInterop) {
await logRequest({
id,
kind: "batch_scrape",
api_version: "v2",
team_id: req.auth.team_id,
origin: req.body.origin ?? "api",
integration: req.body.integration,
target_hint: urls[0] ?? "",
zeroDataRetention: zeroDataRetention || false,
api_key_id: req.acuc?.api_key_id ?? null,
});
}
const sc: StoredCrawl = req.body.appendToId
? ((await getCrawl(req.body.appendToId)) as StoredCrawl)
: {
crawlerOptions: null,
scrapeOptions: req.body,
internalOptions: {
disableSmartWaitCache: true,
teamId: req.auth.team_id,
saveScrapeResultToGCS: config.GCS_FIRE_ENGINE_BUCKET_NAME
? true
: false,
zeroDataRetention,
bypassBilling: !(req.body.__agentInterop?.shouldBill ?? true),
agentIndexOnly: (req as any).agentIndexOnly ?? false,
}, // NOTE: smart wait disabled for batch scrapes to ensure contentful scrape, speed does not matter
team_id: req.auth.team_id,
createdAt: Date.now(),
maxConcurrency: req.body.maxConcurrency,
zeroDataRetention,
};
if (req.body.appendToId) {
if (!sc || sc.team_id !== req.auth.team_id) {
return res.status(404).json({
success: false,
error: "Job not found",
});
}
}
if (!req.body.appendToId) {
await crawlGroup.addGroup(
id,
sc.team_id,
(req.acuc?.flags?.crawlTtlHours ?? 24) * 60 * 60 * 1000,
);
await saveCrawl(id, sc);
await markCrawlActive(id);
}
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 (urls.length > 1000) {
// set base to 21
jobPriority = await getJobPriority({
team_id: req.auth.team_id,
basePriority: 21,
});
}
logger.debug("Using job priority " + jobPriority, { jobPriority });
const scrapeOptions: ScrapeOptions = { ...req.body };
delete (scrapeOptions as any).urls;
delete (scrapeOptions as any).appendToId;
const jobs = urls.map(x => ({
jobId: uuidv7(),
data: {
url: x,
mode: "single_urls" as const,
team_id: req.auth.team_id,
crawlerOptions: null,
scrapeOptions,
origin: "api",
integration: req.body.integration,
billing,
crawl_id: id,
requestId: req.body.__agentInterop?.requestId ?? undefined,
bypassBilling: !(req.body.__agentInterop?.shouldBill ?? true),
sitemapped: true,
v1: true,
webhook: req.body.webhook,
internalOptions: sc.internalOptions,
zeroDataRetention,
apiKeyId: req.acuc?.api_key_id ?? null,
},
priority: jobPriority,
}));
await finishCrawlKickoff(id);
logger.debug("Locking URLs...");
await lockURLs(
id,
sc,
jobs.map(x => x.data.url),
logger,
);
logger.debug("Adding scrape jobs to Redis...");
await addCrawlJobs(
id,
jobs.map(x => x.jobId),
logger,
);
logger.debug("Adding scrape jobs to BullMQ...");
await addScrapeJobs(jobs);
if (req.body.webhook) {
logger.debug("Calling webhook with batch_scrape.started...", {
webhook: req.body.webhook,
});
const sender = await createWebhookSender({
teamId: req.auth.team_id,
jobId: id,
webhook: req.body.webhook,
v0: false,
});
await sender?.send(WebhookEvent.BATCH_SCRAPE_STARTED, { success: true });
}
const protocol = req.protocol;
return res.status(200).json({
success: true,
id,
url: `${protocol}://${req.get("host")}/v2/batch/scrape/${id}`,
invalidURLs,
});
}
|