A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
refactor: split crawler file into separate modules (#2933)
Mohamed Bassemb2c52c9c8879
diff --git a/apps/workers/workers/crawler/assetStorage.ts b/apps/workers/workers/crawler/assetStorage.tsnew file mode 100644index 00000000..2f3bc696--- /dev/null+++ b/apps/workers/workers/crawler/assetStorage.ts@@ -0,0 +1,557 @@+// Everything that persists crawl outputs as assets: screenshots, PDFs,+// banner images (including data: URIs from precrawled archives), large HTML+// content, downloaded files, and monolith full-page archives. All of these+// are quota-checked before writing.+import { promises as fs } from "fs";+import * as fsSync from "fs";+import * as path from "node:path";+import * as os from "os";+import { Transform } from "stream";+import { pipeline } from "stream/promises";+import { dataUriToBuffer } from "data-uri-to-buffer";+import type { MimeBuffer } from "data-uri-to-buffer";+import { execa } from "execa";+import { fetchWithProxy, getBookmarkDomain } from "network";+import type { RunProxyConfig } from "network";++import { db } from "@karakeep/db";+import { getTracer, QuotaService, withSpan } from "@karakeep/shared-server";+import {+ ASSET_TYPES,+ getAssetSize,+ IMAGE_ASSET_TYPES,+ newAssetId,+ saveAsset,+ saveAssetFromFile,+} from "@karakeep/shared/assetdb";+import serverConfig from "@karakeep/shared/config";+import logger from "@karakeep/shared/logger";+import { tryCatch } from "@karakeep/shared/tryCatch";++import { normalizeContentType, truncateUrl } from "./utils";++const tracer = getTracer("@karakeep/workers");++export async function storeScreenshot(+ screenshot: Buffer | undefined,+ userId: string,+ jobId: string,+) {+ return await withSpan(+ tracer,+ "crawlerWorker.storeScreenshot",+ {+ attributes: {+ "job.id": jobId,+ "user.id": userId,+ "asset.size": screenshot?.byteLength ?? 0,+ },+ },+ async () => {+ if (!serverConfig.crawler.storeScreenshot) {+ logger.info(+ `[Crawler][${jobId}] Skipping storing the screenshot as per the config.`,+ );+ return null;+ }+ if (!screenshot) {+ logger.info(+ `[Crawler][${jobId}] Skipping storing the screenshot as it's empty.`,+ );+ return null;+ }+ const assetId = newAssetId();+ const contentType = "image/jpeg";+ const fileName = "screenshot.jpeg";++ // Check storage quota before saving the screenshot+ const { data: quotaApproved, error: quotaError } = await tryCatch(+ QuotaService.checkStorageQuota(db, userId, screenshot.byteLength),+ );++ if (quotaError) {+ logger.warn(+ `[Crawler][${jobId}] Skipping screenshot storage due to quota exceeded: ${quotaError.message}`,+ );+ return null;+ }++ await saveAsset({+ userId,+ assetId,+ metadata: { contentType, fileName },+ asset: screenshot,+ quotaApproved,+ });+ logger.info(+ `[Crawler][${jobId}] Stored the screenshot as assetId: ${assetId} (${screenshot.byteLength} bytes)`,+ );+ return { assetId, contentType, fileName, size: screenshot.byteLength };+ },+ );+}++export async function storePdf(+ pdf: Buffer | undefined,+ userId: string,+ jobId: string,+) {+ return await withSpan(+ tracer,+ "crawlerWorker.storePdf",+ {+ attributes: {+ "job.id": jobId,+ "user.id": userId,+ "asset.size": pdf?.byteLength ?? 0,+ },+ },+ async () => {+ if (!pdf) {+ logger.info(+ `[Crawler][${jobId}] Skipping storing the PDF as it's empty.`,+ );+ return null;+ }+ const assetId = newAssetId();+ const contentType = "application/pdf";+ const fileName = "page.pdf";++ // Check storage quota before saving the PDF+ const { data: quotaApproved, error: quotaError } = await tryCatch(+ QuotaService.checkStorageQuota(db, userId, pdf.byteLength),+ );++ if (quotaError) {+ logger.warn(+ `[Crawler][${jobId}] Skipping PDF storage due to quota exceeded: ${quotaError.message}`,+ );+ return null;+ }++ await saveAsset({+ userId,+ assetId,+ metadata: { contentType, fileName },+ asset: pdf,+ quotaApproved,+ });+ logger.info(+ `[Crawler][${jobId}] Stored the PDF as assetId: ${assetId} (${pdf.byteLength} bytes)`,+ );+ return { assetId, contentType, fileName, size: pdf.byteLength };+ },+ );+}++/**+ * SingleFile / precrawled archives inline images as `data:` URIs, so the image+ * URL metascraper extracts can be a base64 blob rather than something fetchable+ * over the network. Decode it locally and store it as an asset instead of+ * failing on the unsupported protocol.+ */+async function storeDataUriAsset(+ url: string,+ userId: string,+ jobId: string,+ fileType: string,+) {+ const maxBytes = serverConfig.maxAssetSizeMb * 1024 * 1024;++ // Guardrail 1: cap the size *before* decoding into memory. base64 encodes 3+ // bytes per 4 chars, so a URI longer than 4/3 the limit (plus header slack)+ // must decode past it; the exact check below handles the rest.+ if (url.length > Math.ceil((maxBytes * 4) / 3) + 1024) {+ logger.warn(+ `[Crawler][${jobId}] Skipping data URI ${fileType}: encoded size (${url.length} chars) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,+ );+ return null;+ }++ let asset: MimeBuffer;+ try {+ asset = dataUriToBuffer(url);+ } catch (e) {+ logger.error(+ `[Crawler][${jobId}] Failed to decode data URI ${fileType}: ${e}`,+ );+ return null;+ }++ // Guardrail 2: never trust the declared mediatype for anything but the raster+ // image types we actually serve as banners. Rejects svg/html/etc.;+ // saveAsset's SUPPORTED_ASSET_TYPES check is the backstop.+ const contentType = normalizeContentType(asset.type);+ if (!contentType || !IMAGE_ASSET_TYPES.has(contentType)) {+ logger.warn(+ `[Crawler][${jobId}] Skipping data URI ${fileType} with unsupported content type: ${contentType}`,+ );+ return null;+ }++ if (asset.byteLength > maxBytes) {+ logger.warn(+ `[Crawler][${jobId}] Skipping data URI ${fileType}: decoded size (${asset.byteLength} bytes) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,+ );+ return null;+ }++ const { data: quotaApproved, error: quotaError } = await tryCatch(+ QuotaService.checkStorageQuota(db, userId, asset.byteLength),+ );+ if (quotaError) {+ logger.warn(+ `[Crawler][${jobId}] Skipping data URI ${fileType} storage due to quota exceeded: ${quotaError.message}`,+ );+ return null;+ }++ const assetId = newAssetId();+ await saveAsset({+ userId,+ assetId,+ metadata: { contentType },+ asset,+ quotaApproved,+ });+ logger.info(+ `[Crawler][${jobId}] Stored data URI ${fileType} as assetId: ${assetId} (${asset.byteLength} bytes)`,+ );+ return { assetId, userId, contentType, size: asset.byteLength };+}++export async function downloadAndStoreFile(+ url: string,+ userId: string,+ jobId: string,+ fileType: string,+ abortSignal: AbortSignal,+ runProxy: RunProxyConfig,+) {+ return await withSpan(+ tracer,+ "crawlerWorker.downloadAndStoreFile",+ {+ attributes: {+ "bookmark.url": url,+ "bookmark.domain": getBookmarkDomain(url),+ "job.id": jobId,+ "user.id": userId,+ "asset.type": fileType,+ },+ },+ async () => {+ let assetPath: string | undefined;+ try {+ if (url.startsWith("data:")) {+ return await storeDataUriAsset(url, userId, jobId, fileType);+ }+ logger.info(+ `[Crawler][${jobId}] Downloading ${fileType} from "${truncateUrl(url)}"`,+ );+ const response = await fetchWithProxy(+ url,+ {+ signal: abortSignal,+ },+ runProxy,+ );+ if (!response.ok || response.body == null) {+ throw new Error(`Failed to download ${fileType}: ${response.status}`);+ }++ const contentType = normalizeContentType(+ response.headers.get("content-type"),+ );+ if (!contentType) {+ throw new Error("No content type in the response");+ }++ const assetId = newAssetId();+ assetPath = path.join(os.tmpdir(), assetId);++ let bytesRead = 0;+ const contentLengthEnforcer = new Transform({+ transform(chunk, _, callback) {+ bytesRead += chunk.length;++ if (abortSignal.aborted) {+ callback(new Error("AbortError"));+ } else if (bytesRead > serverConfig.maxAssetSizeMb * 1024 * 1024) {+ callback(+ new Error(+ `Content length exceeds maximum allowed size: ${serverConfig.maxAssetSizeMb}MB`,+ ),+ );+ } else {+ callback(null, chunk); // pass data along unchanged+ }+ },+ flush(callback) {+ callback();+ },+ });++ await pipeline(+ response.body,+ contentLengthEnforcer,+ fsSync.createWriteStream(assetPath),+ );++ // Check storage quota before saving the asset+ const { data: quotaApproved, error: quotaError } = await tryCatch(+ QuotaService.checkStorageQuota(db, userId, bytesRead),+ );++ if (quotaError) {+ logger.warn(+ `[Crawler][${jobId}] Skipping ${fileType} storage due to quota exceeded: ${quotaError.message}`,+ );+ return null;+ }++ await saveAssetFromFile({+ userId,+ assetId,+ metadata: { contentType },+ assetPath,+ quotaApproved,+ });++ logger.info(+ `[Crawler][${jobId}] Downloaded ${fileType} as assetId: ${assetId} (${bytesRead} bytes)`,+ );++ return { assetId, userId, contentType, size: bytesRead };+ } catch (e) {+ logger.error(+ `[Crawler][${jobId}] Failed to download and store ${fileType}: ${e}`,+ );+ return null;+ } finally {+ if (assetPath) {+ await tryCatch(fs.unlink(assetPath));+ }+ }+ },+ );+}++export async function downloadAndStoreImage(+ url: string,+ userId: string,+ jobId: string,+ abortSignal: AbortSignal,+ runProxy: RunProxyConfig,+) {+ if (!serverConfig.crawler.downloadBannerImage) {+ logger.info(+ `[Crawler][${jobId}] Skipping downloading the image as per the config.`,+ );+ return null;+ }+ return downloadAndStoreFile(+ url,+ userId,+ jobId,+ "image",+ abortSignal,+ runProxy,+ );+}++export async function archiveWebpage(+ html: string,+ url: string,+ userId: string,+ jobId: string,+ abortSignal: AbortSignal,+ runProxy: RunProxyConfig,+) {+ return await withSpan(+ tracer,+ "crawlerWorker.archiveWebpage",+ {+ attributes: {+ "bookmark.url": url,+ "bookmark.domain": getBookmarkDomain(url),+ "job.id": jobId,+ "user.id": userId,+ },+ },+ async () => {+ logger.info(`[Crawler][${jobId}] Will attempt to archive page ...`);++ {+ // Archival is a heavy operation, so we need to check if the user is within reasonable quota before proceeding+ const { error: quotaError } = await tryCatch(+ QuotaService.checkStorageQuota(db, userId, /* estimated size */ 1024),+ );+ if (quotaError) {+ logger.warn(+ `[Crawler][${jobId}] Skipping archival as the user has exceeded their quota: ${quotaError.message}`,+ );+ return null;+ }+ }++ const assetId = newAssetId();+ const assetPath = path.join(os.tmpdir(), assetId);++ let res = await execa({+ input: html,+ cancelSignal: abortSignal,+ env: {+ https_proxy: runProxy.httpsProxy,+ http_proxy: runProxy.httpProxy,+ no_proxy: runProxy.noProxy?.join(","),+ },+ })("monolith", [+ "-",+ "-Ije",+ "-t",+ String(serverConfig.crawler.monolithTimeoutSec),+ ...serverConfig.crawler.monolithArguments,+ "-b",+ url,+ "-o",+ assetPath,+ ]);++ if (res.isCanceled) {+ logger.error(+ `[Crawler][${jobId}] Canceled archiving the page as we hit global timeout.`,+ );+ await tryCatch(fs.unlink(assetPath));+ return null;+ }++ if (res.exitCode !== 0) {+ logger.error(+ `[Crawler][${jobId}] Failed to archive the page as the command exited with code ${res.exitCode}`,+ );+ await tryCatch(fs.unlink(assetPath));+ return null;+ }++ const contentType = "text/html";++ // Get file size and check quota before saving+ const stats = await fs.stat(assetPath);+ const fileSize = stats.size;++ const { data: quotaApproved, error: quotaError } = await tryCatch(+ QuotaService.checkStorageQuota(db, userId, fileSize),+ );++ if (quotaError) {+ logger.warn(+ `[Crawler][${jobId}] Skipping page archive storage due to quota exceeded: ${quotaError.message}`,+ );+ await tryCatch(fs.unlink(assetPath));+ return null;+ }++ await saveAssetFromFile({+ userId,+ assetId,+ assetPath,+ metadata: {+ contentType,+ },+ quotaApproved,+ });++ logger.info(+ `[Crawler][${jobId}] Done archiving the page as assetId: ${assetId}`,+ );++ return {+ assetId,+ contentType,+ size: await getAssetSize({ userId, assetId }),+ };+ },+ );+}++export type StoreHtmlResult =+ | { result: "stored"; assetId: string; size: number }+ | { result: "store_inline" }+ | { result: "not_stored" };++export async function storeHtmlContent(+ htmlContent: string | undefined,+ userId: string,+ jobId: string,+): Promise<StoreHtmlResult> {+ return await withSpan(+ tracer,+ "crawlerWorker.storeHtmlContent",+ {+ attributes: {+ "job.id": jobId,+ "user.id": userId,+ "bookmark.content.size": htmlContent+ ? Buffer.byteLength(htmlContent, "utf8")+ : 0,+ },+ },+ async () => {+ if (!htmlContent) {+ return { result: "not_stored" };+ }++ const contentSize = Buffer.byteLength(htmlContent, "utf8");++ // Only store in assets if content is >= 50KB+ if (contentSize < serverConfig.crawler.htmlContentSizeThreshold) {+ logger.info(+ `[Crawler][${jobId}] HTML content size (${contentSize} bytes) is below threshold, storing inline`,+ );+ return { result: "store_inline" };+ }++ const { data: quotaApproved, error: quotaError } = await tryCatch(+ QuotaService.checkStorageQuota(db, userId, contentSize),+ );+ if (quotaError) {+ logger.warn(+ `[Crawler][${jobId}] Skipping HTML content storage due to quota exceeded: ${quotaError.message}`,+ );+ return { result: "not_stored" };+ }++ const assetId = newAssetId();++ const { error: saveError } = await tryCatch(+ saveAsset({+ userId,+ assetId,+ asset: Buffer.from(htmlContent, "utf8"),+ metadata: {+ contentType: ASSET_TYPES.TEXT_HTML,+ fileName: null,+ },+ quotaApproved,+ }),+ );+ if (saveError) {+ logger.error(+ `[Crawler][${jobId}] Failed to store HTML content as asset: ${saveError}`,+ );+ throw saveError;+ }++ logger.info(+ `[Crawler][${jobId}] Stored large HTML content (${contentSize} bytes) as asset: ${assetId}`,+ );++ return {+ result: "stored",+ assetId,+ size: contentSize,+ };+ },+ );+}diff --git a/apps/workers/workers/crawler/browser.ts b/apps/workers/workers/crawler/browser.tsnew file mode 100644index 00000000..4a96b0d6--- /dev/null+++ b/apps/workers/workers/crawler/browser.ts@@ -0,0 +1,285 @@+// Manages the shared browser environment used by the crawler: the global+// browser connection (and its reconnect-on-disconnect loop), the adblocker,+// the cookie jar loaded from disk, and the tracking/reaping of browser+// contexts so leaked ones eventually get closed.+import * as dns from "dns";+import { promises as fs } from "fs";+import * as path from "node:path";+import * as os from "os";+import { PlaywrightBlocker } from "@ghostery/adblocker-playwright";+import { Mutex } from "async-mutex";+import { exitAbortController } from "exit";+import { fetchWithProxy } from "network";+import type { RunProxyConfig } from "network";+import { Browser, BrowserContext, BrowserContextOptions } from "playwright";+import { chromium } from "playwright-extra";+import StealthPlugin from "puppeteer-extra-plugin-stealth";+import { raceWith, timeoutRace } from "utils";+import { z } from "zod";++import serverConfig from "@karakeep/shared/config";+import logger from "@karakeep/shared/logger";+import { setUrlHostnameFromResolvedAddress } from "@karakeep/shared/utils/url";+import { tryCatch } from "@karakeep/shared/tryCatch";++import { redactUrlCredentials } from "./utils";++interface Cookie {+ name: string;+ value: string;+ domain?: string;+ path?: string;+ expires?: number;+ httpOnly?: boolean;+ secure?: boolean;+ sameSite?: "Strict" | "Lax" | "None";+}++const cookieSchema = z.object({+ name: z.string(),+ value: z.string(),+ domain: z.string().optional(),+ path: z.string().optional(),+ expires: z.number().optional(),+ httpOnly: z.boolean().optional(),+ secure: z.boolean().optional(),+ sameSite: z.enum(["Strict", "Lax", "None"]).optional(),+});++const cookiesSchema = z.array(cookieSchema);++let globalBrowser: Browser | undefined;+let globalBlocker: PlaywrightBlocker | undefined;+// Global variable to store parsed cookies+let globalCookies: Cookie[] = [];+// Guards the interactions with the browser instance.+// This is needed given that most of the browser APIs are async.+const browserMutex = new Mutex();++// Tracks active browser contexts so we can reap leaked ones.+const activeContexts = new Map<+ string,+ { context: BrowserContext; createdAt: number }+>();++export const CONTEXT_CLOSE_TIMEOUT_MS = 10_000;+export const PAGE_CLOSE_TIMEOUT_MS = 5_000;++export function getGlobalBrowser(): Browser | undefined {+ return globalBrowser;+}++export function getGlobalBlocker(): PlaywrightBlocker | undefined {+ return globalBlocker;+}++export function getGlobalCookies(): Cookie[] {+ return globalCookies;+}++export function trackContext(jobId: string, context: BrowserContext): void {+ activeContexts.set(jobId, { context, createdAt: Date.now() });+}++export function untrackContext(jobId: string): void {+ activeContexts.delete(jobId);+}++export function getPlaywrightProxyConfig(+ runProxy: RunProxyConfig,+): BrowserContextOptions["proxy"] {+ const proxyUrl = runProxy.httpsProxy || runProxy.httpProxy;+ if (!proxyUrl) {+ return undefined;+ }++ const parsed = new URL(proxyUrl);++ return {+ server: proxyUrl,+ username: parsed.username,+ password: parsed.password,+ bypass: runProxy.noProxy?.join(","),+ };+}++/**+ * Reaps browser contexts that have been open longer than the max job timeout.+ * This is a safety net for cases where context.close() hangs or is never called.+ */+function startContextReaper() {+ const maxContextAgeMs =+ (serverConfig.crawler.jobTimeoutSec + 30) * 1000 ++ 60_000 * 5; /* 5 minutes buffer */+ const intervalId = setInterval(() => {+ try {+ const now = Date.now();+ for (const [id, entry] of activeContexts) {+ if (now - entry.createdAt > maxContextAgeMs) {+ logger.warn(+ `[Crawler] Reaping stale browser context for job ${id} (age: ${Math.round((now - entry.createdAt) / 1000)}s)`,+ );+ void raceWith<boolean>(+ entry.context+ .close()+ .then(() => true)+ .catch((e: unknown) => {+ logger.warn(+ `[Crawler] Failed to close stale context for job ${id}: ${e}`,+ );+ return true;+ }),+ timeoutRace<boolean>(CONTEXT_CLOSE_TIMEOUT_MS, () => false),+ ).then((contextClosed) => {+ // Protect against deleting a newer context if the job id gets reused.+ if (!contextClosed) {+ logger.warn(+ `[Crawler] Timed out closing stale context for job ${id} — keeping in active set for retry`,+ );+ return;+ }+ if (activeContexts.get(id) === entry) {+ activeContexts.delete(id);+ }+ });+ }+ }+ } catch (e) {+ logger.error(+ `[Crawler] caught an unexpected error while reaping stale browser contexts: ${e}`,+ );+ }+ }, 60_000 * 5);+ exitAbortController.signal.addEventListener(+ "abort",+ () => clearInterval(intervalId),+ {+ once: true,+ },+ );+}++export async function startBrowserInstance() {+ if (serverConfig.crawler.browserWebSocketUrl) {+ logger.info(+ `[Crawler] Connecting to existing browser websocket address: ${redactUrlCredentials(serverConfig.crawler.browserWebSocketUrl)}`,+ );+ return await chromium.connect(serverConfig.crawler.browserWebSocketUrl, {+ timeout: 5000,+ });+ } else if (serverConfig.crawler.browserWebUrl) {+ logger.info(+ `[Crawler] Connecting to existing browser instance: ${redactUrlCredentials(serverConfig.crawler.browserWebUrl)}`,+ );++ const webUrl = new URL(serverConfig.crawler.browserWebUrl);+ const { address } = await dns.promises.lookup(webUrl.hostname);+ setUrlHostnameFromResolvedAddress(webUrl, address);+ logger.info(+ `[Crawler] Successfully resolved IP address, new address: ${redactUrlCredentials(webUrl.toString())}`,+ );++ return await chromium.connectOverCDP(webUrl.toString(), {+ timeout: 5000,+ });+ } else {+ logger.info(`Running in browserless mode`);+ return undefined;+ }+}++async function launchBrowser() {+ globalBrowser = undefined;+ await browserMutex.runExclusive(async () => {+ const globalBrowserResult = await tryCatch(startBrowserInstance());+ if (globalBrowserResult.error) {+ logger.error(+ `[Crawler] Failed to connect to the browser instance, will retry in 5 secs: ${globalBrowserResult.error.stack}`,+ );+ if (exitAbortController.signal.aborted) {+ logger.info("[Crawler] We're shutting down so won't retry.");+ return;+ }+ setTimeout(() => {+ launchBrowser();+ }, 5000);+ return;+ }+ globalBrowser = globalBrowserResult.data;+ globalBrowser?.on("disconnected", () => {+ if (exitAbortController.signal.aborted) {+ logger.info(+ "[Crawler] The Playwright browser got disconnected. But we're shutting down so won't restart it.",+ );+ return;+ }+ logger.info(+ "[Crawler] The Playwright browser got disconnected. Will attempt to launch it again.",+ );+ launchBrowser();+ });+ });+}++async function loadAdblocker(): Promise<void> {+ if (!serverConfig.crawler.enableAdblocker) {+ return;+ }+ logger.info("[crawler] Loading adblocker ...");+ const globalBlockerResult = await tryCatch(+ PlaywrightBlocker.fromPrebuiltFull(fetchWithProxy, {+ path: path.join(os.tmpdir(), "karakeep_adblocker.bin"),+ read: fs.readFile,+ write: fs.writeFile,+ }),+ );+ if (globalBlockerResult.error) {+ logger.error(+ `[crawler] Failed to load adblocker. Will not be blocking ads: ${globalBlockerResult.error}`,+ );+ } else {+ globalBlocker = globalBlockerResult.data;+ }+}++async function loadCookiesFromFile(): Promise<void> {+ try {+ const path = serverConfig.crawler.browserCookiePath;+ if (!path) {+ logger.info(+ "[Crawler] Not defined in the server configuration BROWSER_COOKIE_PATH",+ );+ return;+ }+ const data = await fs.readFile(path, "utf8");+ const cookies = JSON.parse(data);+ globalCookies = cookiesSchema.parse(cookies);+ } catch (error) {+ logger.error("Failed to read or parse cookies file:", error);+ if (error instanceof z.ZodError) {+ logger.error("[Crawler] Invalid cookie file format:", error.issues);+ } else {+ logger.error("[Crawler] Failed to read or parse cookies file:", error);+ }+ throw error;+ }+}++/**+ * One-time setup of the crawler's browser environment: stealth plugin,+ * adblocker, the shared browser connection (unless connecting on demand),+ * cookies, and the stale-context reaper.+ */+export async function initializeBrowserEnvironment(): Promise<void> {+ chromium.use(StealthPlugin());+ await loadAdblocker();+ if (!serverConfig.crawler.browserConnectOnDemand) {+ await launchBrowser();+ } else {+ logger.info(+ "[Crawler] Browser connect on demand is enabled, won't proactively start the browser instance",+ );+ }+ await loadCookiesFromFile();+ startContextReaper();+}diff --git a/apps/workers/workers/crawler/crawlAndParse.ts b/apps/workers/workers/crawler/crawlAndParse.tsnew file mode 100644index 00000000..09e00b71--- /dev/null+++ b/apps/workers/workers/crawler/crawlAndParse.ts@@ -0,0 +1,513 @@+// Orchestrates a single bookmark crawl: fetches the page (browser render or+// precrawled archive), parses it, merges the probe/render metadata, and+// persists the results (metadata first for fast feedback, then contents and+// assets). Also handles URLs that turn out to be plain assets (pdf/image) by+// converting the link bookmark into an asset bookmark.+import * as path from "node:path";+import { eq } from "drizzle-orm";+import { crawlerStatusCodeCounter } from "metrics";+import { getBookmarkDomain } from "network";+import type { RunProxyConfig } from "network";+import { abortRace, raceWith } from "utils";+import { updateAsset } from "workerUtils";++import { db } from "@karakeep/db";+import {+ assets,+ AssetTypes,+ bookmarkAssets,+ bookmarkLinks,+ bookmarks,+} from "@karakeep/db/schema";+import {+ addLogFields,+ AssetPreprocessingQueue,+ getTracer,+ setSpanAttributes,+ withSpan,+} from "@karakeep/shared-server";+import {+ ASSET_TYPES,+ readAsset,+ silentDeleteAsset,+} from "@karakeep/shared/assetdb";+import serverConfig from "@karakeep/shared/config";+import logger from "@karakeep/shared/logger";+import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";++import type { ParseSubprocessOutput } from "../utils/parseHtmlSubprocessIpc";+import {+ isLikelyChallengePage,+ resolveMetadata,+} from "../utils/metadataResolver";+import {+ archiveWebpage,+ downloadAndStoreFile,+ downloadAndStoreImage,+ storeHtmlContent,+ storePdf,+ storeScreenshot,+} from "./assetStorage";+import { crawlPage } from "./crawlPage";+import { runParseSubprocess } from "./parseSubprocess";+import { redactUrlCredentials, shouldRetryCrawlStatusCode } from "./utils";++const tracer = getTracer("@karakeep/workers");++type DBAssetType = typeof assets.$inferInsert;++/**+ * Downloads the asset from the URL and transforms the linkBookmark to an assetBookmark+ * @param url the url the user provided+ * @param assetType the type of the asset we're downloading+ * @param userId the id of the user+ * @param jobId the id of the job for logging+ * @param bookmarkId the id of the bookmark+ */+export async function handleAsAssetBookmark(+ url: string,+ assetType: "image" | "pdf",+ userId: string,+ jobId: string,+ bookmarkId: string,+ abortSignal: AbortSignal,+ runProxy: RunProxyConfig,+) {+ return await withSpan(+ tracer,+ "crawlerWorker.handleAsAssetBookmark",+ {+ attributes: {+ "bookmark.url": url,+ "bookmark.domain": getBookmarkDomain(url),+ "job.id": jobId,+ "user.id": userId,+ "bookmark.id": bookmarkId,+ "asset.type": assetType,+ },+ },+ async () => {+ const downloaded = await downloadAndStoreFile(+ url,+ userId,+ jobId,+ assetType,+ abortSignal,+ runProxy,+ );+ if (!downloaded) {+ return;+ }+ const fileName = path.basename(new URL(url).pathname);+ await db.transaction(async (trx) => {+ await updateAsset(+ undefined,+ {+ id: downloaded.assetId,+ bookmarkId,+ userId,+ assetType: AssetTypes.BOOKMARK_ASSET,+ contentType: downloaded.contentType,+ size: downloaded.size,+ fileName,+ },+ trx,+ );+ await trx.insert(bookmarkAssets).values({+ id: bookmarkId,+ assetType,+ assetId: downloaded.assetId,+ content: null,+ fileName,+ sourceUrl: url,+ });+ // Switch the type of the bookmark from LINK to ASSET+ await trx+ .update(bookmarks)+ .set({ type: BookmarkTypes.ASSET })+ .where(eq(bookmarks.id, bookmarkId));+ await trx.delete(bookmarkLinks).where(eq(bookmarkLinks.id, bookmarkId));+ });+ await AssetPreprocessingQueue.enqueue(+ {+ bookmarkId,+ fixMode: false,+ },+ {+ groupId: userId,+ },+ );+ },+ );+}++export interface CrawlAndParseUrlArgs {+ url: string;+ userId: string;+ jobId: string;+ bookmarkId: string;+ /** Asset ids from a previous crawl of this bookmark, replaced (and deleted) on success. */+ oldAssets: {+ screenshotAssetId: string | undefined;+ pdfAssetId: string | undefined;+ imageAssetId: string | undefined;+ fullPageArchiveAssetId: string | undefined;+ contentAssetId: string | undefined;+ };+ precrawledArchiveAssetId: string | undefined;+ archiveFullPage: boolean;+ forceStorePdf: boolean;+ numRetriesLeft: number;+ abortSignal: AbortSignal;+ runProxy: RunProxyConfig;+ probeMetadataPromise: Promise<ParseSubprocessOutput["metadata"] | null>;+}++/**+ * Crawls the url, parses it, and persists the bookmark's metadata, content,+ * and assets. Returns a closure that runs the (failure-prone) full-page+ * archival, so the caller can defer it to the very end of the job.+ */+export async function crawlAndParseUrl(+ args: CrawlAndParseUrlArgs,+): Promise<() => Promise<void>> {+ const {+ url,+ userId,+ jobId,+ bookmarkId,+ oldAssets,+ precrawledArchiveAssetId,+ archiveFullPage,+ forceStorePdf,+ numRetriesLeft,+ abortSignal,+ runProxy,+ probeMetadataPromise,+ } = args;+ const sanitizedProxyUrl = redactUrlCredentials(+ runProxy.httpsProxy ?? runProxy.httpProxy ?? "",+ );++ return await withSpan(+ tracer,+ "crawlerWorker.crawlAndParseUrl",+ {+ attributes: {+ "bookmark.url": url,+ "bookmark.domain": getBookmarkDomain(url),+ "job.id": jobId,+ "user.id": userId,+ "bookmark.id": bookmarkId,+ "crawler.archiveFullPage": archiveFullPage,+ "crawler.forceStorePdf": forceStorePdf,+ "crawler.hasPrecrawledArchive": !!precrawledArchiveAssetId,+ "crawler.proxy": sanitizedProxyUrl,+ },+ },+ async () => {+ let result: {+ htmlContent: string;+ screenshot: Buffer | undefined;+ pdf: Buffer | undefined;+ statusCode: number | null;+ url: string;+ };++ if (precrawledArchiveAssetId) {+ logger.info(+ `[Crawler][${jobId}] The page has been precrawled. Will use the precrawled archive instead.`,+ );+ const asset = await readAsset({+ userId,+ assetId: precrawledArchiveAssetId,+ });+ result = {+ htmlContent: asset.asset.toString(),+ screenshot: undefined,+ pdf: undefined,+ statusCode: 200,+ url,+ };+ } else {+ result = await crawlPage(+ jobId,+ url,+ userId,+ forceStorePdf,+ abortSignal,+ runProxy,+ );+ }+ abortSignal.throwIfAborted();++ const {+ htmlContent,+ screenshot,+ pdf,+ statusCode,+ url: browserUrl,+ } = result;++ // Track status code in Prometheus+ if (statusCode !== null) {+ crawlerStatusCodeCounter+ .labels(statusCode.toString(), sanitizedProxyUrl)+ .inc();+ setSpanAttributes({+ "crawler.statusCode": statusCode,+ });+ }+ addLogFields<"crawlerWorker.run">({+ "crawler.status_code": statusCode,+ });++ if (shouldRetryCrawlStatusCode(statusCode)) {+ if (numRetriesLeft > 0) {+ throw new Error(+ `[Crawler][${jobId}] Received status code ${statusCode}. Will retry crawl. Retries left: ${numRetriesLeft}`,+ );+ }+ logger.info(+ `[Crawler][${jobId}] Received status code ${statusCode} on latest retry attempt. Proceeding without retry.`,+ );+ }++ const { metadata: renderMeta, readableContent: parsedReadableContent } =+ await runParseSubprocess(htmlContent, browserUrl, jobId, abortSignal);+ abortSignal.throwIfAborted();++ // The probe metadata extraction has been running alongside the crawl;+ // this is the point where it's needed. The promise never rejects and+ // all its underlying work is time-bounded.+ const probeMetadata = await probeMetadataPromise;+ abortSignal.throwIfAborted();++ // On the last retry attempt the crawl proceeds despite a blocked status+ // code, and some bot walls serve their challenge page with a 200; in+ // both cases don't let that page's metadata override clean values from+ // the preflight probe.+ const renderBlocked =+ shouldRetryCrawlStatusCode(statusCode) ||+ isLikelyChallengePage({ title: renderMeta.title, htmlContent });+ addLogFields<"crawlerWorker.run">({+ "crawler.render_blocked": renderBlocked,+ });+ if (renderBlocked && probeMetadata) {+ logger.info(+ `[Crawler][${jobId}] The rendered page looks blocked (status ${statusCode}); preferring preflight probe metadata.`,+ );+ }+ const meta = resolveMetadata(renderMeta, probeMetadata, renderBlocked);++ const parseDate = (date: string | null | undefined) => {+ if (!date) {+ return null;+ }+ try {+ return new Date(date);+ } catch {+ return null;+ }+ };++ // Phase 1: Write metadata immediately for fast user feedback.+ // Content and asset storage happen later and can be slow (banner+ // image download, screenshot/pdf upload, etc.).+ await db+ .update(bookmarkLinks)+ .set({+ title: meta.title,+ description: meta.description,+ // Don't store data URIs as they're not valid URLs and are usually quite large+ imageUrl: meta.image?.startsWith("data:") ? null : meta.image,+ favicon: meta.logo,+ crawlStatusCode: statusCode,+ author: meta.author,+ publisher: meta.publisher,+ datePublished: parseDate(meta.datePublished),+ dateModified: parseDate(meta.dateModified),+ })+ .where(eq(bookmarkLinks.id, bookmarkId));++ let readableContent = parsedReadableContent;++ const screenshotAssetInfo = await raceWith(+ storeScreenshot(screenshot, userId, jobId),+ abortRace(abortSignal),+ );+ abortSignal.throwIfAborted();++ const pdfAssetInfo = await raceWith(+ storePdf(pdf, userId, jobId),+ abortRace(abortSignal),+ );+ abortSignal.throwIfAborted();++ const htmlContentAssetInfo = await storeHtmlContent(+ readableContent?.content,+ userId,+ jobId,+ );+ abortSignal.throwIfAborted();+ let imageAssetInfo: DBAssetType | null = null;+ if (meta.image) {+ const downloaded = await downloadAndStoreImage(+ meta.image,+ userId,+ jobId,+ abortSignal,+ runProxy,+ );+ if (downloaded) {+ imageAssetInfo = {+ id: downloaded.assetId,+ bookmarkId,+ userId,+ assetType: AssetTypes.LINK_BANNER_IMAGE,+ contentType: downloaded.contentType,+ size: downloaded.size,+ };+ }+ }+ abortSignal.throwIfAborted();++ // Phase 2: Write content and asset references.+ // TODO(important): Restrict the size of content to store+ const assetDeletionTasks: Promise<void>[] = [];+ const inlineHtmlContent =+ htmlContentAssetInfo.result === "store_inline"+ ? (readableContent?.content ?? null)+ : null;+ readableContent = null;+ await db.transaction(async (txn) => {+ await txn+ .update(bookmarkLinks)+ .set({+ crawledAt: new Date(),+ htmlContent: inlineHtmlContent,+ contentAssetId:+ htmlContentAssetInfo.result === "stored"+ ? htmlContentAssetInfo.assetId+ : null,+ })+ .where(eq(bookmarkLinks.id, bookmarkId));++ if (screenshotAssetInfo) {+ await updateAsset(+ oldAssets.screenshotAssetId,+ {+ id: screenshotAssetInfo.assetId,+ bookmarkId,+ userId,+ assetType: AssetTypes.LINK_SCREENSHOT,+ contentType: screenshotAssetInfo.contentType,+ size: screenshotAssetInfo.size,+ fileName: screenshotAssetInfo.fileName,+ },+ txn,+ );+ assetDeletionTasks.push(+ silentDeleteAsset(userId, oldAssets.screenshotAssetId),+ );+ }+ if (pdfAssetInfo) {+ await updateAsset(+ oldAssets.pdfAssetId,+ {+ id: pdfAssetInfo.assetId,+ bookmarkId,+ userId,+ assetType: AssetTypes.LINK_PDF,+ contentType: pdfAssetInfo.contentType,+ size: pdfAssetInfo.size,+ fileName: pdfAssetInfo.fileName,+ },+ txn,+ );+ assetDeletionTasks.push(+ silentDeleteAsset(userId, oldAssets.pdfAssetId),+ );+ }+ if (imageAssetInfo) {+ await updateAsset(oldAssets.imageAssetId, imageAssetInfo, txn);+ assetDeletionTasks.push(+ silentDeleteAsset(userId, oldAssets.imageAssetId),+ );+ }+ if (htmlContentAssetInfo.result === "stored") {+ await updateAsset(+ oldAssets.contentAssetId,+ {+ id: htmlContentAssetInfo.assetId,+ bookmarkId,+ userId,+ assetType: AssetTypes.LINK_HTML_CONTENT,+ contentType: ASSET_TYPES.TEXT_HTML,+ size: htmlContentAssetInfo.size,+ fileName: null,+ },+ txn,+ );+ assetDeletionTasks.push(+ silentDeleteAsset(userId, oldAssets.contentAssetId),+ );+ } else if (oldAssets.contentAssetId) {+ // Unlink the old content asset+ await txn+ .delete(assets)+ .where(eq(assets.id, oldAssets.contentAssetId));+ assetDeletionTasks.push(+ silentDeleteAsset(userId, oldAssets.contentAssetId),+ );+ }+ });++ // Delete the old assets if any+ await Promise.all(assetDeletionTasks);++ return async () => {+ if (+ !precrawledArchiveAssetId &&+ (serverConfig.crawler.fullPageArchive || archiveFullPage)+ ) {+ const archiveResult = await archiveWebpage(+ htmlContent,+ browserUrl,+ userId,+ jobId,+ abortSignal,+ runProxy,+ );++ if (archiveResult) {+ const {+ assetId: fullPageArchiveAssetId,+ size,+ contentType,+ } = archiveResult;++ await db.transaction(async (txn) => {+ await updateAsset(+ oldAssets.fullPageArchiveAssetId,+ {+ id: fullPageArchiveAssetId,+ bookmarkId,+ userId,+ assetType: AssetTypes.LINK_FULL_PAGE_ARCHIVE,+ contentType,+ size,+ fileName: null,+ },+ txn,+ );+ });+ if (oldAssets.fullPageArchiveAssetId) {+ await silentDeleteAsset(userId, oldAssets.fullPageArchiveAssetId);+ }+ }+ }+ };+ },+ );+}diff --git a/apps/workers/workers/crawler/crawlPage.ts b/apps/workers/workers/crawler/crawlPage.tsnew file mode 100644index 00000000..e17a1338--- /dev/null+++ b/apps/workers/workers/crawler/crawlPage.ts@@ -0,0 +1,754 @@+// The browser-based page fetch: navigates to the URL in a Playwright context+// (with redirect/sub-request SSRF guards, adblocking, and proxy auth) and+// captures the page's HTML, an optional screenshot, and an optional PDF.+// Falls back to a plain HTTP fetch when no browser is available or the user+// has browser crawling disabled.+import { eq } from "drizzle-orm";+import {+ fetchWithProxy,+ getBookmarkDomain,+ matchesNoProxy,+ validateUrl,+} from "network";+import type { RunProxyConfig } from "network";+import {+ Browser,+ BrowserContext,+ BrowserContextOptions,+ CDPSession,+ Page,+} from "playwright";+import { abortRace, abortRaceResolve, raceWith, timeoutRace } from "utils";++import { db } from "@karakeep/db";+import { users } from "@karakeep/db/schema";+import {+ getTracer,+ setSpanAttributes,+ withSpan,+} from "@karakeep/shared-server";+import serverConfig from "@karakeep/shared/config";+import logger from "@karakeep/shared/logger";+import { tryCatch } from "@karakeep/shared/tryCatch";++import {+ CONTEXT_CLOSE_TIMEOUT_MS,+ PAGE_CLOSE_TIMEOUT_MS,+ getGlobalBlocker,+ getGlobalBrowser,+ getGlobalCookies,+ getPlaywrightProxyConfig,+ startBrowserInstance,+ trackContext,+ untrackContext,+} from "./browser";+import { truncateUrl } from "./utils";++const tracer = getTracer("@karakeep/workers");++export interface CrawlPageResult {+ htmlContent: string;+ screenshot: Buffer | undefined;+ pdf: Buffer | undefined;+ statusCode: number;+ url: string;+}++function getHeaderValue(+ headers: { name: string; value: string }[] | undefined,+ name: string,+): string | undefined {+ return headers?.find((header) => header.name.toLowerCase() === name)?.value;+}++async function browserlessCrawlPage(+ jobId: string,+ url: string,+ abortSignal: AbortSignal,+ runProxy: RunProxyConfig,+): Promise<CrawlPageResult> {+ return await withSpan(+ tracer,+ "crawlerWorker.browserlessCrawlPage",+ {+ attributes: {+ "bookmark.url": url,+ "bookmark.domain": getBookmarkDomain(url),+ "job.id": jobId,+ },+ },+ async () => {+ logger.info(+ `[Crawler][${jobId}] Running in browserless mode. Will do a plain http request to "${truncateUrl(url)}". Screenshots will be disabled.`,+ );+ const response = await fetchWithProxy(+ url,+ {+ signal: AbortSignal.any([AbortSignal.timeout(5000), abortSignal]),+ },+ runProxy,+ );+ logger.info(+ `[Crawler][${jobId}] Successfully fetched the content of "${truncateUrl(url)}". Status: ${response.status}, Size: ${response.size}`,+ );+ return {+ htmlContent: await response.text(),+ statusCode: response.status,+ screenshot: undefined,+ pdf: undefined,+ url: response.url,+ };+ },+ );+}++/**+ * Installs a CDP-level guard that validates every redirect target before the+ * browser follows it (blocking redirects into disallowed/internal addresses)+ * and answers proxy auth challenges with the run's proxy credentials.+ */+async function installRedirectGuard(+ context: BrowserContext,+ page: Page,+ jobId: string,+ proxyConfig: BrowserContextOptions["proxy"],+): Promise<CDPSession | undefined> {+ let cdpSession: CDPSession | undefined;++ try {+ cdpSession = await context.newCDPSession(page);+ const continuePausedRequest = async (requestId: string) => {+ await cdpSession+ ?.send("Fetch.continueRequest", { requestId })+ .catch(() => {+ // Ignore errors — the request may have been canceled.+ });+ };+ const failPausedRequest = async (requestId: string) => {+ await cdpSession+ ?.send("Fetch.failRequest", {+ requestId,+ errorReason: "BlockedByClient",+ })+ .catch(() => {+ // Ignore errors — the request may have been canceled.+ });+ };+ cdpSession.on("Fetch.authRequired", async (event) => {+ const authChallengeResponse =+ event.authChallenge.source === "Proxy" &&+ (proxyConfig?.username || proxyConfig?.password)+ ? {+ response: "ProvideCredentials" as const,+ username: proxyConfig.username ?? "",+ password: proxyConfig.password ?? "",+ }+ : { response: "Default" as const };+ await cdpSession+ ?.send("Fetch.continueWithAuth", {+ requestId: event.requestId,+ authChallengeResponse,+ })+ .catch(() => {+ // Ignore errors — the request may have been canceled.+ });+ });+ cdpSession.on("Fetch.requestPaused", async (event) => {+ try {+ const status = event.responseStatusCode;+ if (!status || status < 300 || status >= 400) {+ await continuePausedRequest(event.requestId);+ return;+ }++ const location = getHeaderValue(event.responseHeaders, "location");+ if (!location) {+ await continuePausedRequest(event.requestId);+ return;+ }++ const redirectUrl = new URL(location, event.request.url).toString();+ const redirectIsRunningInProxyContext =+ proxyConfig !== undefined &&+ !matchesNoProxy(redirectUrl, proxyConfig.bypass?.split(",") ?? []);+ const validation = await validateUrl(+ redirectUrl,+ redirectIsRunningInProxyContext,+ );++ if (validation.ok) {+ await continuePausedRequest(event.requestId);+ return;+ }++ logger.warn(+ `[Crawler][${jobId}] Blocking redirect to disallowed URL "${redirectUrl}": ${validation.reason}`,+ );+ await failPausedRequest(event.requestId);+ } catch (e) {+ logger.warn(+ `[Crawler][${jobId}] Blocking redirect after redirect guard failed: ${e}`,+ );+ await failPausedRequest(event.requestId);+ }+ });+ await cdpSession.send("Fetch.enable", {+ handleAuthRequests: true,+ patterns: [+ { urlPattern: "*", requestStage: "Request" },+ { urlPattern: "*", requestStage: "Response" },+ ],+ });+ } catch (e) {+ logger.warn(`[Crawler][${jobId}] Failed to install redirect guard: ${e}`);+ }++ return cdpSession;+}++/**+ * Creates and configures the page: redirect guard, adblocking, dialog+ * auto-dismissal, media/SSRF request blocking, and abort wiring.+ */+async function setupPage(+ context: BrowserContext,+ jobId: string,+ proxyConfig: BrowserContextOptions["proxy"],+ abortSignal: AbortSignal,+): Promise<Page> {+ return await withSpan(+ tracer,+ "crawlerWorker.crawlPage.setupPage",+ {+ attributes: {+ "job.id": jobId,+ },+ },+ async () => {+ // Create a new page in the context+ const nextPage = await context.newPage();+ const cdpSession = await installRedirectGuard(+ context,+ nextPage,+ jobId,+ proxyConfig,+ );++ // Apply ad blocking+ const globalBlocker = getGlobalBlocker();+ if (globalBlocker) {+ await globalBlocker.enableBlockingInPage(nextPage);+ }++ // Auto-dismiss JavaScript dialogs (alert, confirm, prompt)+ // to prevent pages from hanging during crawl.+ nextPage.on("dialog", (dialog) => {+ dialog.dismiss().catch(() => {+ // Ignore errors — the dialog may have already been closed.+ });+ });++ // Block audio/video resources and disallowed sub-requests+ await nextPage.route("**/*", async (route) => {+ if (abortSignal.aborted) {+ await route.abort("aborted");+ return;+ }+ const request = route.request();+ const resourceType = request.resourceType();++ // Block audio/video resources+ if (+ resourceType === "media" ||+ request.headers()["content-type"]?.includes("video/") ||+ request.headers()["content-type"]?.includes("audio/")+ ) {+ await route.abort("aborted");+ return;+ }++ const requestUrl = request.url();+ const requestIsRunningInProxyContext =+ proxyConfig !== undefined &&+ !matchesNoProxy(requestUrl, proxyConfig.bypass?.split(",") ?? []);+ if (+ requestUrl.startsWith("http://") ||+ requestUrl.startsWith("https://")+ ) {+ const validation = await validateUrl(+ requestUrl,+ requestIsRunningInProxyContext,+ );+ if (!validation.ok) {+ logger.warn(+ `[Crawler][${jobId}] Blocking sub-request to disallowed URL "${requestUrl}": ${validation.reason}`,+ );+ await route.abort("blockedbyclient");+ return;+ }+ }++ // Continue with other requests+ await route.fallback();+ });++ // On abort, immediately stop intercepting requests so that+ // in-flight route handlers don't block page/context closure.+ abortSignal.addEventListener(+ "abort",+ () => {+ cdpSession?.detach().catch(() => {+ // Ignore errors — the session may already be detached.+ });+ nextPage.unrouteAll({ behavior: "ignoreErrors" }).catch(() => {+ // Ignore errors — the page may already be closed.+ });+ },+ { once: true },+ );++ return nextPage;+ },+ );+}++/**+ * Extracts the page HTML and (depending on config) captures a screenshot and+ * a PDF, all in parallel.+ */+async function capturePageAssets(+ activePage: Page,+ jobId: string,+ forceStorePdf: boolean,+ abortSignal: AbortSignal,+): Promise<[string, Buffer | undefined, Buffer | undefined]> {+ return await withSpan(+ tracer,+ "crawlerWorker.crawlPage.captureAssets",+ {+ attributes: {+ "job.id": jobId,+ },+ },+ async () => {+ const htmlPromise = withSpan(+ tracer,+ "crawlerWorker.crawlPage.extractHtml",+ {+ attributes: {+ "job.id": jobId,+ },+ },+ async () => {+ const content = await activePage.content();+ abortSignal.throwIfAborted();+ logger.info(+ `[Crawler][${jobId}] Successfully fetched the page content.`,+ );+ return content;+ },+ );++ const screenshotPromise: Promise<Buffer | undefined> = serverConfig+ .crawler.storeScreenshot+ ? withSpan(+ tracer,+ "crawlerWorker.crawlPage.captureScreenshot",+ {+ attributes: {+ "job.id": jobId,+ "asset.type": "image",+ },+ },+ async () => {+ const { data: screenshotData, error: screenshotError } =+ await tryCatch(+ raceWith<Buffer>(+ activePage.screenshot({+ // If you change this, you need to change the asset type in the store function.+ type: "jpeg",+ fullPage: serverConfig.crawler.fullPageScreenshot,+ quality: 80,+ }),+ timeoutRace<Buffer>(+ serverConfig.crawler.screenshotTimeoutSec * 1000,+ () => {+ throw new Error(+ "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",+ );+ },+ ),+ abortRaceResolve(abortSignal, Buffer.from("")),+ ),+ );+ abortSignal.throwIfAborted();+ if (screenshotError) {+ logger.warn(+ `[Crawler][${jobId}] Failed to capture the screenshot. Reason: ${screenshotError}`,+ );+ return undefined;+ }+ setSpanAttributes({+ "asset.size": screenshotData.byteLength,+ });+ logger.info(+ `[Crawler][${jobId}] Finished capturing page content and a screenshot. FullPageScreenshot: ${serverConfig.crawler.fullPageScreenshot}`,+ );+ return screenshotData;+ },+ )+ : Promise.resolve(undefined);++ const pdfPromise: Promise<Buffer | undefined> =+ serverConfig.crawler.storePdf || forceStorePdf+ ? withSpan(+ tracer,+ "crawlerWorker.crawlPage.capturePdf",+ {+ attributes: {+ "job.id": jobId,+ "asset.type": "pdf",+ },+ },+ async () => {+ const { data: pdfData, error: pdfError } = await tryCatch(+ raceWith<Buffer>(+ activePage.pdf({+ format: "A4",+ printBackground: true,+ }),+ timeoutRace<Buffer>(+ serverConfig.crawler.screenshotTimeoutSec * 1000,+ () => {+ throw new Error(+ "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",+ );+ },+ ),+ abortRaceResolve(abortSignal, Buffer.from("")),+ ),+ );+ abortSignal.throwIfAborted();+ if (pdfError) {+ logger.warn(+ `[Crawler][${jobId}] Failed to capture the PDF. Reason: ${pdfError}`,+ );+ return undefined;+ }+ setSpanAttributes({+ "asset.size": pdfData.byteLength,+ });+ logger.info(+ `[Crawler][${jobId}] Finished capturing page content as PDF`,+ );+ return pdfData;+ },+ )+ : Promise.resolve(undefined);++ const captureResults = await Promise.all([+ htmlPromise,+ screenshotPromise,+ pdfPromise,+ ] as const);+ abortSignal.throwIfAborted();+ return captureResults;+ },+ );+}++/**+ * Closes the page and its context with timeouts so a hung close can't wedge+ * the job; contexts that fail to close stay tracked for the reaper. Also+ * closes the browser itself when it was connected on demand.+ */+async function closePageAndContext(+ page: Page | undefined,+ context: BrowserContext,+ browser: Browser,+ jobId: string,+): Promise<void> {+ await withSpan(+ tracer,+ "crawlerWorker.crawlPage.cleanup",+ {+ attributes: {+ "job.id": jobId,+ "crawler.cleanup.hasPage": !!page,+ },+ },+ async () => {+ // Explicitly close the page first (with timeout) to release resources+ // even if context.close() later hangs.+ if (page) {+ const pageToClose = page;+ const pageClosed = await withSpan(+ tracer,+ "crawlerWorker.crawlPage.cleanup.closePage",+ { attributes: { "job.id": jobId } },+ async () =>+ raceWith<boolean>(+ pageToClose+ .close()+ .then(() => true)+ .catch((e: unknown) => {+ logger.warn(`[Crawler][${jobId}] page.close() failed: ${e}`);+ return true;+ }),+ timeoutRace<boolean>(PAGE_CLOSE_TIMEOUT_MS, () => false),+ ),+ );+ setSpanAttributes({ "crawler.cleanup.pageClosed": pageClosed });+ if (!pageClosed) {+ logger.warn(`[Crawler][${jobId}] page.close() timed out`);+ }+ }++ // Close the context (with timeout) to avoid hanging on in-flight ops.+ // Only remove from tracking if close actually succeeded; otherwise+ // the reaper will retry the close later.+ const contextClosed = await withSpan(+ tracer,+ "crawlerWorker.crawlPage.cleanup.closeContext",+ { attributes: { "job.id": jobId } },+ async () =>+ raceWith<boolean>(+ context+ .close()+ .then(() => true)+ .catch((e: unknown) => {+ logger.warn(`[Crawler][${jobId}] context.close() failed: ${e}`);+ return true; // Error means it's likely already closed+ }),+ timeoutRace<boolean>(CONTEXT_CLOSE_TIMEOUT_MS, () => false),+ ),+ );+ setSpanAttributes({+ "crawler.cleanup.contextClosed": contextClosed,+ });++ if (contextClosed) {+ untrackContext(jobId);+ } else {+ logger.warn(+ `[Crawler][${jobId}] context.close() timed out — leaving in active set for reaper`,+ );+ }++ // Only close the browser if it was created on demand+ if (serverConfig.crawler.browserConnectOnDemand) {+ await withSpan(+ tracer,+ "crawlerWorker.crawlPage.cleanup.closeBrowser",+ { attributes: { "job.id": jobId } },+ async () =>+ browser+ .close()+ .then(() => {+ untrackContext(jobId);+ })+ .catch((e: unknown) => {+ logger.warn(`[Crawler][${jobId}] browser.close() failed: ${e}`);+ }),+ );+ }+ },+ );+}++export async function crawlPage(+ jobId: string,+ url: string,+ userId: string,+ forceStorePdf: boolean,+ abortSignal: AbortSignal,+ runProxy: RunProxyConfig,+ // When set, skips the per-user browserCrawlingEnabled DB lookup and uses this+ // value instead. Used by the adhoc crawl CLI, which has no user row.+ browserCrawlingEnabledOverride?: boolean,+): Promise<CrawlPageResult> {+ return await withSpan(+ tracer,+ "crawlerWorker.crawlPage",+ {+ attributes: {+ "bookmark.url": url,+ "bookmark.domain": getBookmarkDomain(url),+ "job.id": jobId,+ "user.id": userId,+ "crawler.forceStorePdf": forceStorePdf,+ },+ },+ async () => {+ let browserCrawlingEnabled: boolean | null;+ if (browserCrawlingEnabledOverride !== undefined) {+ browserCrawlingEnabled = browserCrawlingEnabledOverride;+ } else {+ const userData = await db.query.users.findFirst({+ where: eq(users.id, userId),+ columns: { browserCrawlingEnabled: true },+ });+ if (!userData) {+ logger.error(`[Crawler][${jobId}] User ${userId} not found`);+ throw new Error(`User ${userId} not found`);+ }+ browserCrawlingEnabled = userData.browserCrawlingEnabled;+ }++ if (browserCrawlingEnabled !== null && !browserCrawlingEnabled) {+ return browserlessCrawlPage(jobId, url, abortSignal, runProxy);+ }++ const browser = await withSpan(+ tracer,+ "crawlerWorker.crawlPage.getBrowserInstance",+ {+ attributes: {+ "job.id": jobId,+ },+ },+ async () => {+ if (serverConfig.crawler.browserConnectOnDemand) {+ return startBrowserInstance();+ }+ return getGlobalBrowser();+ },+ );+ if (!browser) {+ return browserlessCrawlPage(jobId, url, abortSignal, runProxy);+ }++ const proxyConfig = getPlaywrightProxyConfig(runProxy);+ const isRunningInProxyContext =+ proxyConfig !== undefined &&+ !matchesNoProxy(url, proxyConfig.bypass?.split(",") ?? []);+ const context = await withSpan(+ tracer,+ "crawlerWorker.crawlPage.createContext",+ {+ attributes: {+ "job.id": jobId,+ },+ },+ async () =>+ browser.newContext({+ viewport: { width: 1440, height: 900 },+ userAgent:+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",+ proxy: proxyConfig,+ serviceWorkers: "block",+ }),+ );++ trackContext(jobId, context);+ let page: Page | undefined;+ try {+ const globalCookies = getGlobalCookies();+ if (globalCookies.length > 0) {+ await context.addCookies(globalCookies);+ logger.info(+ `[Crawler][${jobId}] Cookies successfully loaded into browser context`,+ );+ }++ page = await setupPage(context, jobId, proxyConfig, abortSignal);++ // page is guaranteed to be assigned here; alias to a const for+ // TypeScript narrowing so the rest of the try block sees `Page`.+ const activePage = page;++ // Navigate to the target URL+ const navigationValidation = await withSpan(+ tracer,+ "crawlerWorker.crawlPage.validateNavigationTarget",+ {+ attributes: {+ "job.id": jobId,+ "bookmark.url": url,+ "bookmark.domain": getBookmarkDomain(url),+ },+ },+ async () => validateUrl(url, isRunningInProxyContext),+ );+ if (!navigationValidation.ok) {+ throw new Error(+ `Disallowed navigation target "${truncateUrl(url)}": ${navigationValidation.reason}`,+ );+ }+ const targetUrl = navigationValidation.url.toString();+ logger.info(`[Crawler][${jobId}] Navigating to "${targetUrl}"`);+ const response = await withSpan(+ tracer,+ "crawlerWorker.crawlPage.navigate",+ {+ attributes: {+ "job.id": jobId,+ "bookmark.url": targetUrl,+ "bookmark.domain": getBookmarkDomain(targetUrl),+ },+ },+ async () =>+ raceWith(+ activePage.goto(targetUrl, {+ timeout: serverConfig.crawler.navigateTimeoutSec * 1000,+ waitUntil: "domcontentloaded",+ }),+ abortRaceResolve(abortSignal, null),+ ),+ );+ setSpanAttributes({+ "crawler.statusCode": response?.status() ?? 0,+ });++ logger.info(+ `[Crawler][${jobId}] Successfully navigated to "${targetUrl}". Waiting for the page to load ...`,+ );++ // Wait until network is relatively idle or timeout after 5 seconds+ await withSpan(+ tracer,+ "crawlerWorker.crawlPage.waitForLoadState",+ {+ attributes: {+ "job.id": jobId,+ "bookmark.url": targetUrl,+ "bookmark.domain": getBookmarkDomain(targetUrl),+ },+ },+ async () => {+ await raceWith<unknown>(+ activePage+ .waitForLoadState("networkidle", { timeout: 5000 })+ .catch(() => ({})),+ timeoutRace<unknown>(5000, () => undefined),+ abortRace(abortSignal),+ );+ },+ );++ abortSignal.throwIfAborted();++ logger.info(+ `[Crawler][${jobId}] Finished waiting for the page to load.`,+ );++ const [htmlContent, screenshot, pdf] = await capturePageAssets(+ activePage,+ jobId,+ forceStorePdf,+ abortSignal,+ );++ return {+ htmlContent,+ statusCode: response?.status() ?? 0,+ screenshot,+ pdf,+ url: activePage.url(),+ };+ } finally {+ await closePageAndContext(page, context, browser, jobId);+ }+ },+ );+}diff --git a/apps/workers/workers/crawler/parseSubprocess.ts b/apps/workers/workers/crawler/parseSubprocess.tsnew file mode 100644index 00000000..3bf4db84--- /dev/null+++ b/apps/workers/workers/crawler/parseSubprocess.ts@@ -0,0 +1,149 @@+// Runs the HTML parsing (metadata extraction + readability) in a separate+// node process with a bounded heap, so a pathological page can't OOM the+// worker itself.+import { execa } from "execa";++import { getTracer, withSpan } from "@karakeep/shared-server";+import { getBookmarkDomain } from "network";+import serverConfig from "@karakeep/shared/config";+import logger from "@karakeep/shared/logger";++import type {+ ParseSubprocessError,+ ParseSubprocessOutput,+} from "../utils/parseHtmlSubprocessIpc";+import {+ parseSubprocessErrorSchema,+ parseSubprocessOutputSchema,+} from "../utils/parseHtmlSubprocessIpc";+import { truncateUrl } from "./utils";++const tracer = getTracer("@karakeep/workers");++function getSubprocessScriptPath(): string {+ const currentUrl = import.meta.url;+ if (currentUrl.includes("/dist/")) {+ // Production: running from built output+ return new URL("./scripts/parseHtmlSubprocess.js", currentUrl).pathname;+ }+ // Dev mode: running via tsx+ return new URL("../../scripts/parseHtmlSubprocess.ts", currentUrl).pathname;+}++function getSubprocessCommand(): { cmd: string; args: string[] } {+ const scriptPath = getSubprocessScriptPath();+ const maxOldSpaceSize = serverConfig.crawler.parserMemLimitMb;++ if (scriptPath.endsWith(".ts")) {+ // Dev mode: use tsx to run TypeScript directly+ return {+ cmd: "tsx",+ args: [`--max-old-space-size=${maxOldSpaceSize}`, scriptPath],+ };+ }++ return {+ cmd: process.execPath,+ args: [`--max-old-space-size=${maxOldSpaceSize}`, scriptPath],+ };+}++export async function runParseSubprocess(+ htmlContent: string,+ url: string,+ jobId: string,+ abortSignal: AbortSignal,+ opts?: { metadataOnly?: boolean },+): Promise<{+ metadata: ParseSubprocessOutput["metadata"];+ readableContent: { content: string } | null;+}> {+ return await withSpan(+ tracer,+ "crawlerWorker.runParseSubprocess",+ {+ attributes: {+ "bookmark.url": url,+ "bookmark.domain": getBookmarkDomain(url),+ "job.id": jobId,+ },+ },+ async () => {+ logger.info(+ `[Crawler][${jobId}] Spawning parse subprocess for "${truncateUrl(url)}" ...`,+ );++ const { cmd, args } = getSubprocessCommand();+ const timeoutMs = serverConfig.crawler.parseTimeoutSec * 1000;++ const result = await execa({+ input: JSON.stringify({+ htmlContent,+ url,+ jobId,+ metadataOnly: opts?.metadataOnly,+ }),+ cancelSignal: abortSignal,+ timeout: timeoutMs,+ reject: false,+ stderr: "inherit",+ })(cmd, args);++ if (result.isCanceled) {+ throw new Error(+ `[Crawler][${jobId}] Parse subprocess was cancelled (job aborted)`,+ );+ }++ if (result.exitCode !== 0) {+ // Check for OOM: SIGKILL (137) from OS killer, SIGABRT from V8,+ // or V8's "heap out of memory" fatal error message in stderr+ const isOom =+ result.exitCode === 137 ||+ result.signal === "SIGKILL" ||+ result.signal === "SIGABRT";+ const reason = isOom+ ? `OOM killed (exit code ${result.exitCode}). Consider increasing CRAWLER_PARSER_MEM_LIMIT_MB (currently ${serverConfig.crawler.parserMemLimitMb}MB).`+ : `exited with code ${result.exitCode}${result.signal ? ` (signal: ${result.signal})` : ""}`;++ // Try to parse structured error from stdout+ if (result.stdout) {+ let errorOutput: ParseSubprocessError | null = null;+ try {+ errorOutput = parseSubprocessErrorSchema.parse(+ JSON.parse(result.stdout),+ );+ } catch {+ // stdout wasn't valid JSON error, fall through+ }++ if (errorOutput?.error) {+ throw new Error(+ `[Crawler][${jobId}] Parse subprocess ${reason}: ${errorOutput.error}`,+ );+ }+ }++ throw new Error(`[Crawler][${jobId}] Parse subprocess ${reason}`);+ }++ if (!result.stdout) {+ throw new Error(+ `[Crawler][${jobId}] Parse subprocess produced no output`,+ );+ }++ const output = parseSubprocessOutputSchema.parse(+ JSON.parse(result.stdout),+ );+ logger.info(+ `[Crawler][${jobId}] Parse subprocess completed successfully.`,+ );++ return {+ metadata: output.metadata,+ readableContent: output.readableContent,+ };+ },+ );+}diff --git a/apps/workers/workers/crawler/probe.ts b/apps/workers/workers/crawler/probe.tsnew file mode 100644index 00000000..8d43468d--- /dev/null+++ b/apps/workers/workers/crawler/probe.ts@@ -0,0 +1,315 @@+// The pre-crawl probe: a plain GET that determines the URL's content type+// (deciding asset-bookmark vs webpage routing) and, for HTML pages,+// opportunistically extracts preview metadata in the background so the+// bookmark gets a title/thumbnail before the slow browser render finishes.+import { eq, sql } from "drizzle-orm";+import { fetchWithProxy, getBookmarkDomain } from "network";+import type { RunProxyConfig } from "network";+import { raceWith, timeoutRejectRace } from "utils";++import { db } from "@karakeep/db";+import { bookmarkLinks } from "@karakeep/db/schema";+import {+ addLogFields,+ getTracer,+ setSpanAttributes,+ withSpan,+} from "@karakeep/shared-server";+import { ASSET_TYPES } from "@karakeep/shared/assetdb";+import serverConfig from "@karakeep/shared/config";+import logger from "@karakeep/shared/logger";+import { tryCatch } from "@karakeep/shared/tryCatch";++import type { ParseSubprocessOutput } from "../utils/parseHtmlSubprocessIpc";+import { isLikelyChallengePage } from "../utils/metadataResolver";+import { runParseSubprocess } from "./parseSubprocess";+import {+ normalizeContentType,+ shouldRetryCrawlStatusCode,+ truncateUrl,+} from "./utils";++const tracer = getTracer("@karakeep/workers");++// Cap how much of the probed page we buffer for metadata extraction.+// Preview metadata lives in <head>, so a couple of MB is plenty.+const PROBE_MAX_BODY_BYTES = 2 * 1024 * 1024;+// The content-type routing decision needs only the response headers, so it+// keeps the tight timeout the probe always had. The body download (for+// metadata extraction) runs alongside the browser crawl, so it gets a more+// generous overall budget.+const PROBE_HEADERS_TIMEOUT_MS = 5_000;+const PROBE_TIMEOUT_MS = 30_000;++const PROBE_HTML_CONTENT_TYPES = new Set<string>([+ ASSET_TYPES.TEXT_HTML,+ "application/xhtml+xml",+]);++export interface UrlProbeResult {+ contentType: string | null;+ /**+ * Resolves with the page's preview metadata (or null). The extraction runs+ * in the background so it can overlap with the browser crawl — await it+ * only when the metadata is actually needed. Never rejects.+ */+ metadata: Promise<ParseSubprocessOutput["metadata"] | null>;+}++/**+ * Probes the URL with a plain GET to determine its content type. When the+ * response is an HTML page, the body is also parsed (via the parse subprocess+ * in metadata-only mode) so callers get the page's preview metadata without+ * waiting for the full browser render. The returned promise resolves once the+ * content type is known; the metadata extraction keeps running in the+ * background behind `metadata`. Extraction is best-effort and never affects+ * the returned content type.+ */+export async function getContentTypeAndMetadata(+ url: string,+ jobId: string,+ abortSignal: AbortSignal,+ runProxy: RunProxyConfig,+ opts?: { skipMetadataExtraction?: boolean },+): Promise<UrlProbeResult> {+ return await withSpan(+ tracer,+ "crawlerWorker.getContentTypeAndMetadata",+ {+ attributes: {+ "bookmark.url": url,+ "bookmark.domain": getBookmarkDomain(url),+ "job.id": jobId,+ },+ },+ async () => {+ // The request-level signal uses the long budget (it also governs the+ // body read); the wait for the headers is raced separately against the+ // short timeout so a dead host can't delay the routing decision.+ const probeAbort = new AbortController();+ let response;+ try {+ logger.info(+ `[Crawler][${jobId}] Attempting to determine the content-type for the url ${truncateUrl(url)}`,+ );+ response = await raceWith(+ fetchWithProxy(+ url,+ {+ method: "GET",+ signal: AbortSignal.any([+ AbortSignal.timeout(PROBE_TIMEOUT_MS),+ abortSignal,+ probeAbort.signal,+ ]),+ size: PROBE_MAX_BODY_BYTES,+ headers: serverConfig.crawler.preflightUserAgent+ ? { "User-Agent": serverConfig.crawler.preflightUserAgent }+ : undefined,+ },+ runProxy,+ ),+ timeoutRejectRace(+ PROBE_HEADERS_TIMEOUT_MS,+ `Timed out after ${PROBE_HEADERS_TIMEOUT_MS}ms waiting for the response headers`,+ ),+ );+ } catch (e) {+ // Stop the underlying fetch if it's still in flight (header timeout).+ probeAbort.abort();+ logger.error(+ `[Crawler][${jobId}] Failed to determine the content-type for the url ${truncateUrl(url)}: ${e}`,+ );+ return { contentType: null, metadata: Promise.resolve(null) };+ }+ setSpanAttributes({+ "crawler.getContentType.statusCode": response.status,+ });+ const rawContentType = response.headers.get("content-type");+ const contentType = normalizeContentType(rawContentType);+ setSpanAttributes({+ "crawler.contentType": contentType ?? undefined,+ });+ logger.info(+ `[Crawler][${jobId}] Content-type for the url ${truncateUrl(url)} is "${contentType}"`,+ );++ if (!contentType || !PROBE_HTML_CONTENT_TYPES.has(contentType)) {+ return { contentType, metadata: Promise.resolve(null) };+ }++ // A previous run already extracted and stored this page's metadata; the+ // probe was only needed for the content-type routing decision.+ if (opts?.skipMetadataExtraction) {+ logger.info(+ `[Crawler][${jobId}] Skipping metadata extraction from the content-type probe for the url ${truncateUrl(url)} as it was already fetched by a previous run`,+ );+ addLogFields<"crawlerWorker.run">({+ "crawler.probe.metadata": "reused_stored",+ });+ return { contentType, metadata: Promise.resolve(null) };+ }++ // A blocked/retryable status usually means a challenge or error page+ // whose metadata would be junk — don't extract it.+ if (shouldRetryCrawlStatusCode(response.status)) {+ logger.info(+ `[Crawler][${jobId}] Skipping metadata extraction from the content-type probe for the url ${truncateUrl(url)} due to status code ${response.status}`,+ );+ addLogFields<"crawlerWorker.run">({+ "crawler.probe.metadata": "blocked_status",+ });+ return { contentType, metadata: Promise.resolve(null) };+ }++ // The response is an HTML page: parse its metadata from the body we've+ // already fetched. This is deliberately NOT awaited so it runs alongside+ // the browser crawl. It must never reject (callers may await it late or+ // not at all) and any failure here must not lose the content type, as+ // that would regress the asset-vs-webpage routing decision.+ const metadata = (async () => {+ try {+ const htmlContent = await response.text();+ const { metadata: parsedMetadata } = await runParseSubprocess(+ htmlContent,+ response.url,+ jobId,+ abortSignal,+ { metadataOnly: true },+ );+ if (+ isLikelyChallengePage({ title: parsedMetadata.title, htmlContent })+ ) {+ logger.info(+ `[Crawler][${jobId}] The content-type probe response for the url ${truncateUrl(url)} looks like a bot-challenge page; ignoring its metadata`,+ );+ addLogFields<"crawlerWorker.run">({+ "crawler.probe.metadata": "challenge_page",+ });+ return null;+ }+ logger.info(+ `[Crawler][${jobId}] Extracted page metadata from the content-type probe for the url ${truncateUrl(url)}`,+ );+ addLogFields<"crawlerWorker.run">({+ "crawler.probe.metadata": "extracted",+ });+ return parsedMetadata;+ } catch (e) {+ logger.warn(+ `[Crawler][${jobId}] Failed to extract page metadata from the content-type probe for the url ${truncateUrl(url)}: ${e}`,+ );+ addLogFields<"crawlerWorker.run">({+ "crawler.probe.metadata": "failed",+ });+ return null;+ }+ })();+ return { contentType, metadata };+ },+ );+}++/**+ * Writes the preview metadata extracted by the pre-crawl probe so the bookmark+ * gets a title/thumbnail before the (slow) browser render finishes.+ *+ * The write is strictly fill-only: each field is wrapped in+ * COALESCE(NULLIF(existing, ''), new) so it can only populate fields that are+ * currently empty and never override an existing value. This matters because+ * the probe extraction runs detached from the crawl attempt's lifecycle — if+ * an attempt fails early, this write can fire after a *retry* (possibly on+ * another worker) has already stored its final metadata, and it must not+ * clobber it. The post-render metadata write refines these values within the+ * owning attempt.+ */+export async function writeProbeMetadata(+ bookmarkId: string,+ metadata: ParseSubprocessOutput["metadata"],+ jobId: string,+) {+ // Don't store data URIs as they're not valid URLs and are usually quite large+ const image =+ metadata.image && !metadata.image.startsWith("data:")+ ? metadata.image+ : null;+ if (!metadata.title && !metadata.description && !image && !metadata.logo) {+ return;+ }+ await db+ .update(bookmarkLinks)+ .set({+ ...(metadata.title+ ? {+ title: sql`COALESCE(NULLIF(${bookmarkLinks.title}, ''), ${metadata.title})`,+ }+ : {}),+ ...(metadata.description+ ? {+ description: sql`COALESCE(NULLIF(${bookmarkLinks.description}, ''), ${metadata.description})`,+ }+ : {}),+ ...(image+ ? {+ imageUrl: sql`COALESCE(NULLIF(${bookmarkLinks.imageUrl}, ''), ${image})`,+ }+ : {}),+ ...(metadata.logo+ ? {+ favicon: sql`COALESCE(NULLIF(${bookmarkLinks.favicon}, ''), ${metadata.logo})`,+ }+ : {}),+ // Also record that the probe metadata has been fetched and stored, so+ // crawl retries can skip re-fetching it (see loadStoredProbeMetadata).+ probeMetadataAt: new Date(),+ })+ .where(eq(bookmarkLinks.id, bookmarkId));+ logger.info(+ `[Crawler][${jobId}] Wrote early metadata from the content-type probe.`,+ );+}++/**+ * Reloads previously stored probe metadata from the bookmark row. Used on+ * crawl retries (where `probeMetadataAt` shows a probe already succeeded)+ * instead of re-fetching and re-parsing the page, so the blocked-render merge+ * protection keeps working without the extra fetch. Never rejects.+ */+export async function loadStoredProbeMetadata(+ bookmarkId: string,+ jobId: string,+): Promise<ParseSubprocessOutput["metadata"] | null> {+ const { data: row, error } = await tryCatch(+ db.query.bookmarkLinks.findFirst({+ where: eq(bookmarkLinks.id, bookmarkId),+ columns: {+ title: true,+ description: true,+ imageUrl: true,+ favicon: true,+ author: true,+ publisher: true,+ datePublished: true,+ dateModified: true,+ },+ }),+ );+ if (error || !row) {+ if (error) {+ logger.warn(+ `[Crawler][${jobId}] Failed to load stored probe metadata: ${error}`,+ );+ }+ return null;+ }+ return {+ title: row.title,+ description: row.description,+ image: row.imageUrl,+ logo: row.favicon,+ author: row.author,+ publisher: row.publisher,+ datePublished: row.datePublished?.toISOString() ?? null,+ dateModified: row.dateModified?.toISOString() ?? null,+ };+}diff --git a/apps/workers/workers/crawler/utils.ts b/apps/workers/workers/crawler/utils.tsnew file mode 100644index 00000000..599d99b3--- /dev/null+++ b/apps/workers/workers/crawler/utils.ts@@ -0,0 +1,42 @@+export function truncateUrl(url: string): string {+ return url.length > 100 ? url.slice(0, 100) + "..." : url;+}++/**+ * Redact sensitive query parameters (e.g., tokens) from a URL for safe logging.+ */+export function redactUrlCredentials(url: string): string {+ try {+ const parsed = new URL(url);+ for (const key of parsed.searchParams.keys()) {+ parsed.searchParams.set(key, "REDACTED");+ }+ if (parsed.username) {+ parsed.username = "REDACTED";+ }+ if (parsed.password) {+ parsed.password = "REDACTED";+ }+ return parsed.toString();+ } catch {+ return url;+ }+}++/**+ * Normalize a Content-Type header by stripping parameters (e.g., charset)+ * and lowercasing the media type, so comparisons against supported types work.+ */+export function normalizeContentType(header: string | null): string | null {+ if (!header) {+ return null;+ }+ return header.split(";", 1)[0]!.trim().toLowerCase();+}++export function shouldRetryCrawlStatusCode(statusCode: number | null): boolean {+ if (statusCode === null) {+ return false;+ }+ return statusCode === 403 || statusCode === 429 || statusCode >= 500;+}diff --git a/apps/workers/workers/crawlerWorker.ts b/apps/workers/workers/crawlerWorker.tsindex bbd28b91..0d3f834e 100644--- a/apps/workers/workers/crawlerWorker.ts+++ b/apps/workers/workers/crawlerWorker.ts@@ -1,68 +1,22 @@-import * as dns from "dns";-import { promises as fs } from "fs";-import * as fsSync from "fs";-import * as path from "node:path";-import * as os from "os";-import { Transform } from "stream";-import { pipeline } from "stream/promises";-import { PlaywrightBlocker } from "@ghostery/adblocker-playwright";-import { Mutex } from "async-mutex";-import { dataUriToBuffer } from "data-uri-to-buffer";-import type { MimeBuffer } from "data-uri-to-buffer";-import { and, eq, sql } from "drizzle-orm";-import { execa } from "execa";-import { exitAbortController } from "exit";-import {- bookmarkCrawlLatencyHistogram,- crawlerStatusCodeCounter,- workerStatsCounter,-} from "metrics";-import {- fetchWithProxy,- getBookmarkDomain,- matchesNoProxy,- selectRunProxies,- validateUrl,-} from "network";-import type { RunProxyConfig } from "network";-import {- Browser,- BrowserContext,- BrowserContextOptions,- CDPSession,- Page,-} from "playwright";-import { chromium } from "playwright-extra";-import StealthPlugin from "puppeteer-extra-plugin-stealth";-import {- abortRace,- abortRaceResolve,- raceWith,- timeoutRace,- timeoutRejectRace,-} from "utils";+// The crawler worker's queue wiring and per-job orchestration. The heavy+// lifting lives in ./crawler/: browser lifecycle (browser.ts), the browser+// fetch itself (crawlPage.ts), the pre-crawl probe (probe.ts), HTML parsing+// (parseSubprocess.ts), asset persistence (assetStorage.ts), and the+// per-bookmark crawl flow (crawlAndParse.ts).+import { and, eq } from "drizzle-orm";+import { bookmarkCrawlLatencyHistogram, workerStatsCounter } from "metrics";+import { getBookmarkDomain, selectRunProxies } from "network";import { withWorkerTracing, withWorkerEventLog } from "workerTracing";-import { getBookmarkDetails, updateAsset } from "workerUtils";-import { z } from "zod";+import { getBookmarkDetails } from "workerUtils";import type { ZCrawlLinkRequest } from "@karakeep/shared-server";import { db } from "@karakeep/db";-import {- assets,- AssetTypes,- bookmarkAssets,- bookmarkLinks,- bookmarks,- users,-} from "@karakeep/db/schema";+import { bookmarkLinks, bookmarks } from "@karakeep/db/schema";import {addLogFields,- AssetPreprocessingQueue,- getTracer,EmbeddingsQueue,+ getTracer,OpenAIQueue,- QuotaService,- setSpanAttributes,triggerSearchReindex,VideoWorkerQueue,withSpan,@@ -70,18 +24,11 @@ import {} from "@karakeep/shared-server";import {ASSET_TYPES,- getAssetSize,IMAGE_ASSET_TYPES,- newAssetId,- readAsset,- saveAsset,- saveAssetFromFile,- silentDeleteAsset,SUPPORTED_UPLOAD_ASSET_TYPES,} from "@karakeep/shared/assetdb";import serverConfig from "@karakeep/shared/config";import logger from "@karakeep/shared/logger";-import { setUrlHostnameFromResolvedAddress } from "@karakeep/shared/utils/url";import {DequeuedJob,DequeuedJobError,@@ -92,289 +39,39 @@ import {} from "@karakeep/shared/queueing";import { getRateLimitClient } from "@karakeep/shared/ratelimiting";import { tryCatch } from "@karakeep/shared/tryCatch";-import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";import { WebhooksService } from "@karakeep/trpc/models/webhooks.service";-import type {- ParseSubprocessError,- ParseSubprocessOutput,-} from "./utils/parseHtmlSubprocessIpc";import {- parseSubprocessErrorSchema,- parseSubprocessOutputSchema,-} from "./utils/parseHtmlSubprocessIpc";+ getGlobalBrowser,+ initializeBrowserEnvironment,+} from "./crawler/browser";import {- isLikelyChallengePage,- resolveMetadata,-} from "./utils/metadataResolver";--const tracer = getTracer("@karakeep/workers");--function truncateUrl(url: string): string {- return url.length > 100 ? url.slice(0, 100) + "..." : url;-}--/**- * Redact sensitive query parameters (e.g., tokens) from a URL for safe logging.- */-function redactUrlCredentials(url: string): string {- try {- const parsed = new URL(url);- for (const key of parsed.searchParams.keys()) {- parsed.searchParams.set(key, "REDACTED");- }- if (parsed.username) {- parsed.username = "REDACTED";- }- if (parsed.password) {- parsed.password = "REDACTED";- }- return parsed.toString();- } catch {- return url;- }-}--/**- * Normalize a Content-Type header by stripping parameters (e.g., charset)- * and lowercasing the media type, so comparisons against supported types work.- */-function normalizeContentType(header: string | null): string | null {- if (!header) {- return null;- }- return header.split(";", 1)[0]!.trim().toLowerCase();-}--function shouldRetryCrawlStatusCode(statusCode: number | null): boolean {- if (statusCode === null) {- return false;- }- return statusCode === 403 || statusCode === 429 || statusCode >= 500;-}--interface Cookie {- name: string;- value: string;- domain?: string;- path?: string;- expires?: number;- httpOnly?: boolean;- secure?: boolean;- sameSite?: "Strict" | "Lax" | "None";-}+ crawlAndParseUrl,+ handleAsAssetBookmark,+} from "./crawler/crawlAndParse";+import {+ getContentTypeAndMetadata,+ loadStoredProbeMetadata,+ writeProbeMetadata,+} from "./crawler/probe";+import type { UrlProbeResult } from "./crawler/probe";+import { redactUrlCredentials, truncateUrl } from "./crawler/utils";-const cookieSchema = z.object({- name: z.string(),- value: z.string(),- domain: z.string().optional(),- path: z.string().optional(),- expires: z.number().optional(),- httpOnly: z.boolean().optional(),- secure: z.boolean().optional(),- sameSite: z.enum(["Strict", "Lax", "None"]).optional(),-});+// Re-exported for the adhoc crawl CLI (scripts/crawlAdhoc.ts).+export { crawlPage } from "./crawler/crawlPage";-const cookiesSchema = z.array(cookieSchema);+const tracer = getTracer("@karakeep/workers");interface CrawlerRunResult {status: "completed";}-function getPlaywrightProxyConfig(- runProxy: RunProxyConfig,-): BrowserContextOptions["proxy"] {- const proxyUrl = runProxy.httpsProxy || runProxy.httpProxy;- if (!proxyUrl) {- return undefined;- }-- const parsed = new URL(proxyUrl);-- return {- server: proxyUrl,- username: parsed.username,- password: parsed.password,- bypass: runProxy.noProxy?.join(","),- };-}--let globalBrowser: Browser | undefined;-let globalBlocker: PlaywrightBlocker | undefined;-// Global variable to store parsed cookies-let globalCookies: Cookie[] = [];-// Guards the interactions with the browser instance.-// This is needed given that most of the browser APIs are async.-const browserMutex = new Mutex();--// Tracks active browser contexts so we can reap leaked ones.-const activeContexts = new Map<- string,- { context: BrowserContext; createdAt: number }->();--const CONTEXT_CLOSE_TIMEOUT_MS = 10_000;-const PAGE_CLOSE_TIMEOUT_MS = 5_000;--function getHeaderValue(- headers: { name: string; value: string }[] | undefined,- name: string,-): string | undefined {- return headers?.find((header) => header.name.toLowerCase() === name)?.value;-}--/**- * Reaps browser contexts that have been open longer than the max job timeout.- * This is a safety net for cases where context.close() hangs or is never called.- */-function startContextReaper() {- const maxContextAgeMs =- (serverConfig.crawler.jobTimeoutSec + 30) * 1000 +- 60_000 * 5; /* 5 minutes buffer */- const intervalId = setInterval(() => {- try {- const now = Date.now();- for (const [id, entry] of activeContexts) {- if (now - entry.createdAt > maxContextAgeMs) {- logger.warn(- `[Crawler] Reaping stale browser context for job ${id} (age: ${Math.round((now - entry.createdAt) / 1000)}s)`,- );- void raceWith<boolean>(- entry.context- .close()- .then(() => true)- .catch((e: unknown) => {- logger.warn(- `[Crawler] Failed to close stale context for job ${id}: ${e}`,- );- return true;- }),- timeoutRace<boolean>(CONTEXT_CLOSE_TIMEOUT_MS, () => false),- ).then((contextClosed) => {- // Protect against deleting a newer context if the job id gets reused.- if (!contextClosed) {- logger.warn(- `[Crawler] Timed out closing stale context for job ${id} — keeping in active set for retry`,- );- return;- }- if (activeContexts.get(id) === entry) {- activeContexts.delete(id);- }- });- }- }- } catch (e) {- logger.error(- `[Crawler] caught an unexpected error while reaping stale browser contexts: ${e}`,- );- }- }, 60_000 * 5);- exitAbortController.signal.addEventListener(- "abort",- () => clearInterval(intervalId),- {- once: true,- },- );-}--async function startBrowserInstance() {- if (serverConfig.crawler.browserWebSocketUrl) {- logger.info(- `[Crawler] Connecting to existing browser websocket address: ${redactUrlCredentials(serverConfig.crawler.browserWebSocketUrl)}`,- );- return await chromium.connect(serverConfig.crawler.browserWebSocketUrl, {- timeout: 5000,- });- } else if (serverConfig.crawler.browserWebUrl) {- logger.info(- `[Crawler] Connecting to existing browser instance: ${redactUrlCredentials(serverConfig.crawler.browserWebUrl)}`,- );-- const webUrl = new URL(serverConfig.crawler.browserWebUrl);- const { address } = await dns.promises.lookup(webUrl.hostname);- setUrlHostnameFromResolvedAddress(webUrl, address);- logger.info(- `[Crawler] Successfully resolved IP address, new address: ${redactUrlCredentials(webUrl.toString())}`,- );-- return await chromium.connectOverCDP(webUrl.toString(), {- timeout: 5000,- });- } else {- logger.info(`Running in browserless mode`);- return undefined;- }-}--async function launchBrowser() {- globalBrowser = undefined;- await browserMutex.runExclusive(async () => {- const globalBrowserResult = await tryCatch(startBrowserInstance());- if (globalBrowserResult.error) {- logger.error(- `[Crawler] Failed to connect to the browser instance, will retry in 5 secs: ${globalBrowserResult.error.stack}`,- );- if (exitAbortController.signal.aborted) {- logger.info("[Crawler] We're shutting down so won't retry.");- return;- }- setTimeout(() => {- launchBrowser();- }, 5000);- return;- }- globalBrowser = globalBrowserResult.data;- globalBrowser?.on("disconnected", () => {- if (exitAbortController.signal.aborted) {- logger.info(- "[Crawler] The Playwright browser got disconnected. But we're shutting down so won't restart it.",- );- return;- }- logger.info(- "[Crawler] The Playwright browser got disconnected. Will attempt to launch it again.",- );- launchBrowser();- });- });-}-export class CrawlerWorker {private static initPromise: Promise<void> | null = null;private static ensureInitialized() {if (!CrawlerWorker.initPromise) {- CrawlerWorker.initPromise = (async () => {- chromium.use(StealthPlugin());- if (serverConfig.crawler.enableAdblocker) {- logger.info("[crawler] Loading adblocker ...");- const globalBlockerResult = await tryCatch(- PlaywrightBlocker.fromPrebuiltFull(fetchWithProxy, {- path: path.join(os.tmpdir(), "karakeep_adblocker.bin"),- read: fs.readFile,- write: fs.writeFile,- }),- );- if (globalBlockerResult.error) {- logger.error(- `[crawler] Failed to load adblocker. Will not be blocking ads: ${globalBlockerResult.error}`,- );- } else {- globalBlocker = globalBlockerResult.data;- }- }- if (!serverConfig.crawler.browserConnectOnDemand) {- await launchBrowser();- } else {- logger.info(- "[Crawler] Browser connect on demand is enabled, won't proactively start the browser instance",- );- }- await loadCookiesFromFile();- startContextReaper();- })();+ CrawlerWorker.initPromise = initializeBrowserEnvironment();}return CrawlerWorker.initPromise;}@@ -402,7 +99,7 @@ export class CrawlerWorker {"or BROWSER_WEBSOCKET_URL to a reachable Chrome.",);}- if (!serverConfig.crawler.browserConnectOnDemand && !globalBrowser) {+ if (!serverConfig.crawler.browserConnectOnDemand && !getGlobalBrowser()) {throw new Error("[adhoc] Browser failed to connect — refusing to run. crawlPage() would " +"silently fall back to a plain HTTP fetch. Check that BROWSER_WEB_URL / " +@@ -507,40 +204,14 @@ export class CrawlerWorker {}}-async function loadCookiesFromFile(): Promise<void> {- try {- const path = serverConfig.crawler.browserCookiePath;- if (!path) {- logger.info(- "[Crawler] Not defined in the server configuration BROWSER_COOKIE_PATH",- );- return;- }- const data = await fs.readFile(path, "utf8");- const cookies = JSON.parse(data);- globalCookies = cookiesSchema.parse(cookies);- } catch (error) {- logger.error("Failed to read or parse cookies file:", error);- if (error instanceof z.ZodError) {- logger.error("[Crawler] Invalid cookie file format:", error.issues);- } else {- logger.error("[Crawler] Failed to read or parse cookies file:", error);- }- throw error;- }-}--type DBAssetType = typeof assets.$inferInsert;--async function browserlessCrawlPage(- jobId: string,- url: string,- abortSignal: AbortSignal,- runProxy: RunProxyConfig,-) {+/**+ * Checks if the domain should be rate limited and throws QueueRetryAfterError if needed.+ * @throws {QueueRetryAfterError} if the domain is rate limited+ */+async function checkDomainRateLimit(url: string, jobId: string): Promise<void> {return await withSpan(tracer,- "crawlerWorker.browserlessCrawlPage",+ "crawlerWorker.checkDomainRateLimit",{attributes: {"bookmark.url": url,@@ -549,2117 +220,183 @@ async function browserlessCrawlPage(},},async () => {- logger.info(- `[Crawler][${jobId}] Running in browserless mode. Will do a plain http request to "${truncateUrl(url)}". Screenshots will be disabled.`,- );- const response = await fetchWithProxy(- url,+ const crawlerDomainRateLimitConfig =+ serverConfig.crawler.domainRatelimiting;+ if (!crawlerDomainRateLimitConfig) {+ return;+ }++ const rateLimitClient = await getRateLimitClient();+ if (!rateLimitClient) {+ return;+ }++ const hostname = new URL(url).hostname;+ const rateLimitResult = await rateLimitClient.checkRateLimit({- signal: AbortSignal.any([AbortSignal.timeout(5000), abortSignal]),+ name: "domain-ratelimit",+ maxRequests: crawlerDomainRateLimitConfig.maxRequests,+ windowMs: crawlerDomainRateLimitConfig.windowMs,},- runProxy,- );- logger.info(- `[Crawler][${jobId}] Successfully fetched the content of "${truncateUrl(url)}". Status: ${response.status}, Size: ${response.size}`,+ hostname,);- return {- htmlContent: await response.text(),- statusCode: response.status,- screenshot: undefined,- pdf: undefined,- url: response.url,- };++ if (!rateLimitResult.allowed) {+ const resetInSeconds = rateLimitResult.resetInSeconds;+ // Add jitter to prevent thundering herd: +40% random variation+ const jitterFactor = 1.0 + Math.random() * 0.4; // Random value between 1.0 and 1.4+ const delayMs = Math.floor(resetInSeconds * 1000 * jitterFactor);+ logger.info(+ `[Crawler][${jobId}] Domain "${hostname}" is rate limited. Will retry in ${(delayMs / 1000).toFixed(2)} seconds (with jitter).`,+ );+ throw new QueueRetryAfterError(+ `Domain "${hostname}" is rate limited`,+ delayMs,+ );+ }},);}-export async function crawlPage(- jobId: string,- url: string,+/**+ * Enqueues the follow-up work after a successful webpage crawl: inference+ * (tagging/summarization/embeddings), search reindexing, video download, and+ * the "crawled" webhook.+ */+async function enqueuePostCrawlJobs(+ job: DequeuedJob<ZCrawlLinkRequest>,+ bookmarkId: string,userId: string,- forceStorePdf: boolean,- abortSignal: AbortSignal,- runProxy: RunProxyConfig,- // When set, skips the per-user browserCrawlingEnabled DB lookup and uses this- // value instead. Used by the adhoc crawl CLI, which has no user row.- browserCrawlingEnabledOverride?: boolean,-): Promise<{- htmlContent: string;- screenshot: Buffer | undefined;- pdf: Buffer | undefined;- statusCode: number;- url: string;-}> {- return await withSpan(- tracer,- "crawlerWorker.crawlPage",- {- attributes: {- "bookmark.url": url,- "bookmark.domain": getBookmarkDomain(url),- "job.id": jobId,- "user.id": userId,- "crawler.forceStorePdf": forceStorePdf,- },- },- async () => {- let browserCrawlingEnabled: boolean | null;- if (browserCrawlingEnabledOverride !== undefined) {- browserCrawlingEnabled = browserCrawlingEnabledOverride;- } else {- const userData = await db.query.users.findFirst({- where: eq(users.id, userId),- columns: { browserCrawlingEnabled: true },- });- if (!userData) {- logger.error(`[Crawler][${jobId}] User ${userId} not found`);- throw new Error(`User ${userId} not found`);- }- browserCrawlingEnabled = userData.browserCrawlingEnabled;- }-- if (browserCrawlingEnabled !== null && !browserCrawlingEnabled) {- return browserlessCrawlPage(jobId, url, abortSignal, runProxy);- }+ url: string,+): Promise<void> {+ // Propagate priority to child jobs+ const enqueueOpts: EnqueueOptions = {+ priority: job.priority,+ groupId: userId,+ };- let browser: Browser | undefined;- browser = await withSpan(- tracer,- "crawlerWorker.crawlPage.getBrowserInstance",+ // Enqueue openai job (if not set, assume it's true for backward compatibility)+ if (job.data.runInference !== false) {+ if (serverConfig.embedding.enableAutoIndexing) {+ await EmbeddingsQueue.enqueue({- attributes: {- "job.id": jobId,- },- },- async () => {- if (serverConfig.crawler.browserConnectOnDemand) {- return startBrowserInstance();- }- return globalBrowser;+ bookmarkId,+ type: "embed",+ runTaggingOnComplete: true,},+ enqueueOpts,);- if (!browser) {- return browserlessCrawlPage(jobId, url, abortSignal, runProxy);- }-- const proxyConfig = getPlaywrightProxyConfig(runProxy);- const isRunningInProxyContext =- proxyConfig !== undefined &&- !matchesNoProxy(url, proxyConfig.bypass?.split(",") ?? []);- const context = await withSpan(- tracer,- "crawlerWorker.crawlPage.createContext",+ } else {+ await OpenAIQueue.enqueue({- attributes: {- "job.id": jobId,- },+ bookmarkId,+ type: "tag",},- async () =>- browser.newContext({- viewport: { width: 1440, height: 900 },- userAgent:- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",- proxy: proxyConfig,- serviceWorkers: "block",- }),+ enqueueOpts,);+ }+ await OpenAIQueue.enqueue(+ {+ bookmarkId,+ type: "summarize",+ },+ enqueueOpts,+ );+ }- activeContexts.set(jobId, { context, createdAt: Date.now() });- let page: Page | undefined;- try {- if (globalCookies.length > 0) {- await context.addCookies(globalCookies);- logger.info(- `[Crawler][${jobId}] Cookies successfully loaded into browser context`,- );- }-- page = await withSpan(- tracer,- "crawlerWorker.crawlPage.setupPage",- {- attributes: {- "job.id": jobId,- },- },- async () => {- // Create a new page in the context- const nextPage = await context.newPage();- let cdpSession: CDPSession | undefined;+ // Update the search index+ await triggerSearchReindex(bookmarkId, enqueueOpts);- try {- cdpSession = await context.newCDPSession(nextPage);- const continuePausedRequest = async (requestId: string) => {- await cdpSession- ?.send("Fetch.continueRequest", { requestId })- .catch(() => {- // Ignore errors — the request may have been canceled.- });- };- const failPausedRequest = async (requestId: string) => {- await cdpSession- ?.send("Fetch.failRequest", {- requestId,- errorReason: "BlockedByClient",- })- .catch(() => {- // Ignore errors — the request may have been canceled.- });- };- cdpSession.on("Fetch.authRequired", async (event) => {- const authChallengeResponse =- event.authChallenge.source === "Proxy" &&- (proxyConfig?.username || proxyConfig?.password)- ? {- response: "ProvideCredentials" as const,- username: proxyConfig.username ?? "",- password: proxyConfig.password ?? "",- }- : { response: "Default" as const };- await cdpSession- ?.send("Fetch.continueWithAuth", {- requestId: event.requestId,- authChallengeResponse,- })- .catch(() => {- // Ignore errors — the request may have been canceled.- });- });- cdpSession.on("Fetch.requestPaused", async (event) => {- try {- const status = event.responseStatusCode;- if (!status || status < 300 || status >= 400) {- await continuePausedRequest(event.requestId);- return;- }+ if (serverConfig.crawler.downloadVideo) {+ // Trigger a potential download of a video from the URL+ await VideoWorkerQueue.enqueue(+ {+ bookmarkId,+ url,+ },+ enqueueOpts,+ );+ }- const location = getHeaderValue(- event.responseHeaders,- "location",- );- if (!location) {- await continuePausedRequest(event.requestId);- return;- }+ // Trigger a webhook+ {+ const webhookService = new WebhooksService(db);+ await webhookService.triggerWebhook(+ bookmarkId,+ "crawled",+ userId,+ enqueueOpts,+ );+ }+}- const redirectUrl = new URL(- location,- event.request.url,- ).toString();- const redirectIsRunningInProxyContext =- proxyConfig !== undefined &&- !matchesNoProxy(- redirectUrl,- proxyConfig.bypass?.split(",") ?? [],- );- const validation = await validateUrl(- redirectUrl,- redirectIsRunningInProxyContext,- );+async function runCrawler(+ job: DequeuedJob<ZCrawlLinkRequest>,+ maxRetries: number,+): Promise<CrawlerRunResult> {+ const jobId = `${job.id}:${job.runNumber}`;+ const numRetriesLeft = Math.max(maxRetries - job.runNumber, 0);- if (validation.ok) {- await continuePausedRequest(event.requestId);- return;- }+ const request = zCrawlLinkRequestSchema.safeParse(job.data);+ if (!request.success) {+ logger.error(+ `[Crawler][${jobId}] Got malformed job request: ${request.error.toString()}`,+ );+ return { status: "completed" };+ }- logger.warn(- `[Crawler][${jobId}] Blocking redirect to disallowed URL "${redirectUrl}": ${validation.reason}`,- );- await failPausedRequest(event.requestId);- } catch (e) {- logger.warn(- `[Crawler][${jobId}] Blocking redirect after redirect guard failed: ${e}`,- );- await failPausedRequest(event.requestId);- }- });- await cdpSession.send("Fetch.enable", {- handleAuthRequests: true,- patterns: [- { urlPattern: "*", requestStage: "Request" },- { urlPattern: "*", requestStage: "Response" },- ],- });- } catch (e) {- logger.warn(- `[Crawler][${jobId}] Failed to install redirect guard: ${e}`,- );- }+ const { bookmarkId, archiveFullPage, storePdf } = request.data;+ const {+ url,+ userId,+ createdAt,+ crawledAt,+ screenshotAssetId: oldScreenshotAssetId,+ pdfAssetId: oldPdfAssetId,+ imageAssetId: oldImageAssetId,+ fullPageArchiveAssetId: oldFullPageArchiveAssetId,+ contentAssetId: oldContentAssetId,+ precrawledArchiveAssetId,+ probeMetadataAt,+ } = await getBookmarkDetails(bookmarkId);- // Apply ad blocking- if (globalBlocker) {- await globalBlocker.enableBlockingInPage(nextPage);- }+ await checkDomainRateLimit(url, jobId);- // Auto-dismiss JavaScript dialogs (alert, confirm, prompt)- // to prevent pages from hanging during crawl.- nextPage.on("dialog", (dialog) => {- dialog.dismiss().catch(() => {- // Ignore errors — the dialog may have already been closed.- });- });+ // Select proxy URLs once for the entire run so all requests use the same proxy.+ const runProxy = selectRunProxies();- // Block audio/video resources and disallowed sub-requests- await nextPage.route("**/*", async (route) => {- if (abortSignal.aborted) {- await route.abort("aborted");- return;- }- const request = route.request();- const resourceType = request.resourceType();+ addLogFields<"crawlerWorker.run">({+ "crawler.url": url,+ "crawler.domain": getBookmarkDomain(url),+ "crawler.proxy": redactUrlCredentials(+ runProxy.httpsProxy ?? runProxy.httpProxy ?? "",+ ),+ });- // Block audio/video resources- if (- resourceType === "media" ||- request.headers()["content-type"]?.includes("video/") ||- request.headers()["content-type"]?.includes("audio/")- ) {- await route.abort("aborted");- return;- }+ logger.info(+ `[Crawler][${jobId}] Will crawl "${truncateUrl(url)}" for link with id "${bookmarkId}"`,+ );- const requestUrl = request.url();- const requestIsRunningInProxyContext =- proxyConfig !== undefined &&- !matchesNoProxy(- requestUrl,- proxyConfig.bypass?.split(",") ?? [],- );- if (- requestUrl.startsWith("http://") ||- requestUrl.startsWith("https://")- ) {- const validation = await validateUrl(- requestUrl,- requestIsRunningInProxyContext,- );- if (!validation.ok) {- logger.warn(- `[Crawler][${jobId}] Blocking sub-request to disallowed URL "${requestUrl}": ${validation.reason}`,- );- await route.abort("blockedbyclient");- return;- }- }+ if (precrawledArchiveAssetId) {+ logger.info(+ `[Crawler][${jobId}] Skipped fetching content-type for the url ${url} as precrawledArchiveAssetId exists`,+ );+ }+ // Retry runs re-probe for the content type, but if a previous run already+ // extracted and stored the probe metadata (probeMetadataAt), don't re-fetch+ // it — reload it from the bookmark row instead.+ const reuseStoredProbeMetadata =+ job.runNumber > 0 && probeMetadataAt !== null;+ const { contentType, metadata: probeMetadata }: UrlProbeResult =+ precrawledArchiveAssetId+ ? { contentType: ASSET_TYPES.TEXT_HTML, metadata: Promise.resolve(null) }+ : await getContentTypeAndMetadata(url, jobId, job.abortSignal, runProxy, {+ skipMetadataExtraction: reuseStoredProbeMetadata,+ });+ job.abortSignal.throwIfAborted();- // Continue with other requests- await route.fallback();- });-- // On abort, immediately stop intercepting requests so that- // in-flight route handlers don't block page/context closure.- abortSignal.addEventListener(- "abort",- () => {- cdpSession?.detach().catch(() => {- // Ignore errors — the session may already be detached.- });- nextPage.unrouteAll({ behavior: "ignoreErrors" }).catch(() => {- // Ignore errors — the page may already be closed.- });- },- { once: true },- );-- return nextPage;- },- );-- // page is guaranteed to be assigned here; alias to a const for- // TypeScript narrowing so the rest of the try block sees `Page`.- const activePage = page;-- // Navigate to the target URL- const navigationValidation = await withSpan(- tracer,- "crawlerWorker.crawlPage.validateNavigationTarget",- {- attributes: {- "job.id": jobId,- "bookmark.url": url,- "bookmark.domain": getBookmarkDomain(url),- },- },- async () => validateUrl(url, isRunningInProxyContext),- );- if (!navigationValidation.ok) {- throw new Error(- `Disallowed navigation target "${truncateUrl(url)}": ${navigationValidation.reason}`,- );- }- const targetUrl = navigationValidation.url.toString();- logger.info(`[Crawler][${jobId}] Navigating to "${targetUrl}"`);- const response = await withSpan(- tracer,- "crawlerWorker.crawlPage.navigate",- {- attributes: {- "job.id": jobId,- "bookmark.url": targetUrl,- "bookmark.domain": getBookmarkDomain(targetUrl),- },- },- async () =>- raceWith(- activePage.goto(targetUrl, {- timeout: serverConfig.crawler.navigateTimeoutSec * 1000,- waitUntil: "domcontentloaded",- }),- abortRaceResolve(abortSignal, null),- ),- );- setSpanAttributes({- "crawler.statusCode": response?.status() ?? 0,- });-- logger.info(- `[Crawler][${jobId}] Successfully navigated to "${targetUrl}". Waiting for the page to load ...`,- );-- // Wait until network is relatively idle or timeout after 5 seconds- await withSpan(- tracer,- "crawlerWorker.crawlPage.waitForLoadState",- {- attributes: {- "job.id": jobId,- "bookmark.url": targetUrl,- "bookmark.domain": getBookmarkDomain(targetUrl),- },- },- async () => {- await raceWith<unknown>(- activePage- .waitForLoadState("networkidle", { timeout: 5000 })- .catch(() => ({})),- timeoutRace<unknown>(5000, () => undefined),- abortRace(abortSignal),- );- },- );-- abortSignal.throwIfAborted();-- logger.info(- `[Crawler][${jobId}] Finished waiting for the page to load.`,- );-- const [htmlContent, screenshot, pdf] = await withSpan(- tracer,- "crawlerWorker.crawlPage.captureAssets",- {- attributes: {- "job.id": jobId,- },- },- async () => {- const htmlPromise = withSpan(- tracer,- "crawlerWorker.crawlPage.extractHtml",- {- attributes: {- "job.id": jobId,- },- },- async () => {- const content = await activePage.content();- abortSignal.throwIfAborted();- logger.info(- `[Crawler][${jobId}] Successfully fetched the page content.`,- );- return content;- },- );-- const screenshotPromise: Promise<Buffer | undefined> = serverConfig- .crawler.storeScreenshot- ? withSpan(- tracer,- "crawlerWorker.crawlPage.captureScreenshot",- {- attributes: {- "job.id": jobId,- "asset.type": "image",- },- },- async () => {- const { data: screenshotData, error: screenshotError } =- await tryCatch(- raceWith<Buffer>(- activePage.screenshot({- // If you change this, you need to change the asset type in the store function.- type: "jpeg",- fullPage: serverConfig.crawler.fullPageScreenshot,- quality: 80,- }),- timeoutRace<Buffer>(- serverConfig.crawler.screenshotTimeoutSec * 1000,- () => {- throw new Error(- "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",- );- },- ),- abortRaceResolve(abortSignal, Buffer.from("")),- ),- );- abortSignal.throwIfAborted();- if (screenshotError) {- logger.warn(- `[Crawler][${jobId}] Failed to capture the screenshot. Reason: ${screenshotError}`,- );- return undefined;- }- setSpanAttributes({- "asset.size": screenshotData.byteLength,- });- logger.info(- `[Crawler][${jobId}] Finished capturing page content and a screenshot. FullPageScreenshot: ${serverConfig.crawler.fullPageScreenshot}`,- );- return screenshotData;- },- )- : Promise.resolve(undefined);-- const pdfPromise: Promise<Buffer | undefined> =- serverConfig.crawler.storePdf || forceStorePdf- ? withSpan(- tracer,- "crawlerWorker.crawlPage.capturePdf",- {- attributes: {- "job.id": jobId,- "asset.type": "pdf",- },- },- async () => {- const { data: pdfData, error: pdfError } = await tryCatch(- raceWith<Buffer>(- activePage.pdf({- format: "A4",- printBackground: true,- }),- timeoutRace<Buffer>(- serverConfig.crawler.screenshotTimeoutSec * 1000,- () => {- throw new Error(- "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",- );- },- ),- abortRaceResolve(abortSignal, Buffer.from("")),- ),- );- abortSignal.throwIfAborted();- if (pdfError) {- logger.warn(- `[Crawler][${jobId}] Failed to capture the PDF. Reason: ${pdfError}`,- );- return undefined;- }- setSpanAttributes({- "asset.size": pdfData.byteLength,- });- logger.info(- `[Crawler][${jobId}] Finished capturing page content as PDF`,- );- return pdfData;- },- )- : Promise.resolve(undefined);-- const captureResults = await Promise.all([- htmlPromise,- screenshotPromise,- pdfPromise,- ] as const);- abortSignal.throwIfAborted();- return captureResults;- },- );-- return {- htmlContent,- statusCode: response?.status() ?? 0,- screenshot,- pdf,- url: activePage.url(),- };- } finally {- await withSpan(- tracer,- "crawlerWorker.crawlPage.cleanup",- {- attributes: {- "job.id": jobId,- "crawler.cleanup.hasPage": !!page,- },- },- async () => {- // Explicitly close the page first (with timeout) to release resources- // even if context.close() later hangs.- if (page) {- const pageToClose = page;- const pageClosed = await withSpan(- tracer,- "crawlerWorker.crawlPage.cleanup.closePage",- { attributes: { "job.id": jobId } },- async () =>- raceWith<boolean>(- pageToClose- .close()- .then(() => true)- .catch((e: unknown) => {- logger.warn(- `[Crawler][${jobId}] page.close() failed: ${e}`,- );- return true;- }),- timeoutRace<boolean>(PAGE_CLOSE_TIMEOUT_MS, () => false),- ),- );- setSpanAttributes({ "crawler.cleanup.pageClosed": pageClosed });- if (!pageClosed) {- logger.warn(`[Crawler][${jobId}] page.close() timed out`);- }- }-- // Close the context (with timeout) to avoid hanging on in-flight ops.- // Only remove from tracking if close actually succeeded; otherwise- // the reaper will retry the close later.- const contextClosed = await withSpan(- tracer,- "crawlerWorker.crawlPage.cleanup.closeContext",- { attributes: { "job.id": jobId } },- async () =>- raceWith<boolean>(- context- .close()- .then(() => true)- .catch((e: unknown) => {- logger.warn(- `[Crawler][${jobId}] context.close() failed: ${e}`,- );- return true; // Error means it's likely already closed- }),- timeoutRace<boolean>(CONTEXT_CLOSE_TIMEOUT_MS, () => false),- ),- );- setSpanAttributes({- "crawler.cleanup.contextClosed": contextClosed,- });-- if (contextClosed) {- activeContexts.delete(jobId);- } else {- logger.warn(- `[Crawler][${jobId}] context.close() timed out — leaving in active set for reaper`,- );- }-- // Only close the browser if it was created on demand- if (serverConfig.crawler.browserConnectOnDemand) {- await withSpan(- tracer,- "crawlerWorker.crawlPage.cleanup.closeBrowser",- { attributes: { "job.id": jobId } },- async () =>- browser- .close()- .then(() => {- activeContexts.delete(jobId);- })- .catch((e: unknown) => {- logger.warn(- `[Crawler][${jobId}] browser.close() failed: ${e}`,- );- }),- );- }- },- );- }- },- );-}--function getSubprocessScriptPath(): string {- const currentUrl = import.meta.url;- if (currentUrl.includes("/dist/")) {- // Production: running from built output- return new URL("./scripts/parseHtmlSubprocess.js", currentUrl).pathname;- }- // Dev mode: running via tsx- return new URL("../scripts/parseHtmlSubprocess.ts", currentUrl).pathname;-}--function getSubprocessCommand(): { cmd: string; args: string[] } {- const scriptPath = getSubprocessScriptPath();- const maxOldSpaceSize = serverConfig.crawler.parserMemLimitMb;-- if (scriptPath.endsWith(".ts")) {- // Dev mode: use tsx to run TypeScript directly- return {- cmd: "tsx",- args: [`--max-old-space-size=${maxOldSpaceSize}`, scriptPath],- };- }-- return {- cmd: process.execPath,- args: [`--max-old-space-size=${maxOldSpaceSize}`, scriptPath],- };-}--async function runParseSubprocess(- htmlContent: string,- url: string,- jobId: string,- abortSignal: AbortSignal,- opts?: { metadataOnly?: boolean },-): Promise<{- metadata: ParseSubprocessOutput["metadata"];- readableContent: { content: string } | null;-}> {- return await withSpan(- tracer,- "crawlerWorker.runParseSubprocess",- {- attributes: {- "bookmark.url": url,- "bookmark.domain": getBookmarkDomain(url),- "job.id": jobId,- },- },- async () => {- logger.info(- `[Crawler][${jobId}] Spawning parse subprocess for "${truncateUrl(url)}" ...`,- );-- const { cmd, args } = getSubprocessCommand();- const timeoutMs = serverConfig.crawler.parseTimeoutSec * 1000;-- const result = await execa({- input: JSON.stringify({- htmlContent,- url,- jobId,- metadataOnly: opts?.metadataOnly,- }),- cancelSignal: abortSignal,- timeout: timeoutMs,- reject: false,- stderr: "inherit",- })(cmd, args);-- if (result.isCanceled) {- throw new Error(- `[Crawler][${jobId}] Parse subprocess was cancelled (job aborted)`,- );- }-- if (result.exitCode !== 0) {- // Check for OOM: SIGKILL (137) from OS killer, SIGABRT from V8,- // or V8's "heap out of memory" fatal error message in stderr- const isOom =- result.exitCode === 137 ||- result.signal === "SIGKILL" ||- result.signal === "SIGABRT";- const reason = isOom- ? `OOM killed (exit code ${result.exitCode}). Consider increasing CRAWLER_PARSER_MEM_LIMIT_MB (currently ${serverConfig.crawler.parserMemLimitMb}MB).`- : `exited with code ${result.exitCode}${result.signal ? ` (signal: ${result.signal})` : ""}`;-- // Try to parse structured error from stdout- if (result.stdout) {- let errorOutput: ParseSubprocessError | null = null;- try {- errorOutput = parseSubprocessErrorSchema.parse(- JSON.parse(result.stdout),- );- } catch {- // stdout wasn't valid JSON error, fall through- }-- if (errorOutput?.error) {- throw new Error(- `[Crawler][${jobId}] Parse subprocess ${reason}: ${errorOutput.error}`,- );- }- }-- throw new Error(`[Crawler][${jobId}] Parse subprocess ${reason}`);- }-- if (!result.stdout) {- throw new Error(- `[Crawler][${jobId}] Parse subprocess produced no output`,- );- }-- const output = parseSubprocessOutputSchema.parse(- JSON.parse(result.stdout),- );- logger.info(- `[Crawler][${jobId}] Parse subprocess completed successfully.`,- );-- return {- metadata: output.metadata,- readableContent: output.readableContent,- };- },- );-}--async function storeScreenshot(- screenshot: Buffer | undefined,- userId: string,- jobId: string,-) {- return await withSpan(- tracer,- "crawlerWorker.storeScreenshot",- {- attributes: {- "job.id": jobId,- "user.id": userId,- "asset.size": screenshot?.byteLength ?? 0,- },- },- async () => {- if (!serverConfig.crawler.storeScreenshot) {- logger.info(- `[Crawler][${jobId}] Skipping storing the screenshot as per the config.`,- );- return null;- }- if (!screenshot) {- logger.info(- `[Crawler][${jobId}] Skipping storing the screenshot as it's empty.`,- );- return null;- }- const assetId = newAssetId();- const contentType = "image/jpeg";- const fileName = "screenshot.jpeg";-- // Check storage quota before saving the screenshot- const { data: quotaApproved, error: quotaError } = await tryCatch(- QuotaService.checkStorageQuota(db, userId, screenshot.byteLength),- );-- if (quotaError) {- logger.warn(- `[Crawler][${jobId}] Skipping screenshot storage due to quota exceeded: ${quotaError.message}`,- );- return null;- }-- await saveAsset({- userId,- assetId,- metadata: { contentType, fileName },- asset: screenshot,- quotaApproved,- });- logger.info(- `[Crawler][${jobId}] Stored the screenshot as assetId: ${assetId} (${screenshot.byteLength} bytes)`,- );- return { assetId, contentType, fileName, size: screenshot.byteLength };- },- );-}--async function storePdf(- pdf: Buffer | undefined,- userId: string,- jobId: string,-) {- return await withSpan(- tracer,- "crawlerWorker.storePdf",- {- attributes: {- "job.id": jobId,- "user.id": userId,- "asset.size": pdf?.byteLength ?? 0,- },- },- async () => {- if (!pdf) {- logger.info(- `[Crawler][${jobId}] Skipping storing the PDF as it's empty.`,- );- return null;- }- const assetId = newAssetId();- const contentType = "application/pdf";- const fileName = "page.pdf";-- // Check storage quota before saving the PDF- const { data: quotaApproved, error: quotaError } = await tryCatch(- QuotaService.checkStorageQuota(db, userId, pdf.byteLength),- );-- if (quotaError) {- logger.warn(- `[Crawler][${jobId}] Skipping PDF storage due to quota exceeded: ${quotaError.message}`,- );- return null;- }-- await saveAsset({- userId,- assetId,- metadata: { contentType, fileName },- asset: pdf,- quotaApproved,- });- logger.info(- `[Crawler][${jobId}] Stored the PDF as assetId: ${assetId} (${pdf.byteLength} bytes)`,- );- return { assetId, contentType, fileName, size: pdf.byteLength };- },- );-}--/**- * SingleFile / precrawled archives inline images as `data:` URIs, so the image- * URL metascraper extracts can be a base64 blob rather than something fetchable- * over the network. Decode it locally and store it as an asset instead of- * failing on the unsupported protocol.- */-async function storeDataUriAsset(- url: string,- userId: string,- jobId: string,- fileType: string,-) {- const maxBytes = serverConfig.maxAssetSizeMb * 1024 * 1024;-- // Guardrail 1: cap the size *before* decoding into memory. base64 encodes 3- // bytes per 4 chars, so a URI longer than 4/3 the limit (plus header slack)- // must decode past it; the exact check below handles the rest.- if (url.length > Math.ceil((maxBytes * 4) / 3) + 1024) {- logger.warn(- `[Crawler][${jobId}] Skipping data URI ${fileType}: encoded size (${url.length} chars) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,- );- return null;- }-- let asset: MimeBuffer;- try {- asset = dataUriToBuffer(url);- } catch (e) {- logger.error(- `[Crawler][${jobId}] Failed to decode data URI ${fileType}: ${e}`,- );- return null;- }-- // Guardrail 2: never trust the declared mediatype for anything but the raster- // image types we actually serve as banners. Rejects svg/html/etc.;- // saveAsset's SUPPORTED_ASSET_TYPES check is the backstop.- const contentType = normalizeContentType(asset.type);- if (!contentType || !IMAGE_ASSET_TYPES.has(contentType)) {- logger.warn(- `[Crawler][${jobId}] Skipping data URI ${fileType} with unsupported content type: ${contentType}`,- );- return null;- }-- if (asset.byteLength > maxBytes) {- logger.warn(- `[Crawler][${jobId}] Skipping data URI ${fileType}: decoded size (${asset.byteLength} bytes) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,- );- return null;- }-- const { data: quotaApproved, error: quotaError } = await tryCatch(- QuotaService.checkStorageQuota(db, userId, asset.byteLength),- );- if (quotaError) {- logger.warn(- `[Crawler][${jobId}] Skipping data URI ${fileType} storage due to quota exceeded: ${quotaError.message}`,- );- return null;- }-- const assetId = newAssetId();- await saveAsset({- userId,- assetId,- metadata: { contentType },- asset,- quotaApproved,- });- logger.info(- `[Crawler][${jobId}] Stored data URI ${fileType} as assetId: ${assetId} (${asset.byteLength} bytes)`,- );- return { assetId, userId, contentType, size: asset.byteLength };-}--async function downloadAndStoreFile(- url: string,- userId: string,- jobId: string,- fileType: string,- abortSignal: AbortSignal,- runProxy: RunProxyConfig,-) {- return await withSpan(- tracer,- "crawlerWorker.downloadAndStoreFile",- {- attributes: {- "bookmark.url": url,- "bookmark.domain": getBookmarkDomain(url),- "job.id": jobId,- "user.id": userId,- "asset.type": fileType,- },- },- async () => {- let assetPath: string | undefined;- try {- if (url.startsWith("data:")) {- return await storeDataUriAsset(url, userId, jobId, fileType);- }- logger.info(- `[Crawler][${jobId}] Downloading ${fileType} from "${truncateUrl(url)}"`,- );- const response = await fetchWithProxy(- url,- {- signal: abortSignal,- },- runProxy,- );- if (!response.ok || response.body == null) {- throw new Error(`Failed to download ${fileType}: ${response.status}`);- }-- const contentType = normalizeContentType(- response.headers.get("content-type"),- );- if (!contentType) {- throw new Error("No content type in the response");- }-- const assetId = newAssetId();- assetPath = path.join(os.tmpdir(), assetId);-- let bytesRead = 0;- const contentLengthEnforcer = new Transform({- transform(chunk, _, callback) {- bytesRead += chunk.length;-- if (abortSignal.aborted) {- callback(new Error("AbortError"));- } else if (bytesRead > serverConfig.maxAssetSizeMb * 1024 * 1024) {- callback(- new Error(- `Content length exceeds maximum allowed size: ${serverConfig.maxAssetSizeMb}MB`,- ),- );- } else {- callback(null, chunk); // pass data along unchanged- }- },- flush(callback) {- callback();- },- });-- await pipeline(- response.body,- contentLengthEnforcer,- fsSync.createWriteStream(assetPath),- );-- // Check storage quota before saving the asset- const { data: quotaApproved, error: quotaError } = await tryCatch(- QuotaService.checkStorageQuota(db, userId, bytesRead),- );-- if (quotaError) {- logger.warn(- `[Crawler][${jobId}] Skipping ${fileType} storage due to quota exceeded: ${quotaError.message}`,- );- return null;- }-- await saveAssetFromFile({- userId,- assetId,- metadata: { contentType },- assetPath,- quotaApproved,- });-- logger.info(- `[Crawler][${jobId}] Downloaded ${fileType} as assetId: ${assetId} (${bytesRead} bytes)`,- );-- return { assetId, userId, contentType, size: bytesRead };- } catch (e) {- logger.error(- `[Crawler][${jobId}] Failed to download and store ${fileType}: ${e}`,- );- return null;- } finally {- if (assetPath) {- await tryCatch(fs.unlink(assetPath));- }- }- },- );-}--async function downloadAndStoreImage(- url: string,- userId: string,- jobId: string,- abortSignal: AbortSignal,- runProxy: RunProxyConfig,-) {- if (!serverConfig.crawler.downloadBannerImage) {- logger.info(- `[Crawler][${jobId}] Skipping downloading the image as per the config.`,- );- return null;- }- return downloadAndStoreFile(- url,- userId,- jobId,- "image",- abortSignal,- runProxy,- );-}--async function archiveWebpage(- html: string,- url: string,- userId: string,- jobId: string,- abortSignal: AbortSignal,- runProxy: RunProxyConfig,-) {- return await withSpan(- tracer,- "crawlerWorker.archiveWebpage",- {- attributes: {- "bookmark.url": url,- "bookmark.domain": getBookmarkDomain(url),- "job.id": jobId,- "user.id": userId,- },- },- async () => {- logger.info(`[Crawler][${jobId}] Will attempt to archive page ...`);-- {- // Archival is a heavy operation, so we need to check if the user is within reasonable quota before proceeding- const { error: quotaError } = await tryCatch(- QuotaService.checkStorageQuota(db, userId, /* estimated size */ 1024),- );- if (quotaError) {- logger.warn(- `[Crawler][${jobId}] Skipping archival as the user has exceeded their quota: ${quotaError.message}`,- );- return null;- }- }-- const assetId = newAssetId();- const assetPath = path.join(os.tmpdir(), assetId);-- let res = await execa({- input: html,- cancelSignal: abortSignal,- env: {- https_proxy: runProxy.httpsProxy,- http_proxy: runProxy.httpProxy,- no_proxy: runProxy.noProxy?.join(","),- },- })("monolith", [- "-",- "-Ije",- "-t",- String(serverConfig.crawler.monolithTimeoutSec),- ...serverConfig.crawler.monolithArguments,- "-b",- url,- "-o",- assetPath,- ]);-- if (res.isCanceled) {- logger.error(- `[Crawler][${jobId}] Canceled archiving the page as we hit global timeout.`,- );- await tryCatch(fs.unlink(assetPath));- return null;- }-- if (res.exitCode !== 0) {- logger.error(- `[Crawler][${jobId}] Failed to archive the page as the command exited with code ${res.exitCode}`,- );- await tryCatch(fs.unlink(assetPath));- return null;- }-- const contentType = "text/html";-- // Get file size and check quota before saving- const stats = await fs.stat(assetPath);- const fileSize = stats.size;-- const { data: quotaApproved, error: quotaError } = await tryCatch(- QuotaService.checkStorageQuota(db, userId, fileSize),- );-- if (quotaError) {- logger.warn(- `[Crawler][${jobId}] Skipping page archive storage due to quota exceeded: ${quotaError.message}`,- );- await tryCatch(fs.unlink(assetPath));- return null;- }-- await saveAssetFromFile({- userId,- assetId,- assetPath,- metadata: {- contentType,- },- quotaApproved,- });-- logger.info(- `[Crawler][${jobId}] Done archiving the page as assetId: ${assetId}`,- );-- return {- assetId,- contentType,- size: await getAssetSize({ userId, assetId }),- };- },- );-}--// Cap how much of the probed page we buffer for metadata extraction.-// Preview metadata lives in <head>, so a couple of MB is plenty.-const PROBE_MAX_BODY_BYTES = 2 * 1024 * 1024;--// The content-type routing decision needs only the response headers, so it-// keeps the tight timeout the probe always had. The body download (for-// metadata extraction) runs alongside the browser crawl, so it gets a more-// generous overall budget.-const PROBE_HEADERS_TIMEOUT_MS = 5_000;-const PROBE_TIMEOUT_MS = 30_000;--const PROBE_HTML_CONTENT_TYPES = new Set<string>([- ASSET_TYPES.TEXT_HTML,- "application/xhtml+xml",-]);--interface UrlProbeResult {- contentType: string | null;- /**- * Resolves with the page's preview metadata (or null). The extraction runs- * in the background so it can overlap with the browser crawl — await it- * only when the metadata is actually needed. Never rejects.- */- metadata: Promise<ParseSubprocessOutput["metadata"] | null>;-}--/**- * Probes the URL with a plain GET to determine its content type. When the- * response is an HTML page, the body is also parsed (via the parse subprocess- * in metadata-only mode) so callers get the page's preview metadata without- * waiting for the full browser render. The returned promise resolves once the- * content type is known; the metadata extraction keeps running in the- * background behind `metadata`. Extraction is best-effort and never affects- * the returned content type.- */-async function getContentTypeAndMetadata(- url: string,- jobId: string,- abortSignal: AbortSignal,- runProxy: RunProxyConfig,- opts?: { skipMetadataExtraction?: boolean },-): Promise<UrlProbeResult> {- return await withSpan(- tracer,- "crawlerWorker.getContentTypeAndMetadata",- {- attributes: {- "bookmark.url": url,- "bookmark.domain": getBookmarkDomain(url),- "job.id": jobId,- },- },- async () => {- // The request-level signal uses the long budget (it also governs the- // body read); the wait for the headers is raced separately against the- // short timeout so a dead host can't delay the routing decision.- const probeAbort = new AbortController();- let response;- try {- logger.info(- `[Crawler][${jobId}] Attempting to determine the content-type for the url ${truncateUrl(url)}`,- );- response = await raceWith(- fetchWithProxy(- url,- {- method: "GET",- signal: AbortSignal.any([- AbortSignal.timeout(PROBE_TIMEOUT_MS),- abortSignal,- probeAbort.signal,- ]),- size: PROBE_MAX_BODY_BYTES,- headers: serverConfig.crawler.preflightUserAgent- ? { "User-Agent": serverConfig.crawler.preflightUserAgent }- : undefined,- },- runProxy,- ),- timeoutRejectRace(- PROBE_HEADERS_TIMEOUT_MS,- `Timed out after ${PROBE_HEADERS_TIMEOUT_MS}ms waiting for the response headers`,- ),- );- } catch (e) {- // Stop the underlying fetch if it's still in flight (header timeout).- probeAbort.abort();- logger.error(- `[Crawler][${jobId}] Failed to determine the content-type for the url ${truncateUrl(url)}: ${e}`,- );- return { contentType: null, metadata: Promise.resolve(null) };- }- setSpanAttributes({- "crawler.getContentType.statusCode": response.status,- });- const rawContentType = response.headers.get("content-type");- const contentType = normalizeContentType(rawContentType);- setSpanAttributes({- "crawler.contentType": contentType ?? undefined,- });- logger.info(- `[Crawler][${jobId}] Content-type for the url ${truncateUrl(url)} is "${contentType}"`,- );-- if (!contentType || !PROBE_HTML_CONTENT_TYPES.has(contentType)) {- return { contentType, metadata: Promise.resolve(null) };- }-- // A previous run already extracted and stored this page's metadata; the- // probe was only needed for the content-type routing decision.- if (opts?.skipMetadataExtraction) {- logger.info(- `[Crawler][${jobId}] Skipping metadata extraction from the content-type probe for the url ${truncateUrl(url)} as it was already fetched by a previous run`,- );- addLogFields<"crawlerWorker.run">({- "crawler.probe.metadata": "reused_stored",- });- return { contentType, metadata: Promise.resolve(null) };- }-- // A blocked/retryable status usually means a challenge or error page- // whose metadata would be junk — don't extract it.- if (shouldRetryCrawlStatusCode(response.status)) {- logger.info(- `[Crawler][${jobId}] Skipping metadata extraction from the content-type probe for the url ${truncateUrl(url)} due to status code ${response.status}`,- );- addLogFields<"crawlerWorker.run">({- "crawler.probe.metadata": "blocked_status",- });- return { contentType, metadata: Promise.resolve(null) };- }-- // The response is an HTML page: parse its metadata from the body we've- // already fetched. This is deliberately NOT awaited so it runs alongside- // the browser crawl. It must never reject (callers may await it late or- // not at all) and any failure here must not lose the content type, as- // that would regress the asset-vs-webpage routing decision.- const metadata = (async () => {- try {- const htmlContent = await response.text();- const { metadata: parsedMetadata } = await runParseSubprocess(- htmlContent,- response.url,- jobId,- abortSignal,- { metadataOnly: true },- );- if (- isLikelyChallengePage({ title: parsedMetadata.title, htmlContent })- ) {- logger.info(- `[Crawler][${jobId}] The content-type probe response for the url ${truncateUrl(url)} looks like a bot-challenge page; ignoring its metadata`,- );- addLogFields<"crawlerWorker.run">({- "crawler.probe.metadata": "challenge_page",- });- return null;- }- logger.info(- `[Crawler][${jobId}] Extracted page metadata from the content-type probe for the url ${truncateUrl(url)}`,- );- addLogFields<"crawlerWorker.run">({- "crawler.probe.metadata": "extracted",- });- return parsedMetadata;- } catch (e) {- logger.warn(- `[Crawler][${jobId}] Failed to extract page metadata from the content-type probe for the url ${truncateUrl(url)}: ${e}`,- );- addLogFields<"crawlerWorker.run">({- "crawler.probe.metadata": "failed",- });- return null;- }- })();- return { contentType, metadata };- },- );-}--/**- * Writes the preview metadata extracted by the pre-crawl probe so the bookmark- * gets a title/thumbnail before the (slow) browser render finishes.- *- * The write is strictly fill-only: each field is wrapped in- * COALESCE(NULLIF(existing, ''), new) so it can only populate fields that are- * currently empty and never override an existing value. This matters because- * the probe extraction runs detached from the crawl attempt's lifecycle — if- * an attempt fails early, this write can fire after a *retry* (possibly on- * another worker) has already stored its final metadata, and it must not- * clobber it. The post-render metadata write refines these values within the- * owning attempt.- */-async function writeProbeMetadata(- bookmarkId: string,- metadata: ParseSubprocessOutput["metadata"],- jobId: string,-) {- // Don't store data URIs as they're not valid URLs and are usually quite large- const image =- metadata.image && !metadata.image.startsWith("data:")- ? metadata.image- : null;- if (!metadata.title && !metadata.description && !image && !metadata.logo) {- return;- }- await db- .update(bookmarkLinks)- .set({- ...(metadata.title- ? {- title: sql`COALESCE(NULLIF(${bookmarkLinks.title}, ''), ${metadata.title})`,- }- : {}),- ...(metadata.description- ? {- description: sql`COALESCE(NULLIF(${bookmarkLinks.description}, ''), ${metadata.description})`,- }- : {}),- ...(image- ? {- imageUrl: sql`COALESCE(NULLIF(${bookmarkLinks.imageUrl}, ''), ${image})`,- }- : {}),- ...(metadata.logo- ? {- favicon: sql`COALESCE(NULLIF(${bookmarkLinks.favicon}, ''), ${metadata.logo})`,- }- : {}),- // Also record that the probe metadata has been fetched and stored, so- // crawl retries can skip re-fetching it (see loadStoredProbeMetadata).- probeMetadataAt: new Date(),- })- .where(eq(bookmarkLinks.id, bookmarkId));- logger.info(- `[Crawler][${jobId}] Wrote early metadata from the content-type probe.`,- );-}--/**- * Reloads previously stored probe metadata from the bookmark row. Used on- * crawl retries (where `probeMetadataAt` shows a probe already succeeded)- * instead of re-fetching and re-parsing the page, so the blocked-render merge- * protection keeps working without the extra fetch. Never rejects.- */-async function loadStoredProbeMetadata(- bookmarkId: string,- jobId: string,-): Promise<ParseSubprocessOutput["metadata"] | null> {- const { data: row, error } = await tryCatch(- db.query.bookmarkLinks.findFirst({- where: eq(bookmarkLinks.id, bookmarkId),- columns: {- title: true,- description: true,- imageUrl: true,- favicon: true,- author: true,- publisher: true,- datePublished: true,- dateModified: true,- },- }),- );- if (error || !row) {- if (error) {- logger.warn(- `[Crawler][${jobId}] Failed to load stored probe metadata: ${error}`,- );- }- return null;- }- return {- title: row.title,- description: row.description,- image: row.imageUrl,- logo: row.favicon,- author: row.author,- publisher: row.publisher,- datePublished: row.datePublished?.toISOString() ?? null,- dateModified: row.dateModified?.toISOString() ?? null,- };-}--/**- * Downloads the asset from the URL and transforms the linkBookmark to an assetBookmark- * @param url the url the user provided- * @param assetType the type of the asset we're downloading- * @param userId the id of the user- * @param jobId the id of the job for logging- * @param bookmarkId the id of the bookmark- */-async function handleAsAssetBookmark(- url: string,- assetType: "image" | "pdf",- userId: string,- jobId: string,- bookmarkId: string,- abortSignal: AbortSignal,- runProxy: RunProxyConfig,-) {- return await withSpan(- tracer,- "crawlerWorker.handleAsAssetBookmark",- {- attributes: {- "bookmark.url": url,- "bookmark.domain": getBookmarkDomain(url),- "job.id": jobId,- "user.id": userId,- "bookmark.id": bookmarkId,- "asset.type": assetType,- },- },- async () => {- const downloaded = await downloadAndStoreFile(- url,- userId,- jobId,- assetType,- abortSignal,- runProxy,- );- if (!downloaded) {- return;- }- const fileName = path.basename(new URL(url).pathname);- await db.transaction(async (trx) => {- await updateAsset(- undefined,- {- id: downloaded.assetId,- bookmarkId,- userId,- assetType: AssetTypes.BOOKMARK_ASSET,- contentType: downloaded.contentType,- size: downloaded.size,- fileName,- },- trx,- );- await trx.insert(bookmarkAssets).values({- id: bookmarkId,- assetType,- assetId: downloaded.assetId,- content: null,- fileName,- sourceUrl: url,- });- // Switch the type of the bookmark from LINK to ASSET- await trx- .update(bookmarks)- .set({ type: BookmarkTypes.ASSET })- .where(eq(bookmarks.id, bookmarkId));- await trx.delete(bookmarkLinks).where(eq(bookmarkLinks.id, bookmarkId));- });- await AssetPreprocessingQueue.enqueue(- {- bookmarkId,- fixMode: false,- },- {- groupId: userId,- },- );- },- );-}--type StoreHtmlResult =- | { result: "stored"; assetId: string; size: number }- | { result: "store_inline" }- | { result: "not_stored" };--async function storeHtmlContent(- htmlContent: string | undefined,- userId: string,- jobId: string,-): Promise<StoreHtmlResult> {- return await withSpan(- tracer,- "crawlerWorker.storeHtmlContent",- {- attributes: {- "job.id": jobId,- "user.id": userId,- "bookmark.content.size": htmlContent- ? Buffer.byteLength(htmlContent, "utf8")- : 0,- },- },- async () => {- if (!htmlContent) {- return { result: "not_stored" };- }-- const contentSize = Buffer.byteLength(htmlContent, "utf8");-- // Only store in assets if content is >= 50KB- if (contentSize < serverConfig.crawler.htmlContentSizeThreshold) {- logger.info(- `[Crawler][${jobId}] HTML content size (${contentSize} bytes) is below threshold, storing inline`,- );- return { result: "store_inline" };- }-- const { data: quotaApproved, error: quotaError } = await tryCatch(- QuotaService.checkStorageQuota(db, userId, contentSize),- );- if (quotaError) {- logger.warn(- `[Crawler][${jobId}] Skipping HTML content storage due to quota exceeded: ${quotaError.message}`,- );- return { result: "not_stored" };- }-- const assetId = newAssetId();-- const { error: saveError } = await tryCatch(- saveAsset({- userId,- assetId,- asset: Buffer.from(htmlContent, "utf8"),- metadata: {- contentType: ASSET_TYPES.TEXT_HTML,- fileName: null,- },- quotaApproved,- }),- );- if (saveError) {- logger.error(- `[Crawler][${jobId}] Failed to store HTML content as asset: ${saveError}`,- );- throw saveError;- }-- logger.info(- `[Crawler][${jobId}] Stored large HTML content (${contentSize} bytes) as asset: ${assetId}`,- );-- return {- result: "stored",- assetId,- size: contentSize,- };- },- );-}--async function crawlAndParseUrl(- url: string,- userId: string,- jobId: string,- bookmarkId: string,- oldScreenshotAssetId: string | undefined,- oldPdfAssetId: string | undefined,- oldImageAssetId: string | undefined,- oldFullPageArchiveAssetId: string | undefined,- oldContentAssetId: string | undefined,- precrawledArchiveAssetId: string | undefined,- archiveFullPage: boolean,- forceStorePdf: boolean,- numRetriesLeft: number,- abortSignal: AbortSignal,- runProxy: RunProxyConfig,- probeMetadataPromise: Promise<ParseSubprocessOutput["metadata"] | null>,-) {- const sanitizedProxyUrl = redactUrlCredentials(- runProxy.httpsProxy ?? runProxy.httpProxy ?? "",- );-- return await withSpan(- tracer,- "crawlerWorker.crawlAndParseUrl",- {- attributes: {- "bookmark.url": url,- "bookmark.domain": getBookmarkDomain(url),- "job.id": jobId,- "user.id": userId,- "bookmark.id": bookmarkId,- "crawler.archiveFullPage": archiveFullPage,- "crawler.forceStorePdf": forceStorePdf,- "crawler.hasPrecrawledArchive": !!precrawledArchiveAssetId,- "crawler.proxy": sanitizedProxyUrl,- },- },- async () => {- let result: {- htmlContent: string;- screenshot: Buffer | undefined;- pdf: Buffer | undefined;- statusCode: number | null;- url: string;- };-- if (precrawledArchiveAssetId) {- logger.info(- `[Crawler][${jobId}] The page has been precrawled. Will use the precrawled archive instead.`,- );- const asset = await readAsset({- userId,- assetId: precrawledArchiveAssetId,- });- result = {- htmlContent: asset.asset.toString(),- screenshot: undefined,- pdf: undefined,- statusCode: 200,- url,- };- } else {- result = await crawlPage(- jobId,- url,- userId,- forceStorePdf,- abortSignal,- runProxy,- );- }- abortSignal.throwIfAborted();-- const {- htmlContent,- screenshot,- pdf,- statusCode,- url: browserUrl,- } = result;-- // Track status code in Prometheus- if (statusCode !== null) {- crawlerStatusCodeCounter- .labels(statusCode.toString(), sanitizedProxyUrl)- .inc();- setSpanAttributes({- "crawler.statusCode": statusCode,- });- }- addLogFields<"crawlerWorker.run">({- "crawler.status_code": statusCode,- });-- if (shouldRetryCrawlStatusCode(statusCode)) {- if (numRetriesLeft > 0) {- throw new Error(- `[Crawler][${jobId}] Received status code ${statusCode}. Will retry crawl. Retries left: ${numRetriesLeft}`,- );- }- logger.info(- `[Crawler][${jobId}] Received status code ${statusCode} on latest retry attempt. Proceeding without retry.`,- );- }-- const { metadata: renderMeta, readableContent: parsedReadableContent } =- await runParseSubprocess(htmlContent, browserUrl, jobId, abortSignal);- abortSignal.throwIfAborted();-- // The probe metadata extraction has been running alongside the crawl;- // this is the point where it's needed. The promise never rejects and- // all its underlying work is time-bounded.- const probeMetadata = await probeMetadataPromise;- abortSignal.throwIfAborted();-- // On the last retry attempt the crawl proceeds despite a blocked status- // code, and some bot walls serve their challenge page with a 200; in- // both cases don't let that page's metadata override clean values from- // the preflight probe.- const renderBlocked =- shouldRetryCrawlStatusCode(statusCode) ||- isLikelyChallengePage({ title: renderMeta.title, htmlContent });- addLogFields<"crawlerWorker.run">({- "crawler.render_blocked": renderBlocked,- });- if (renderBlocked && probeMetadata) {- logger.info(- `[Crawler][${jobId}] The rendered page looks blocked (status ${statusCode}); preferring preflight probe metadata.`,- );- }- const meta = resolveMetadata(renderMeta, probeMetadata, renderBlocked);-- const parseDate = (date: string | null | undefined) => {- if (!date) {- return null;- }- try {- return new Date(date);- } catch {- return null;- }- };-- // Phase 1: Write metadata immediately for fast user feedback.- // Content and asset storage happen later and can be slow (banner- // image download, screenshot/pdf upload, etc.).- await db- .update(bookmarkLinks)- .set({- title: meta.title,- description: meta.description,- // Don't store data URIs as they're not valid URLs and are usually quite large- imageUrl: meta.image?.startsWith("data:") ? null : meta.image,- favicon: meta.logo,- crawlStatusCode: statusCode,- author: meta.author,- publisher: meta.publisher,- datePublished: parseDate(meta.datePublished),- dateModified: parseDate(meta.dateModified),- })- .where(eq(bookmarkLinks.id, bookmarkId));-- let readableContent = parsedReadableContent;-- const screenshotAssetInfo = await raceWith(- storeScreenshot(screenshot, userId, jobId),- abortRace(abortSignal),- );- abortSignal.throwIfAborted();-- const pdfAssetInfo = await raceWith(- storePdf(pdf, userId, jobId),- abortRace(abortSignal),- );- abortSignal.throwIfAborted();-- const htmlContentAssetInfo = await storeHtmlContent(- readableContent?.content,- userId,- jobId,- );- abortSignal.throwIfAborted();- let imageAssetInfo: DBAssetType | null = null;- if (meta.image) {- const downloaded = await downloadAndStoreImage(- meta.image,- userId,- jobId,- abortSignal,- runProxy,- );- if (downloaded) {- imageAssetInfo = {- id: downloaded.assetId,- bookmarkId,- userId,- assetType: AssetTypes.LINK_BANNER_IMAGE,- contentType: downloaded.contentType,- size: downloaded.size,- };- }- }- abortSignal.throwIfAborted();-- // Phase 2: Write content and asset references.- // TODO(important): Restrict the size of content to store- const assetDeletionTasks: Promise<void>[] = [];- const inlineHtmlContent =- htmlContentAssetInfo.result === "store_inline"- ? (readableContent?.content ?? null)- : null;- readableContent = null;- await db.transaction(async (txn) => {- await txn- .update(bookmarkLinks)- .set({- crawledAt: new Date(),- htmlContent: inlineHtmlContent,- contentAssetId:- htmlContentAssetInfo.result === "stored"- ? htmlContentAssetInfo.assetId- : null,- })- .where(eq(bookmarkLinks.id, bookmarkId));-- if (screenshotAssetInfo) {- await updateAsset(- oldScreenshotAssetId,- {- id: screenshotAssetInfo.assetId,- bookmarkId,- userId,- assetType: AssetTypes.LINK_SCREENSHOT,- contentType: screenshotAssetInfo.contentType,- size: screenshotAssetInfo.size,- fileName: screenshotAssetInfo.fileName,- },- txn,- );- assetDeletionTasks.push(- silentDeleteAsset(userId, oldScreenshotAssetId),- );- }- if (pdfAssetInfo) {- await updateAsset(- oldPdfAssetId,- {- id: pdfAssetInfo.assetId,- bookmarkId,- userId,- assetType: AssetTypes.LINK_PDF,- contentType: pdfAssetInfo.contentType,- size: pdfAssetInfo.size,- fileName: pdfAssetInfo.fileName,- },- txn,- );- assetDeletionTasks.push(silentDeleteAsset(userId, oldPdfAssetId));- }- if (imageAssetInfo) {- await updateAsset(oldImageAssetId, imageAssetInfo, txn);- assetDeletionTasks.push(silentDeleteAsset(userId, oldImageAssetId));- }- if (htmlContentAssetInfo.result === "stored") {- await updateAsset(- oldContentAssetId,- {- id: htmlContentAssetInfo.assetId,- bookmarkId,- userId,- assetType: AssetTypes.LINK_HTML_CONTENT,- contentType: ASSET_TYPES.TEXT_HTML,- size: htmlContentAssetInfo.size,- fileName: null,- },- txn,- );- assetDeletionTasks.push(silentDeleteAsset(userId, oldContentAssetId));- } else if (oldContentAssetId) {- // Unlink the old content asset- await txn.delete(assets).where(eq(assets.id, oldContentAssetId));- assetDeletionTasks.push(silentDeleteAsset(userId, oldContentAssetId));- }- });-- // Delete the old assets if any- await Promise.all(assetDeletionTasks);-- return async () => {- if (- !precrawledArchiveAssetId &&- (serverConfig.crawler.fullPageArchive || archiveFullPage)- ) {- const archiveResult = await archiveWebpage(- htmlContent,- browserUrl,- userId,- jobId,- abortSignal,- runProxy,- );-- if (archiveResult) {- const {- assetId: fullPageArchiveAssetId,- size,- contentType,- } = archiveResult;-- await db.transaction(async (txn) => {- await updateAsset(- oldFullPageArchiveAssetId,- {- id: fullPageArchiveAssetId,- bookmarkId,- userId,- assetType: AssetTypes.LINK_FULL_PAGE_ARCHIVE,- contentType,- size,- fileName: null,- },- txn,- );- });- if (oldFullPageArchiveAssetId) {- await silentDeleteAsset(userId, oldFullPageArchiveAssetId);- }- }- }- };- },- );-}--/**- * Checks if the domain should be rate limited and throws QueueRetryAfterError if needed.- * @throws {QueueRetryAfterError} if the domain is rate limited- */-async function checkDomainRateLimit(url: string, jobId: string): Promise<void> {- return await withSpan(- tracer,- "crawlerWorker.checkDomainRateLimit",- {- attributes: {- "bookmark.url": url,- "bookmark.domain": getBookmarkDomain(url),- "job.id": jobId,- },- },- async () => {- const crawlerDomainRateLimitConfig =- serverConfig.crawler.domainRatelimiting;- if (!crawlerDomainRateLimitConfig) {- return;- }-- const rateLimitClient = await getRateLimitClient();- if (!rateLimitClient) {- return;- }-- const hostname = new URL(url).hostname;- const rateLimitResult = await rateLimitClient.checkRateLimit(- {- name: "domain-ratelimit",- maxRequests: crawlerDomainRateLimitConfig.maxRequests,- windowMs: crawlerDomainRateLimitConfig.windowMs,- },- hostname,- );-- if (!rateLimitResult.allowed) {- const resetInSeconds = rateLimitResult.resetInSeconds;- // Add jitter to prevent thundering herd: +40% random variation- const jitterFactor = 1.0 + Math.random() * 0.4; // Random value between 1.0 and 1.4- const delayMs = Math.floor(resetInSeconds * 1000 * jitterFactor);- logger.info(- `[Crawler][${jobId}] Domain "${hostname}" is rate limited. Will retry in ${(delayMs / 1000).toFixed(2)} seconds (with jitter).`,- );- throw new QueueRetryAfterError(- `Domain "${hostname}" is rate limited`,- delayMs,- );- }- },- );-}--async function runCrawler(- job: DequeuedJob<ZCrawlLinkRequest>,- maxRetries: number,-): Promise<CrawlerRunResult> {- const jobId = `${job.id}:${job.runNumber}`;- const numRetriesLeft = Math.max(maxRetries - job.runNumber, 0);-- const request = zCrawlLinkRequestSchema.safeParse(job.data);- if (!request.success) {- logger.error(- `[Crawler][${jobId}] Got malformed job request: ${request.error.toString()}`,- );- return { status: "completed" };- }-- const { bookmarkId, archiveFullPage, storePdf } = request.data;- const {- url,- userId,- createdAt,- crawledAt,- screenshotAssetId: oldScreenshotAssetId,- pdfAssetId: oldPdfAssetId,- imageAssetId: oldImageAssetId,- fullPageArchiveAssetId: oldFullPageArchiveAssetId,- contentAssetId: oldContentAssetId,- precrawledArchiveAssetId,- probeMetadataAt,- } = await getBookmarkDetails(bookmarkId);-- await checkDomainRateLimit(url, jobId);-- // Select proxy URLs once for the entire run so all requests use the same proxy.- const runProxy = selectRunProxies();-- addLogFields<"crawlerWorker.run">({- "crawler.url": url,- "crawler.domain": getBookmarkDomain(url),- "crawler.proxy": redactUrlCredentials(- runProxy.httpsProxy ?? runProxy.httpProxy ?? "",- ),- });-- logger.info(- `[Crawler][${jobId}] Will crawl "${truncateUrl(url)}" for link with id "${bookmarkId}"`,- );-- if (precrawledArchiveAssetId) {- logger.info(- `[Crawler][${jobId}] Skipped fetching content-type for the url ${url} as precrawledArchiveAssetId exists`,- );- }- // Retry runs re-probe for the content type, but if a previous run already- // extracted and stored the probe metadata (probeMetadataAt), don't re-fetch- // it — reload it from the bookmark row instead.- const reuseStoredProbeMetadata =- job.runNumber > 0 && probeMetadataAt !== null;- const { contentType, metadata: probeMetadata }: UrlProbeResult =- precrawledArchiveAssetId- ? { contentType: ASSET_TYPES.TEXT_HTML, metadata: Promise.resolve(null) }- : await getContentTypeAndMetadata(url, jobId, job.abortSignal, runProxy, {- skipMetadataExtraction: reuseStoredProbeMetadata,- });- job.abortSignal.throwIfAborted();-- // Link bookmarks get transformed into asset bookmarks if they point to a supported asset instead of a webpage- const isPdf = contentType === ASSET_TYPES.APPLICATION_PDF;+ // Link bookmarks get transformed into asset bookmarks if they point to a supported asset instead of a webpage+ const isPdf = contentType === ASSET_TYPES.APPLICATION_PDF;if (isPdf) {await handleAsAssetBookmark(@@ -2711,84 +448,28 @@ async function runCrawler(}return metadata;});- const archivalLogic = await crawlAndParseUrl(+ const archivalLogic = await crawlAndParseUrl({url,userId,jobId,bookmarkId,- oldScreenshotAssetId,- oldPdfAssetId,- oldImageAssetId,- oldFullPageArchiveAssetId,- oldContentAssetId,+ oldAssets: {+ screenshotAssetId: oldScreenshotAssetId,+ pdfAssetId: oldPdfAssetId,+ imageAssetId: oldImageAssetId,+ fullPageArchiveAssetId: oldFullPageArchiveAssetId,+ contentAssetId: oldContentAssetId,+ },precrawledArchiveAssetId,archiveFullPage,- storePdf ?? false,+ forceStorePdf: storePdf ?? false,numRetriesLeft,- job.abortSignal,+ abortSignal: job.abortSignal,runProxy,probeMetadataPromise,- );-- // Propagate priority to child jobs- const enqueueOpts: EnqueueOptions = {- priority: job.priority,- groupId: userId,- };-- // Enqueue openai job (if not set, assume it's true for backward compatibility)- if (job.data.runInference !== false) {- if (serverConfig.embedding.enableAutoIndexing) {- await EmbeddingsQueue.enqueue(- {- bookmarkId,- type: "embed",- runTaggingOnComplete: true,- },- enqueueOpts,- );- } else {- await OpenAIQueue.enqueue(- {- bookmarkId,- type: "tag",- },- enqueueOpts,- );- }- await OpenAIQueue.enqueue(- {- bookmarkId,- type: "summarize",- },- enqueueOpts,- );- }-- // Update the search index- await triggerSearchReindex(bookmarkId, enqueueOpts);-- if (serverConfig.crawler.downloadVideo) {- // Trigger a potential download of a video from the URL- await VideoWorkerQueue.enqueue(- {- bookmarkId,- url,- },- enqueueOpts,- );- }+ });- // Trigger a webhook- {- const webhookService = new WebhooksService(db);- await webhookService.triggerWebhook(- bookmarkId,- "crawled",- userId,- enqueueOpts,- );- }+ await enqueuePostCrawlJobs(job, bookmarkId, userId, url);// Do the archival as a separate last step as it has the potential for failureawait archivalLogic();