Skip to content

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

feat(workers): optimize downloaded banner images (#3165)

Mohamed Bassemac5d7880be3b
diff --git a/apps/workers/package.json b/apps/workers/package.json
index 5b2a8a9c..e6981da5 100644
--- a/apps/workers/package.json
+++ b/apps/workers/package.json
@@ -54,6 +54,7 @@
"pdfjs-dist": "^4.2.67",
"prom-client": "^15.1.3",
"rss-parser": "^3.13.0",
+ "sharp": "^0.35.5",
"tesseract.js": "^7.0.0",
"tsx": "^4.23.13",
"typescript": "^5.9",
diff --git a/apps/workers/workers/crawlerWorker.ts b/apps/workers/workers/crawlerWorker.ts
index 8e71d64d..c0b08c04 100644
--- a/apps/workers/workers/crawlerWorker.ts
+++ b/apps/workers/workers/crawlerWorker.ts
@@ -71,6 +71,7 @@ import {
IMAGE_ASSET_TYPES,
newAssetId,
OpenAIQueue,
+ optimizeBannerImage,
QuotaService,
readAsset,
saveAsset,
@@ -1073,15 +1074,15 @@ const crawlAndParseUrl = traced(
abortSignal.throwIfAborted();
let imageAssetInfo: DBAssetType | null = null;
if (meta.image && serverConfig.crawler.downloadBannerImage) {
- const downloaded = await downloadAndStoreFile(ctx, meta.image, "image");
- if (downloaded) {
+ const banner = await downloadAndStoreBanner(ctx, meta.image);
+ if (banner) {
imageAssetInfo = {
- id: downloaded.assetId,
+ id: banner.assetId,
bookmarkId,
userId,
assetType: AssetTypes.LINK_BANNER_IMAGE,
- contentType: downloaded.contentType,
- size: downloaded.size,
+ contentType: banner.contentType,
+ size: banner.size,
};
}
}
@@ -1912,15 +1913,11 @@ function storeCapturedAsset(
/**
* 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.
+ * over the network. Decode it locally instead of failing on the unsupported
+ * protocol.
*/
-async function storeDataUriAsset(
- ctx: CrawlContext,
- url: string,
- fileType: string,
-) {
- const { userId, log } = ctx;
+function decodeDataUriImage(ctx: CrawlContext, url: string) {
+ const { log } = ctx;
const maxBytes = serverConfig.maxAssetSizeMb * 1024 * 1024;
// Guardrail 1: cap the size *before* decoding into memory. base64 encodes 3
@@ -1928,7 +1925,7 @@ async function storeDataUriAsset(
// must decode past it; the exact check below handles the rest.
if (url.length > Math.ceil((maxBytes * 4) / 3) + 1024) {
log.warn(
- `Skipping data URI ${fileType}: encoded size (${url.length} chars) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,
+ `Skipping data URI image: encoded size (${url.length} chars) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,
);
return null;
}
@@ -1937,7 +1934,7 @@ async function storeDataUriAsset(
try {
asset = dataUriToBuffer(url);
} catch (e) {
- log.error(`Failed to decode data URI ${fileType}: ${e}`);
+ log.error(`Failed to decode data URI image: ${e}`);
return null;
}
@@ -1947,31 +1944,115 @@ async function storeDataUriAsset(
const contentType = normalizeContentType(asset.type);
if (!contentType || !IMAGE_ASSET_TYPES.has(contentType)) {
log.warn(
- `Skipping data URI ${fileType} with unsupported content type: ${contentType}`,
+ `Skipping data URI image with unsupported content type: ${contentType}`,
);
return null;
}
if (asset.byteLength > maxBytes) {
log.warn(
- `Skipping data URI ${fileType}: decoded size (${asset.byteLength} bytes) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,
+ `Skipping data URI image: decoded size (${asset.byteLength} bytes) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,
);
return null;
}
- const assetId = await saveBufferAsset(ctx, `data URI ${fileType}`, asset, {
- contentType,
- });
- if (!assetId) {
- return null;
+ return { image: asset, contentType };
+}
+
+async function fetchAsset(ctx: CrawlContext, url: string, fileType: string) {
+ ctx.log.info(`Downloading ${fileType} from "${truncateUrl(url)}"`);
+ const response = await fetchWithProxy(
+ url,
+ {
+ signal: ctx.abortSignal,
+ },
+ ctx.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");
}
- return { assetId, userId, contentType, size: asset.byteLength };
+ return { contentType, body: response.body };
}
+async function fetchImage(ctx: CrawlContext, url: string) {
+ const { contentType, body } = await fetchAsset(ctx, url, "banner image");
+ const maxBytes = serverConfig.maxAssetSizeMb * 1024 * 1024;
+ // Grows in place as chunks arrive, so the banner is never held twice in memory.
+ const buffer = new ArrayBuffer(0, { maxByteLength: maxBytes });
+ const bytes = new Uint8Array(buffer);
+ for await (const chunk of body) {
+ ctx.abortSignal.throwIfAborted();
+ const offset = buffer.byteLength;
+ if (offset + chunk.length > maxBytes) {
+ throw new Error(
+ `Content length exceeds maximum allowed size: ${serverConfig.maxAssetSizeMb}MB`,
+ );
+ }
+ buffer.resize(offset + chunk.length);
+ bytes.set(Buffer.from(chunk), offset);
+ }
+ return { image: Buffer.from(buffer, 0, buffer.byteLength), contentType };
+}
+
+/**
+ * Downloads the page's banner image and stores a downscaled webp version of it.
+ * Banners are small, so unlike other downloads they're kept in memory instead
+ * of going through a temp file.
+ */
+const downloadAndStoreBanner = traced(
+ "downloadAndStoreBanner",
+ async (ctx: CrawlContext, url: string) => {
+ setSpanAttributes({
+ "bookmark.url": url,
+ "bookmark.domain": getBookmarkDomain(url),
+ });
+ try {
+ const banner = url.startsWith("data:")
+ ? decodeDataUriImage(ctx, url)
+ : await fetchImage(ctx, url);
+ if (!banner) {
+ return null;
+ }
+ const toStore =
+ (await optimizeBannerImage(banner.image, banner.contentType)) ?? banner;
+ // The crawl might have timed out while converting the banner.
+ ctx.abortSignal.throwIfAborted();
+ const assetId = await saveBufferAsset(
+ ctx,
+ "banner image",
+ toStore.image,
+ { contentType: toStore.contentType },
+ );
+ if (!assetId) {
+ return null;
+ }
+ return {
+ assetId,
+ contentType: toStore.contentType,
+ size: toStore.image.byteLength,
+ };
+ } catch (e) {
+ ctx.log.error(`Failed to download and store the banner image: ${e}`);
+ // A crawler timeout aborts the job-wide signal. Do not turn that abort
+ // into a best-effort download miss: the queue runner must observe it so
+ // the crawl is retried and is not reported as successfully completed.
+ ctx.abortSignal.throwIfAborted();
+ return null;
+ }
+ },
+);
+
const downloadAndStoreFile = traced(
"downloadAndStoreFile",
async (ctx: CrawlContext, url: string, fileType: string) => {
- const { userId, abortSignal, runProxy, log } = ctx;
+ const { userId, abortSignal, log } = ctx;
setSpanAttributes({
"bookmark.url": url,
"bookmark.domain": getBookmarkDomain(url),
@@ -1979,27 +2060,7 @@ const downloadAndStoreFile = traced(
});
let assetPath: string | undefined;
try {
- if (url.startsWith("data:")) {
- return await storeDataUriAsset(ctx, url, fileType);
- }
- log.info(`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 { contentType, body } = await fetchAsset(ctx, url, fileType);
const assetId = newAssetId();
assetPath = path.join(os.tmpdir(), assetId);
@@ -2027,7 +2088,7 @@ const downloadAndStoreFile = traced(
});
await pipeline(
- response.body,
+ body,
contentLengthEnforcer,
fsSync.createWriteStream(assetPath),
);
diff --git a/packages/plugins/assetstore-filesystem/src/index.ts b/packages/plugins/assetstore-filesystem/src/index.ts
index a07fc52e..a6d80342 100644
--- a/packages/plugins/assetstore-filesystem/src/index.ts
+++ b/packages/plugins/assetstore-filesystem/src/index.ts
@@ -40,10 +40,7 @@ export class LocalFileSystemAssetStore implements AssetStore {
await fs.promises.mkdir(assetDir, { recursive: true });
await Promise.all([
- fs.promises.writeFile(
- path.join(assetDir, "asset.bin"),
- Uint8Array.from(asset),
- ),
+ fs.promises.writeFile(path.join(assetDir, "asset.bin"), asset),
fs.promises.writeFile(
path.join(assetDir, "metadata.json"),
JSON.stringify(metadata),
diff --git a/packages/shared-server/package.json b/packages/shared-server/package.json
index 3c4c8406..079577e4 100644
--- a/packages/shared-server/package.json
+++ b/packages/shared-server/package.json
@@ -19,6 +19,7 @@
"@opentelemetry/semantic-conventions": "^1.38.0",
"@opentelemetry/winston-transport": "^0.23.0",
"@trpc/server": "^11.9.0",
+ "sharp": "^0.35.5",
"winston": "^3.11.0"
},
"devDependencies": {
diff --git a/packages/shared-server/src/bannerImages.ts b/packages/shared-server/src/bannerImages.ts
new file mode 100644
index 00000000..ad230e6b
--- /dev/null
+++ b/packages/shared-server/src/bannerImages.ts
@@ -0,0 +1,53 @@
+import { ASSET_TYPES } from "@karakeep/shared/assetdb";
+import logger from "@karakeep/shared/logger";
+
+// Banners are displayed at most ~768px wide (the bookmark preview), so this
+// leaves enough room for high density screens.
+const BANNER_MAX_WIDTH = 1200;
+
+// Banners come from untrusted pages, and a small compressed image can decode
+// into a huge number of pixels. Larger images are stored as is instead.
+const BANNER_MAX_INPUT_PIXELS = 50_000_000;
+
+/**
+ * Banners are only ever displayed, so we store a downscaled webp version of
+ * them instead of the original. Returns null if the banner should be stored
+ * as is (gifs, already webp, animated, not any smaller as webp, or if the
+ * conversion failed).
+ */
+export async function optimizeBannerImage(
+ image: Buffer,
+ contentType: string,
+): Promise<{ image: Buffer; contentType: string } | null> {
+ if (
+ contentType !== ASSET_TYPES.IMAGE_JPEG &&
+ contentType !== ASSET_TYPES.IMAGE_PNG
+ ) {
+ return null;
+ }
+ try {
+ // Lazily loaded as it's a native module that most users of this package don't need.
+ const { default: sharp } = await import("sharp");
+ const pipeline = sharp(image, {
+ limitInputPixels: BANNER_MAX_INPUT_PIXELS,
+ });
+ const metadata = await pipeline.metadata();
+ if ((metadata.pages ?? 1) > 1) {
+ return null;
+ }
+ const optimized = await pipeline
+ .rotate() // Apply the EXIF orientation
+ .resize({ width: BANNER_MAX_WIDTH, withoutEnlargement: true })
+ .webp({ quality: 80 })
+ .toBuffer();
+ // webp isn't always smaller (e.g. small or heavily compressed pngs).
+ if (optimized.byteLength >= image.byteLength) {
+ return null;
+ }
+ return { image: optimized, contentType: ASSET_TYPES.IMAGE_WEBP };
+ } catch (e) {
+ // Optimizing is best effort, the original gets stored instead.
+ logger.warn(`Failed to optimize the banner image: ${e}`);
+ return null;
+ }
+}
diff --git a/packages/shared-server/src/index.ts b/packages/shared-server/src/index.ts
index d5c9ab17..423329ba 100644
--- a/packages/shared-server/src/index.ts
+++ b/packages/shared-server/src/index.ts
@@ -1,5 +1,6 @@
export { loadAllPlugins } from "./plugins";
export * from "./assetdb";
+export * from "./bannerImages";
export { QuotaService, StorageQuotaError } from "./services/quotaService";
export * from "./queues";
export * from "./eventLogger";
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6fc4701d..f15b2a83 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1049,6 +1049,9 @@ importers:
rss-parser:
specifier: ^3.13.0
version: 3.13.0
+ sharp:
+ specifier: ^0.35.5
+ version: 0.35.5(@types/[email protected])
tesseract.js:
specifier: ^7.0.0
version: 7.0.0
@@ -1543,6 +1546,9 @@ importers:
'@trpc/server':
specifier: ^11.9.0
version: 11.9.0([email protected])
+ sharp:
+ specifier: ^0.35.5
+ version: 0.35.5(@types/[email protected])
winston:
specifier: ^3.11.0
version: 3.17.0