A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
refactor(workers): more crawler refactorings (#3164)
Mohamed Bassem5888361aae8d
diff --git a/apps/workers/workers/crawlerWorker.ts b/apps/workers/workers/crawlerWorker.tsindex 273fe5d2..8e71d64d 100644--- a/apps/workers/workers/crawlerWorker.ts+++ b/apps/workers/workers/crawlerWorker.ts@@ -50,7 +50,7 @@ import {import { withWorkerEventLog, withWorkerTracing } from "workerTracing";import { getBookmarkDetails, updateAsset } from "workerUtils";-import type { ZCrawlLinkRequest } from "@karakeep/shared-server";+import type { AssetMetadata, ZCrawlLinkRequest } from "@karakeep/shared-server";import type { ZReaderViewReason } from "@karakeep/shared/types/bookmarks";import { db } from "@karakeep/db";import {@@ -391,6 +391,7 @@ async function runCrawler(),});setSpanAttributes({+ "crawler.archiveFullPage": archiveFullPage,"bookmark.id": bookmarkId,"bookmark.url": url,"bookmark.domain": getBookmarkDomain(url),@@ -454,16 +455,14 @@ async function runCrawler(}return metadata;});- const archivalLogic = await crawlAndParseUrl(ctx, {+ const page = await crawlAndParseUrl(ctx, {oldAssets: {screenshotAssetId: oldScreenshotAssetId,pdfAssetId: oldPdfAssetId,imageAssetId: oldImageAssetId,- fullPageArchiveAssetId: oldFullPageArchiveAssetId,contentAssetId: oldContentAssetId,},precrawledArchiveAssetId,- archiveFullPage,forceStorePdf: storePdf ?? false,numRetriesLeft,probeMetadataPromise,@@ -472,7 +471,17 @@ async function runCrawler(await enqueuePostCrawlJobs(ctx, job);// Do the archival as a separate last step as it has the potential for failure- await archivalLogic();+ if (+ !precrawledArchiveAssetId &&+ (serverConfig.crawler.fullPageArchive || archiveFullPage)+ ) {+ await storeFullPageArchive(+ ctx,+ page.htmlContent,+ page.url,+ oldFullPageArchiveAssetId,+ );+ }}// Record the latency from bookmark creation to crawl completion.@@ -493,46 +502,42 @@ async function runCrawler(* Checks if the domain should be rate limited and throws QueueRetryAfterError if needed.* @throws {QueueRetryAfterError} if the domain is rate limited*/-const checkDomainRateLimit = traced(- "checkDomainRateLimit",- async (ctx: CrawlContext): Promise<void> => {- const { url, log } = ctx;- const crawlerDomainRateLimitConfig =- serverConfig.crawler.domainRatelimiting;- if (!crawlerDomainRateLimitConfig) {- return;- }+async function checkDomainRateLimit(ctx: CrawlContext): Promise<void> {+ const { url, log } = ctx;+ const crawlerDomainRateLimitConfig = serverConfig.crawler.domainRatelimiting;+ if (!crawlerDomainRateLimitConfig) {+ return;+ }- const rateLimitClient = await getRateLimitClient();- if (!rateLimitClient) {- 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,- );+ 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);- log.info(- `Domain "${hostname}" is rate limited. Will retry in ${(delayMs / 1000).toFixed(2)} seconds (with jitter).`,- );- throw new QueueRetryAfterError(- `Domain "${hostname}" is rate limited`,- delayMs,- );- }- },-);+ 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);+ log.info(+ `Domain "${hostname}" is rate limited. Will retry in ${(delayMs / 1000).toFixed(2)} seconds (with jitter).`,+ );+ throw new QueueRetryAfterError(+ `Domain "${hostname}" is rate limited`,+ delayMs,+ );+ }+}// Cap how much of the probed page we buffer for metadata extraction.// Preview metadata lives in <head>, so a couple of MB is plenty.@@ -885,11 +890,9 @@ interface CrawlAndParseUrlArgs {screenshotAssetId: string | undefined;pdfAssetId: string | undefined;imageAssetId: string | undefined;- fullPageArchiveAssetId: string | undefined;contentAssetId: string | undefined;};precrawledArchiveAssetId: string | undefined;- archiveFullPage: boolean;forceStorePdf: boolean;numRetriesLeft: number;probeMetadataPromise: Promise<ParseSubprocessOutput["metadata"] | null>;@@ -897,20 +900,19 @@ interface CrawlAndParseUrlArgs {/*** 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.+ * and assets. Returns the rendered page's html and final url, which the+ * full-page archival (run later by the caller) works from.*/const crawlAndParseUrl = traced("crawlAndParseUrl",async (ctx: CrawlContext,args: CrawlAndParseUrlArgs,- ): Promise<() => Promise<void>> => {+ ): Promise<{ htmlContent: string; url: string }> => {const { url, userId, jobId, bookmarkId, abortSignal, runProxy, log } = ctx;const {oldAssets,precrawledArchiveAssetId,- archiveFullPage,forceStorePdf,numRetriesLeft,probeMetadataPromise,@@ -920,7 +922,6 @@ const crawlAndParseUrl = traced();setSpanAttributes({- "crawler.archiveFullPage": archiveFullPage,"crawler.forceStorePdf": forceStorePdf,"crawler.hasPrecrawledArchive": !!precrawledArchiveAssetId,});@@ -1028,11 +1029,8 @@ const crawlAndParseUrl = traced(if (!date) {return null;}- try {- return new Date(date);- } catch {- return null;- }+ const parsed = new Date(date);+ return isNaN(parsed.getTime()) ? null : parsed;};// Phase 1: Write metadata immediately for fast user feedback.@@ -1179,48 +1177,46 @@ const crawlAndParseUrl = traced(assetIdsToDelete.map((assetId) => silentDeleteAsset(userId, assetId)),);- return async () => {- if (- !precrawledArchiveAssetId &&- (serverConfig.crawler.fullPageArchive || archiveFullPage)- ) {- const archiveResult = await archiveWebpage(- ctx,- htmlContent,- browserUrl,- );-- if (archiveResult) {- const {- assetId: fullPageArchiveAssetId,- size,- contentType,- } = archiveResult;-- await db.transaction((txn) => {- 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);- }- }- }- };+ return { htmlContent, url: browserUrl };},);+/**+ * Archives the full page with monolith and stores it as the bookmark's+ * full-page archive, replacing (and deleting) the previous one.+ */+async function storeFullPageArchive(+ ctx: CrawlContext,+ htmlContent: string,+ url: string,+ oldAssetId: string | undefined,+): Promise<void> {+ const { bookmarkId, userId } = ctx;+ const archiveResult = await archiveWebpage(ctx, htmlContent, url);+ if (!archiveResult) {+ return;+ }+ const { assetId, size, contentType } = archiveResult;+ await db.transaction((txn) => {+ updateAsset(+ oldAssetId,+ {+ id: assetId,+ bookmarkId,+ userId,+ assetType: AssetTypes.LINK_FULL_PAGE_ARCHIVE,+ contentType,+ size,+ fileName: null,+ },+ txn,+ );+ });+ if (oldAssetId) {+ await silentDeleteAsset(userId, oldAssetId);+ }+}+interface CrawlPageResult {htmlContent: string;screenshot: Buffer | undefined;@@ -1253,17 +1249,15 @@ export const crawlPage = traced(const isRunningInProxyContext =proxyConfig !== undefined &&!matchesNoProxy(url, proxyConfig.bypass?.split(",") ?? []);- const context = await span("crawlPage.createContext", () =>- browser.newContext({- viewport: { width: 1440, height: 900 },- userAgent,- // A UTC browser behind a proxy that geolocates elsewhere is a- // strong bot signal; this should match the proxy's location.- timezoneId: serverConfig.crawler.browserTimezone,- proxy: proxyConfig,- serviceWorkers: "block",- }),- );+ const context = await browser.newContext({+ viewport: { width: 1440, height: 900 },+ userAgent,+ // A UTC browser behind a proxy that geolocates elsewhere is a+ // strong bot signal; this should match the proxy's location.+ timezoneId: serverConfig.crawler.browserTimezone,+ proxy: proxyConfig,+ serviceWorkers: "block",+ });trackContext(jobId, context);let page: Page | undefined;@@ -1282,9 +1276,9 @@ export const crawlPage = traced(const activePage = page;// Navigate to the target URL- const navigationValidation = await span(- "crawlPage.validateNavigationTarget",- () => validateUrl(url, isRunningInProxyContext),+ const navigationValidation = await validateUrl(+ url,+ isRunningInProxyContext,);if (!navigationValidation.ok) {throw new Error(@@ -1369,13 +1363,11 @@ export const crawlPage = traced(},);-const getBrowserInstance = traced(- "crawlPage.getBrowserInstance",- async (): Promise<Browser | undefined> =>- serverConfig.crawler.browserConnectOnDemand- ? startBrowserInstance()- : getGlobalBrowser(),-);+async function getBrowserInstance(): Promise<Browser | undefined> {+ return serverConfig.crawler.browserConnectOnDemand+ ? startBrowserInstance()+ : getGlobalBrowser();+}/*** Renders a precrawled archive (e.g. a SingleFile capture uploaded by the@@ -1484,121 +1476,114 @@ async function renderPrecrawledArchiveScreenshot(* Creates and configures the page: redirect guard, adblocking, dialog* auto-dismissal, media/SSRF request blocking, and abort wiring.*/-const setupPage = traced(- "crawlPage.setupPage",- async (- ctx: CrawlContext,- context: BrowserContext,- proxyConfig: BrowserContextOptions["proxy"],- ): Promise<{ page: Page; autoconsentEnabled: boolean }> => {- const { jobId, abortSignal, log } = ctx;- // Create a new page in the context- const nextPage = await context.newPage();- const cdpSession = await installRedirectGuard(- context,- nextPage,- jobId,- proxyConfig,- );+async function setupPage(+ ctx: CrawlContext,+ context: BrowserContext,+ proxyConfig: BrowserContextOptions["proxy"],+): Promise<{ page: Page; autoconsentEnabled: boolean }> {+ const { jobId, abortSignal, log } = ctx;+ // 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);- }+ // 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.- });+ // 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;- }+ // 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,+ 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) {+ log.warn(+ `Blocking sub-request to disallowed URL "${requestUrl}": ${validation.reason}`,);- if (!validation.ok) {- log.warn(- `Blocking sub-request to disallowed URL "${requestUrl}": ${validation.reason}`,- );- await route.abort("blockedbyclient");- return;- }+ await route.abort("blockedbyclient");+ return;}+ }- // Continue with other requests- await route.fallback();- });+ // Continue with other requests+ await route.fallback();+ });- // Install autoconsent AFTER the redirect guard and SSRF request router- // are in place (conservative ordering; it injects scripts). No-op unless- // enabled and the bundle loaded.- const autoconsentEnabled = await installAutoconsent(nextPage, jobId);-- // 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 },- );+ // Install autoconsent AFTER the redirect guard and SSRF request router+ // are in place (conservative ordering; it injects scripts). No-op unless+ // enabled and the bundle loaded.+ const autoconsentEnabled = await installAutoconsent(nextPage, jobId);++ // 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 { page: nextPage, autoconsentEnabled };- },-);+ return { page: nextPage, autoconsentEnabled };+}/**- * Captures a JPEG screenshot of the page. Failures and timeouts are logged and- * reported as `undefined` since the screenshot is best-effort.+ * Captures a screenshot or PDF of the page. Failures and timeouts are logged+ * and reported as `undefined` since both are best-effort.*/-const captureScreenshot = traced(- "crawlPage.captureScreenshot",- async (ctx: CrawlContext, activePage: Page): Promise<Buffer | undefined> => {- const { abortSignal, log } = ctx;- const { data: screenshotData, error: screenshotError } = await tryCatch(+function captureAsset(+ ctx: CrawlContext,+ kind: keyof typeof CAPTURED_ASSETS,+ capture: () => Promise<Buffer>,+): Promise<Buffer | undefined> {+ const { abortSignal, log } = ctx;+ const { captureSpanName, label } = CAPTURED_ASSETS[kind];+ return span(captureSpanName, async () => {+ const { data, error } = await tryCatch(raceWith<Buffer>(- activePage.screenshot({- // If you change this, change the content type in CAPTURED_ASSETS too.- type: "jpeg",- fullPage: serverConfig.crawler.fullPageScreenshot,- quality: 80,- }),+ capture(),timeoutRace<Buffer>(serverConfig.crawler.screenshotTimeoutSec * 1000,() => {@@ -1611,17 +1596,26 @@ const captureScreenshot = traced(),);abortSignal.throwIfAborted();- if (screenshotError) {- log.warn(`Failed to capture the screenshot. Reason: ${screenshotError}`);+ if (error) {+ log.warn(`Failed to capture the ${label}. Reason: ${error}`);return undefined;}- setSpanAttributes({ "asset.size": screenshotData.byteLength });- log.info(- `Finished capturing page content and a screenshot. FullPageScreenshot: ${serverConfig.crawler.fullPageScreenshot}`,- );- return screenshotData;- },-);+ setSpanAttributes({ "asset.size": data.byteLength });+ log.info(`Captured the ${label} (${data.byteLength} bytes)`);+ return data;+ });+}++function captureScreenshot(ctx: CrawlContext, page: Page) {+ return captureAsset(ctx, "screenshot", () =>+ page.screenshot({+ // If you change this, change the content type in CAPTURED_ASSETS too.+ type: "jpeg",+ fullPage: serverConfig.crawler.fullPageScreenshot,+ quality: 80,+ }),+ );+}/*** Extracts the page HTML and (depending on config) captures a screenshot and@@ -1635,8 +1629,7 @@ const capturePageAssets = traced(forceStorePdf: boolean,): Promise<[string, Buffer | undefined, Buffer | undefined]> => {const { abortSignal, log } = ctx;- const htmlPromise = span("crawlPage.extractHtml", async () => {- const content = await activePage.content();+ const htmlPromise = activePage.content().then((content) => {abortSignal.throwIfAborted();log.info(`Successfully fetched the page content.`);return content;@@ -1646,35 +1639,11 @@ const capturePageAssets = traced(? captureScreenshot(ctx, activePage): Promise.resolve(undefined);- const pdfPromise: Promise<Buffer | undefined> =+ const pdfPromise =serverConfig.crawler.storePdf || forceStorePdf- ? span("crawlPage.capturePdf", 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) {- log.warn(`Failed to capture the PDF. Reason: ${pdfError}`);- return undefined;- }- setSpanAttributes({ "asset.size": pdfData.byteLength });- log.info(`Finished capturing page content as PDF`);- return pdfData;- })+ ? captureAsset(ctx, "pdf", () =>+ activePage.pdf({ format: "A4", printBackground: true }),+ ): Promise.resolve(undefined);const captureResults = await Promise.all([@@ -1707,17 +1676,15 @@ const closePageAndContext = traced(// even if context.close() later hangs.if (page) {const pageToClose = page;- const pageClosed = await span("crawlPage.cleanup.closePage", () =>- raceWith<boolean>(- pageToClose- .close()- .then(() => true)- .catch((e: unknown) => {- log.warn(`page.close() failed: ${e}`);- return true;- }),- timeoutRace<boolean>(PAGE_CLOSE_TIMEOUT_MS, () => false),- ),+ const pageClosed = await raceWith<boolean>(+ pageToClose+ .close()+ .then(() => true)+ .catch((e: unknown) => {+ log.warn(`page.close() failed: ${e}`);+ return true;+ }),+ timeoutRace<boolean>(PAGE_CLOSE_TIMEOUT_MS, () => false),);setSpanAttributes({ "crawler.cleanup.pageClosed": pageClosed });if (!pageClosed) {@@ -1728,17 +1695,15 @@ const closePageAndContext = traced(// 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 span("crawlPage.cleanup.closeContext", () =>- raceWith<boolean>(- context- .close()- .then(() => true)- .catch((e: unknown) => {- log.warn(`context.close() failed: ${e}`);- return true; // Error means it's likely already closed- }),- timeoutRace<boolean>(CONTEXT_CLOSE_TIMEOUT_MS, () => false),- ),+ const contextClosed = await raceWith<boolean>(+ context+ .close()+ .then(() => true)+ .catch((e: unknown) => {+ log.warn(`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 });@@ -1750,16 +1715,14 @@ const closePageAndContext = traced(// Only close the browser if it was created on demandif (serverConfig.crawler.browserConnectOnDemand) {- await span("crawlPage.cleanup.closeBrowser", () =>- browser- .close()- .then(() => {- untrackContext(jobId);- })- .catch((e: unknown) => {- log.warn(`browser.close() failed: ${e}`);- }),- );+ await browser+ .close()+ .then(() => {+ untrackContext(jobId);+ })+ .catch((e: unknown) => {+ log.warn(`browser.close() failed: ${e}`);+ });}},);@@ -1870,16 +1833,51 @@ async function enqueuePostCrawlJobs(// Asset storage: screenshots, PDFs, images, HTML content, archives// ---------------------------------------------------------------------------+/**+ * Saves the buffer as a new asset if it fits in the user's storage quota.+ * Returns the new asset's id, or null (logged) when over quota.+ */+async function saveBufferAsset(+ ctx: CrawlContext,+ label: string,+ asset: Buffer,+ metadata: AssetMetadata,+): Promise<string | null> {+ const { data: quotaApproved, error: quotaError } = await tryCatch(+ QuotaService.checkStorageQuota(db, ctx.userId, asset.byteLength),+ );+ if (quotaError) {+ ctx.log.warn(+ `Skipping ${label} storage due to quota exceeded: ${quotaError.message}`,+ );+ return null;+ }+ const assetId = newAssetId();+ await saveAsset({+ userId: ctx.userId,+ assetId,+ metadata,+ asset,+ quotaApproved,+ });+ ctx.log.info(+ `Stored the ${label} as assetId: ${assetId} (${asset.byteLength} bytes)`,+ );+ return assetId;+}+const CAPTURED_ASSETS = {screenshot: {- spanName: "storeScreenshot",+ captureSpanName: "crawlPage.captureScreenshot",+ storeSpanName: "storeScreenshot",label: "screenshot",// Must match the format capturePageAssets takes the screenshot in.contentType: "image/jpeg",fileName: "screenshot.jpeg",},pdf: {- spanName: "storePdf",+ captureSpanName: "crawlPage.capturePdf",+ storeSpanName: "storePdf",label: "PDF",contentType: "application/pdf",fileName: "page.pdf",@@ -1892,36 +1890,21 @@ function storeCapturedAsset(kind: keyof typeof CAPTURED_ASSETS,data: Buffer | undefined,) {- const { userId, log } = ctx;- const { spanName, label, contentType, fileName } = CAPTURED_ASSETS[kind];- return span(spanName, async () => {+ const { storeSpanName, label, contentType, fileName } = CAPTURED_ASSETS[kind];+ return span(storeSpanName, async () => {setSpanAttributes({ "asset.size": data?.byteLength ?? 0 });if (!data) {- log.info(`Skipping storing the ${label} as it's empty.`);+ ctx.log.info(`Skipping storing the ${label} as it's empty.`);return null;}- const { data: quotaApproved, error: quotaError } = await tryCatch(- QuotaService.checkStorageQuota(db, userId, data.byteLength),- );- if (quotaError) {- log.warn(- `Skipping ${label} storage due to quota exceeded: ${quotaError.message}`,- );+ const assetId = await saveBufferAsset(ctx, label, data, {+ contentType,+ fileName,+ });+ if (!assetId) {return null;}-- const assetId = newAssetId();- await saveAsset({- userId,- assetId,- metadata: { contentType, fileName },- asset: data,- quotaApproved,- });- log.info(- `Stored the ${label} as assetId: ${assetId} (${data.byteLength} bytes)`,- );return { assetId, contentType, fileName, size: data.byteLength };});}@@ -1976,27 +1959,12 @@ async function storeDataUriAsset(return null;}- const { data: quotaApproved, error: quotaError } = await tryCatch(- QuotaService.checkStorageQuota(db, userId, asset.byteLength),- );- if (quotaError) {- log.warn(- `Skipping data URI ${fileType} storage due to quota exceeded: ${quotaError.message}`,- );+ const assetId = await saveBufferAsset(ctx, `data URI ${fileType}`, asset, {+ contentType,+ });+ if (!assetId) {return null;}-- const assetId = newAssetId();- await saveAsset({- userId,- assetId,- metadata: { contentType },- asset,- quotaApproved,- });- log.info(- `Stored data URI ${fileType} as assetId: ${assetId} (${asset.byteLength} bytes)`,- );return { assetId, userId, contentType, size: asset.byteLength };}@@ -2126,9 +2094,12 @@ const archiveWebpage = traced(const assetId = newAssetId();const assetPath = path.join(os.tmpdir(), assetId);- let res = await execa({+ const res = await execa({input: html,cancelSignal: abortSignal,+ // Report failures through the result instead of throwing, so that they+ // are handled below and the temp file is cleaned up.+ reject: false,env: {https_proxy: runProxy.httpsProxy,http_proxy: runProxy.httpProxy,@@ -2146,17 +2117,12 @@ const archiveWebpage = traced(assetPath,]);- if (res.isCanceled) {- log.error(`Canceled archiving the page as we hit global timeout.`);- await tryCatch(fs.unlink(assetPath));- return null;- }-- if (res.exitCode !== 0) {- log.error(- `Failed to archive the page as the command exited with code ${res.exitCode}`,- );+ if (res.failed) {await tryCatch(fs.unlink(assetPath));+ // A job timeout must still fail the job so the crawl is retried rather+ // than reported as completed (see downloadAndStoreFile).+ abortSignal.throwIfAborted();+ log.error(`Failed to archive the page: ${res.shortMessage}`);return null;}@@ -2221,7 +2187,7 @@ const storeHtmlContent = traced(ctx: CrawlContext,htmlContent: string | undefined,): Promise<StoreHtmlResult> => {- const { userId, log } = ctx;+ const { log } = ctx;setSpanAttributes({"bookmark.content.size": htmlContent? Buffer.byteLength(htmlContent, "utf8")@@ -2241,43 +2207,15 @@ const storeHtmlContent = traced(return { result: "store_inline" };}- const { data: quotaApproved, error: quotaError } = await tryCatch(- QuotaService.checkStorageQuota(db, userId, contentSize),+ const assetId = await saveBufferAsset(+ ctx,+ "HTML content",+ Buffer.from(htmlContent, "utf8"),+ { contentType: ASSET_TYPES.TEXT_HTML, fileName: null },);- if (quotaError) {- log.warn(- `Skipping HTML content storage due to quota exceeded: ${quotaError.message}`,- );+ if (!assetId) {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) {- log.error(`Failed to store HTML content as asset: ${saveError}`);- throw saveError;- }-- log.info(- `Stored large HTML content (${contentSize} bytes) as asset: ${assetId}`,- );-- return {- result: "stored",- assetId,- size: contentSize,- };+ return { result: "stored", assetId, size: contentSize };},);