Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

fix: use consistent proxy URL per crawler run (#2681)

Mohamed Bassemdb9862284844
diff --git a/apps/workers/metrics.ts b/apps/workers/metrics.ts
index 42b5aa46..ad3a1ee6 100644
--- a/apps/workers/metrics.ts
+++ b/apps/workers/metrics.ts
@@ -18,7 +18,7 @@ export const workerStatsCounter = new Counter({
export const crawlerStatusCodeCounter = new Counter({
name: "karakeep_crawler_status_codes_total",
help: "HTTP status codes encountered during crawling",
- labelNames: ["status_code"],
+ labelNames: ["status_code", "proxy"],
});
export const bookmarkCrawlLatencyHistogram = new Histogram({
diff --git a/apps/workers/network.ts b/apps/workers/network.ts
index 2ef8483f..d22beb58 100644
--- a/apps/workers/network.ts
+++ b/apps/workers/network.ts
@@ -236,10 +236,43 @@ export function matchesNoProxy(url: string, noProxy: string[]) {
}
}
-export function getProxyAgent(url: string) {
+/**
+ * Pre-selected proxy URLs to use consistently across a single crawler run.
+ * Created once at the start of a run via `selectRunProxies()`.
+ */
+export interface RunProxyConfig {
+ httpProxy: string | undefined;
+ httpsProxy: string | undefined;
+ noProxy: string[] | undefined;
+}
+
+/**
+ * Selects a random proxy from each configured proxy list, to be used
+ * consistently for the duration of a single crawler run.
+ */
+export function selectRunProxies(): RunProxyConfig {
const { proxy } = serverConfig;
+ return {
+ httpProxy: proxy.httpProxy ? getRandomProxy(proxy.httpProxy) : undefined,
+ httpsProxy: proxy.httpsProxy ? getRandomProxy(proxy.httpsProxy) : undefined,
+ noProxy: proxy.noProxy,
+ };
+}
- if (!proxy.httpProxy && !proxy.httpsProxy) {
+export function getProxyAgent(url: string, runProxy?: RunProxyConfig) {
+ const httpProxy = runProxy
+ ? runProxy.httpProxy
+ : serverConfig.proxy.httpProxy
+ ? getRandomProxy(serverConfig.proxy.httpProxy)
+ : undefined;
+ const httpsProxy = runProxy
+ ? runProxy.httpsProxy
+ : serverConfig.proxy.httpsProxy
+ ? getRandomProxy(serverConfig.proxy.httpsProxy)
+ : undefined;
+ const noProxy = runProxy ? runProxy.noProxy : serverConfig.proxy.noProxy;
+
+ if (!httpProxy && !httpsProxy) {
return undefined;
}
@@ -247,19 +280,16 @@ export function getProxyAgent(url: string) {
const protocol = urlObj.protocol;
// Check if URL should bypass proxy
- if (proxy.noProxy && matchesNoProxy(url, proxy.noProxy)) {
+ if (noProxy && matchesNoProxy(url, noProxy)) {
return undefined;
}
- if (protocol === "https:" && proxy.httpsProxy) {
- const selectedProxy = getRandomProxy(proxy.httpsProxy);
- return new HttpsProxyAgent(selectedProxy);
- } else if (protocol === "http:" && proxy.httpProxy) {
- const selectedProxy = getRandomProxy(proxy.httpProxy);
- return new HttpProxyAgent(selectedProxy);
- } else if (proxy.httpProxy) {
- const selectedProxy = getRandomProxy(proxy.httpProxy);
- return new HttpProxyAgent(selectedProxy);
+ if (protocol === "https:" && httpsProxy) {
+ return new HttpsProxyAgent(httpsProxy);
+ } else if (protocol === "http:" && httpProxy) {
+ return new HttpProxyAgent(httpProxy);
+ } else if (httpProxy) {
+ return new HttpProxyAgent(httpProxy);
}
return undefined;
@@ -371,6 +401,7 @@ export function buildFetchOptions({
export const fetchWithProxy = async (
url: string,
options: FetchWithProxyOptions = {},
+ runProxy?: RunProxyConfig,
) => {
const {
maxRedirects,
@@ -386,7 +417,7 @@ export const fetchWithProxy = async (
let currentBody = preparedBody;
while (true) {
- const agent = getProxyAgent(currentUrl);
+ const agent = getProxyAgent(currentUrl, runProxy);
const validation = await validateUrl(currentUrl, !!agent);
if (!validation.ok) {
diff --git a/apps/workers/workers/crawlerWorker.ts b/apps/workers/workers/crawlerWorker.ts
index cfe1288c..4c3fb29c 100644
--- a/apps/workers/workers/crawlerWorker.ts
+++ b/apps/workers/workers/crawlerWorker.ts
@@ -18,10 +18,11 @@ import {
import {
fetchWithProxy,
getBookmarkDomain,
- getRandomProxy,
matchesNoProxy,
+ selectRunProxies,
validateUrl,
} from "network";
+import type { RunProxyConfig } from "network";
import {
Browser,
BrowserContext,
@@ -126,6 +127,9 @@ function redactUrlCredentials(url: string): string {
for (const key of parsed.searchParams.keys()) {
parsed.searchParams.set(key, "REDACTED");
}
+ if (parsed.username) {
+ parsed.username = "REDACTED";
+ }
if (parsed.password) {
parsed.password = "REDACTED";
}
@@ -181,28 +185,21 @@ interface CrawlerRunResult {
status: "completed";
}
-function getPlaywrightProxyConfig(): BrowserContextOptions["proxy"] {
- const { proxy } = serverConfig;
-
- if (!proxy.httpProxy && !proxy.httpsProxy) {
- return undefined;
- }
-
- // Use HTTPS proxy if available, otherwise fall back to HTTP proxy
- const proxyList = proxy.httpsProxy || proxy.httpProxy;
- if (!proxyList) {
- // Unreachable, but TypeScript doesn't know that
+function getPlaywrightProxyConfig(
+ runProxy: RunProxyConfig,
+): BrowserContextOptions["proxy"] {
+ const proxyUrl = runProxy.httpsProxy || runProxy.httpProxy;
+ if (!proxyUrl) {
return undefined;
}
- const proxyUrl = getRandomProxy(proxyList);
const parsed = new URL(proxyUrl);
return {
server: proxyUrl,
username: parsed.username,
password: parsed.password,
- bypass: proxy.noProxy?.join(","),
+ bypass: runProxy.noProxy?.join(","),
};
}
@@ -492,6 +489,7 @@ async function browserlessCrawlPage(
jobId: string,
url: string,
abortSignal: AbortSignal,
+ runProxy: RunProxyConfig,
) {
return await withSpan(
tracer,
@@ -507,9 +505,13 @@ async function browserlessCrawlPage(
logger.info(
`[Crawler][${jobId}] Running in browserless mode. Will do a plain http request to "${url}". Screenshots will be disabled.`,
);
- const response = await fetchWithProxy(url, {
- signal: AbortSignal.any([AbortSignal.timeout(5000), abortSignal]),
- });
+ const response = await fetchWithProxy(
+ url,
+ {
+ signal: AbortSignal.any([AbortSignal.timeout(5000), abortSignal]),
+ },
+ runProxy,
+ );
logger.info(
`[Crawler][${jobId}] Successfully fetched the content of "${url}". Status: ${response.status}, Size: ${response.size}`,
);
@@ -530,6 +532,7 @@ async function crawlPage(
userId: string,
forceStorePdf: boolean,
abortSignal: AbortSignal,
+ runProxy: RunProxyConfig,
): Promise<{
htmlContent: string;
screenshot: Buffer | undefined;
@@ -562,7 +565,7 @@ async function crawlPage(
const browserCrawlingEnabled = userData.browserCrawlingEnabled;
if (browserCrawlingEnabled !== null && !browserCrawlingEnabled) {
- return browserlessCrawlPage(jobId, url, abortSignal);
+ return browserlessCrawlPage(jobId, url, abortSignal, runProxy);
}
let browser: Browser | undefined;
@@ -582,10 +585,10 @@ async function crawlPage(
},
);
if (!browser) {
- return browserlessCrawlPage(jobId, url, abortSignal);
+ return browserlessCrawlPage(jobId, url, abortSignal, runProxy);
}
- const proxyConfig = getPlaywrightProxyConfig();
+ const proxyConfig = getPlaywrightProxyConfig(runProxy);
const isRunningInProxyContext =
proxyConfig !== undefined &&
!matchesNoProxy(url, proxyConfig.bypass?.split(",") ?? []);
@@ -1268,6 +1271,7 @@ async function downloadAndStoreFile(
jobId: string,
fileType: string,
abortSignal: AbortSignal,
+ runProxy: RunProxyConfig,
) {
return await withSpan(
tracer,
@@ -1287,9 +1291,13 @@ async function downloadAndStoreFile(
logger.info(
`[Crawler][${jobId}] Downloading ${fileType} from "${url.length > 100 ? url.slice(0, 100) + "..." : url}"`,
);
- const response = await fetchWithProxy(url, {
- signal: abortSignal,
- });
+ const response = await fetchWithProxy(
+ url,
+ {
+ signal: abortSignal,
+ },
+ runProxy,
+ );
if (!response.ok || response.body == null) {
throw new Error(`Failed to download ${fileType}: ${response.status}`);
}
@@ -1376,6 +1384,7 @@ async function downloadAndStoreImage(
userId: string,
jobId: string,
abortSignal: AbortSignal,
+ runProxy: RunProxyConfig,
) {
if (!serverConfig.crawler.downloadBannerImage) {
logger.info(
@@ -1383,7 +1392,14 @@ async function downloadAndStoreImage(
);
return null;
}
- return downloadAndStoreFile(url, userId, jobId, "image", abortSignal);
+ return downloadAndStoreFile(
+ url,
+ userId,
+ jobId,
+ "image",
+ abortSignal,
+ runProxy,
+ );
}
async function archiveWebpage(
@@ -1392,6 +1408,7 @@ async function archiveWebpage(
userId: string,
jobId: string,
abortSignal: AbortSignal,
+ runProxy: RunProxyConfig,
) {
return await withSpan(
tracer,
@@ -1427,13 +1444,9 @@ async function archiveWebpage(
input: html,
cancelSignal: abortSignal,
env: {
- https_proxy: serverConfig.proxy.httpsProxy
- ? getRandomProxy(serverConfig.proxy.httpsProxy)
- : undefined,
- http_proxy: serverConfig.proxy.httpProxy
- ? getRandomProxy(serverConfig.proxy.httpProxy)
- : undefined,
- no_proxy: serverConfig.proxy.noProxy?.join(","),
+ https_proxy: runProxy.httpsProxy,
+ http_proxy: runProxy.httpProxy,
+ no_proxy: runProxy.noProxy?.join(","),
},
})("monolith", [
"-",
@@ -1508,6 +1521,7 @@ async function getContentType(
url: string,
jobId: string,
abortSignal: AbortSignal,
+ runProxy: RunProxyConfig,
): Promise<string | null> {
return await withSpan(
tracer,
@@ -1524,10 +1538,14 @@ async function getContentType(
logger.info(
`[Crawler][${jobId}] Attempting to determine the content-type for the url ${url}`,
);
- const response = await fetchWithProxy(url, {
- method: "GET",
- signal: AbortSignal.any([AbortSignal.timeout(5000), abortSignal]),
- });
+ const response = await fetchWithProxy(
+ url,
+ {
+ method: "GET",
+ signal: AbortSignal.any([AbortSignal.timeout(5000), abortSignal]),
+ },
+ runProxy,
+ );
setSpanAttributes({
"crawler.getContentType.statusCode": response.status,
});
@@ -1565,6 +1583,7 @@ async function handleAsAssetBookmark(
jobId: string,
bookmarkId: string,
abortSignal: AbortSignal,
+ runProxy: RunProxyConfig,
) {
return await withSpan(
tracer,
@@ -1586,6 +1605,7 @@ async function handleAsAssetBookmark(
jobId,
assetType,
abortSignal,
+ runProxy,
);
if (!downloaded) {
return;
@@ -1729,7 +1749,12 @@ async function crawlAndParseUrl(
forceStorePdf: boolean,
numRetriesLeft: number,
abortSignal: AbortSignal,
+ runProxy: RunProxyConfig,
) {
+ const sanitizedProxyUrl = redactUrlCredentials(
+ runProxy.httpsProxy ?? runProxy.httpProxy ?? "",
+ );
+
return await withSpan(
tracer,
"crawlerWorker.crawlAndParseUrl",
@@ -1743,6 +1768,7 @@ async function crawlAndParseUrl(
"crawler.archiveFullPage": archiveFullPage,
"crawler.forceStorePdf": forceStorePdf,
"crawler.hasPrecrawledArchive": !!precrawledArchiveAssetId,
+ "crawler.proxy": sanitizedProxyUrl,
},
},
async () => {
@@ -1776,6 +1802,7 @@ async function crawlAndParseUrl(
userId,
forceStorePdf,
abortSignal,
+ runProxy,
);
}
abortSignal.throwIfAborted();
@@ -1790,7 +1817,9 @@ async function crawlAndParseUrl(
// Track status code in Prometheus
if (statusCode !== null) {
- crawlerStatusCodeCounter.labels(statusCode.toString()).inc();
+ crawlerStatusCodeCounter
+ .labels(statusCode.toString(), sanitizedProxyUrl)
+ .inc();
setSpanAttributes({
"crawler.statusCode": statusCode,
});
@@ -1868,6 +1897,7 @@ async function crawlAndParseUrl(
userId,
jobId,
abortSignal,
+ runProxy,
);
if (downloaded) {
imageAssetInfo = {
@@ -1977,6 +2007,7 @@ async function crawlAndParseUrl(
userId,
jobId,
abortSignal,
+ runProxy,
);
if (archiveResult) {
@@ -2096,11 +2127,19 @@ async function runCrawler(
await checkDomainRateLimit(url, jobId);
+ // Select proxy URLs once for the entire run so all requests use the same proxy.
+ const runProxy = selectRunProxies();
+
logger.info(
`[Crawler][${jobId}] Will crawl "${url}" for link with id "${bookmarkId}"`,
);
- const contentType = await getContentType(url, jobId, job.abortSignal);
+ const contentType = await getContentType(
+ url,
+ jobId,
+ job.abortSignal,
+ runProxy,
+ );
job.abortSignal.throwIfAborted();
// Link bookmarks get transformed into asset bookmarks if they point to a supported asset instead of a webpage
@@ -2114,6 +2153,7 @@ async function runCrawler(
jobId,
bookmarkId,
job.abortSignal,
+ runProxy,
);
} else if (
contentType &&
@@ -2127,6 +2167,7 @@ async function runCrawler(
jobId,
bookmarkId,
job.abortSignal,
+ runProxy,
);
} else {
const archivalLogic = await crawlAndParseUrl(
@@ -2144,6 +2185,7 @@ async function runCrawler(
storePdf ?? false,
numRetriesLeft,
job.abortSignal,
+ runProxy,
);
// Propagate priority to child jobs
diff --git a/packages/shared-server/src/tracingTypes.ts b/packages/shared-server/src/tracingTypes.ts
index 4b56f457..d5581ed5 100644
--- a/packages/shared-server/src/tracingTypes.ts
+++ b/packages/shared-server/src/tracingTypes.ts
@@ -29,6 +29,7 @@ export type TracingAttributeKey =
| "crawler.getContentType.statusCode"
| "crawler.contentType"
| "crawler.statusCode"
+ | "crawler.proxy"
| "crawler.cleanup.hasPage"
| "crawler.cleanup.pageClosed"
| "crawler.cleanup.contextClosed"