Skip to content

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

fix: fix promise race leaks in the worker (#2737)

Mohamed Bassem6610a1aadb54
diff --git a/apps/workers/utils.ts b/apps/workers/utils.ts
index 2f56d3f0..1cacea19 100644
--- a/apps/workers/utils.ts
+++ b/apps/workers/utils.ts
@@ -1,16 +1,157 @@
+/**
+ * Helpers for `Promise.race` without the classic memory leak.
+ *
+ * The leak: when you race a short-lived work promise against a long-lived
+ * cancellation promise (abort signal, shared timer, etc.), the losing side's
+ * handlers stay registered on the long-lived producer even after the race
+ * settles. Over many races this pins closures — and everything they capture —
+ * in memory until the long-lived promise finally resolves or the signal fires.
+ *
+ * The fix: each contender exposes an explicit `cleanup()` that detaches its
+ * listener / clears its timer. `raceWith` runs cleanups in a `finally` so the
+ * loser releases its hold the instant the race resolves.
+ */
+export interface RaceContender<T> {
+ /** Promise to include in `Promise.race`. Rejections are pre-swallowed so a
+ * losing contender does not trigger `unhandledRejection`. */
+ promise: Promise<T>;
+ /** Releases resources held by this contender (listener, timer). Idempotent
+ * and safe to call even if the contender won the race. */
+ cleanup: () => void;
+}
+
+/**
+ * Contender that rejects when `signal` aborts.
+ *
+ * Attaches a single `{ once: true }` listener; `cleanup()` removes it so
+ * signals shared across many races do not accumulate dead listeners.
+ */
+export function abortRace(signal: AbortSignal): RaceContender<never> {
+ if (signal.aborted) {
+ const promise = Promise.reject(signal.reason ?? new Error("AbortError"));
+ promise.catch(() => {
+ /* suppress unhandledRejection */
+ });
+ return {
+ promise,
+ cleanup: () => {
+ /* nothing to clean up */
+ },
+ };
+ }
+
+ let onAbort: (() => void) | undefined;
+ const promise = new Promise<never>((_, reject) => {
+ onAbort = () => reject(signal.reason ?? new Error("AbortError"));
+ signal.addEventListener("abort", onAbort, { once: true });
+ });
+ promise.catch(() => {
+ /* suppress unhandledRejection if race loses */
+ });
+
+ return {
+ promise,
+ cleanup: () => {
+ if (onAbort) signal.removeEventListener("abort", onAbort);
+ },
+ };
+}
+
+/**
+ * Like `abortRace` but resolves with `value` on abort instead of rejecting.
+ *
+ * Use when the caller treats abort as a sentinel (e.g. return `null` / empty
+ * buffer) and calls `signal.throwIfAborted()` itself afterwards.
+ */
+export function abortRaceResolve<T>(
+ signal: AbortSignal,
+ value: T,
+): RaceContender<T> {
+ const base = abortRace(signal);
+ return {
+ promise: base.promise.catch(() => value),
+ cleanup: base.cleanup,
+ };
+}
+
+/**
+ * Contender that fires after `ms` milliseconds and resolves (or rejects) with
+ * whatever `onTimeout` returns/throws. `cleanup()` calls `clearTimeout` so a
+ * timer whose race already ended does not keep its closure alive.
+ */
+export function timeoutRace<T>(
+ ms: number,
+ onTimeout: () => T | PromiseLike<T>,
+): RaceContender<T> {
+ let timer: NodeJS.Timeout | undefined;
+ const promise = new Promise<T>((resolve, reject) => {
+ timer = setTimeout(() => {
+ try {
+ resolve(onTimeout());
+ } catch (e) {
+ reject(e);
+ }
+ }, ms);
+ });
+ return {
+ promise,
+ cleanup: () => {
+ if (timer) clearTimeout(timer);
+ },
+ };
+}
+
+/** Convenience: `timeoutRace` that rejects with `new Error(message)`. */
+export function timeoutRejectRace<T>(
+ ms: number,
+ message: string,
+): RaceContender<T> {
+ return timeoutRace<T>(ms, () => {
+ throw new Error(message);
+ });
+}
+
+/**
+ * `Promise.race` wrapper that always runs each contender's `cleanup()` once
+ * the race settles — regardless of which side won or threw.
+ *
+ * Prefer this over `Promise.race([...])` whenever any contender is backed by
+ * a shared/long-lived producer (abort signal, timer, etc.).
+ *
+ * @example
+ * await raceWith(
+ * page.screenshot(),
+ * timeoutRejectRace(5000, "screenshot timed out"),
+ * abortRaceResolve(signal, Buffer.alloc(0)),
+ * );
+ */
+export async function raceWith<T>(
+ work: Promise<T>,
+ ...contenders: RaceContender<T>[]
+): Promise<T> {
+ try {
+ return await Promise.race([work, ...contenders.map((c) => c.promise)]);
+ } finally {
+ for (const c of contenders) c.cleanup();
+ }
+}
+
+/**
+ * Wraps `func` so each call rejects if it does not settle within `timeoutSec`.
+ * Backed by `raceWith` + `timeoutRejectRace`, so the pending timer is cleared
+ * the moment `func` resolves — no lingering timer pinning the result in memory.
+ */
export function withTimeout<T, Ret>(
func: (param: T) => Promise<Ret>,
timeoutSec: number,
) {
return async (param: T): Promise<Ret> => {
- return await Promise.race([
+ return raceWith<Ret>(
func(param),
- new Promise<Ret>((_resolve, reject) =>
- setTimeout(
- () => reject(new Error(`Timed-out after ${timeoutSec} secs`)),
- timeoutSec * 1000,
- ),
+ timeoutRejectRace<Ret>(
+ timeoutSec * 1000,
+ `Timed-out after ${timeoutSec} secs`,
),
- ]);
+ );
};
}
diff --git a/apps/workers/workers/crawlerWorker.ts b/apps/workers/workers/crawlerWorker.ts
index a7cbd32a..e175ae73 100644
--- a/apps/workers/workers/crawlerWorker.ts
+++ b/apps/workers/workers/crawlerWorker.ts
@@ -31,6 +31,7 @@ import {
} from "playwright";
import { chromium } from "playwright-extra";
import StealthPlugin from "puppeteer-extra-plugin-stealth";
+import { abortRace, abortRaceResolve, raceWith, timeoutRace } from "utils";
import { withWorkerTracing } from "workerTracing";
import { getBookmarkDetails, updateAsset } from "workerUtils";
import { z } from "zod";
@@ -97,31 +98,6 @@ function truncateUrl(url: string): string {
return url.length > 100 ? url.slice(0, 100) + "..." : url;
}
-function abortPromise(signal: AbortSignal): Promise<never> {
- if (signal.aborted) {
- const p = Promise.reject(signal.reason ?? new Error("AbortError"));
- p.catch(() => {
- /* empty */
- }); // suppress unhandledRejection if not awaited
- return p;
- }
-
- const p = new Promise<never>((_, reject) => {
- signal.addEventListener(
- "abort",
- () => {
- reject(signal.reason ?? new Error("AbortError"));
- },
- { once: true },
- );
- });
-
- p.catch(() => {
- /* empty */
- });
- return p;
-}
-
/**
* Redact sensitive query parameters (e.g., tokens) from a URL for safe logging.
*/
@@ -240,7 +216,7 @@ function startContextReaper() {
logger.warn(
`[Crawler] Reaping stale browser context for job ${id} (age: ${Math.round((now - entry.createdAt) / 1000)}s)`,
);
- void Promise.race([
+ void raceWith<boolean>(
entry.context
.close()
.then(() => true)
@@ -250,10 +226,8 @@ function startContextReaper() {
);
return true;
}),
- new Promise<false>((r) =>
- setTimeout(() => r(false), CONTEXT_CLOSE_TIMEOUT_MS),
- ),
- ]).then((contextClosed) => {
+ 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(
@@ -746,13 +720,13 @@ async function crawlPage(
},
},
async () =>
- Promise.race([
+ raceWith(
activePage.goto(targetUrl, {
timeout: serverConfig.crawler.navigateTimeoutSec * 1000,
waitUntil: "domcontentloaded",
}),
- abortPromise(abortSignal).then(() => null),
- ]),
+ abortRaceResolve(abortSignal, null),
+ ),
);
setSpanAttributes({
"crawler.statusCode": response?.status() ?? 0,
@@ -774,13 +748,13 @@ async function crawlPage(
},
},
async () => {
- await Promise.race([
+ await raceWith<unknown>(
activePage
.waitForLoadState("networkidle", { timeout: 5000 })
.catch(() => ({})),
- new Promise((resolve) => setTimeout(resolve, 5000)),
- abortPromise(abortSignal),
- ]);
+ timeoutRace<unknown>(5000, () => undefined),
+ abortRace(abortSignal),
+ );
},
);
@@ -831,24 +805,23 @@ async function crawlPage(
async () => {
const { data: screenshotData, error: screenshotError } =
await tryCatch(
- Promise.race<Buffer>([
+ 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,
}),
- new Promise((_, reject) =>
- setTimeout(
- () =>
- reject(
- "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",
- ),
- serverConfig.crawler.screenshotTimeoutSec * 1000,
- ),
+ timeoutRace<Buffer>(
+ serverConfig.crawler.screenshotTimeoutSec * 1000,
+ () => {
+ throw new Error(
+ "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",
+ );
+ },
),
- abortPromise(abortSignal).then(() => Buffer.from("")),
- ]),
+ abortRaceResolve(abortSignal, Buffer.from("")),
+ ),
);
abortSignal.throwIfAborted();
if (screenshotError) {
@@ -881,22 +854,21 @@ async function crawlPage(
},
async () => {
const { data: pdfData, error: pdfError } = await tryCatch(
- Promise.race<Buffer>([
+ raceWith<Buffer>(
activePage.pdf({
format: "A4",
printBackground: true,
}),
- new Promise((_, reject) =>
- setTimeout(
- () =>
- reject(
- "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",
- ),
- serverConfig.crawler.screenshotTimeoutSec * 1000,
- ),
+ timeoutRace<Buffer>(
+ serverConfig.crawler.screenshotTimeoutSec * 1000,
+ () => {
+ throw new Error(
+ "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",
+ );
+ },
),
- abortPromise(abortSignal).then(() => Buffer.from("")),
- ]),
+ abortRaceResolve(abortSignal, Buffer.from("")),
+ ),
);
abortSignal.throwIfAborted();
if (pdfError) {
@@ -953,7 +925,7 @@ async function crawlPage(
"crawlerWorker.crawlPage.cleanup.closePage",
{ attributes: { "job.id": jobId } },
async () =>
- Promise.race([
+ raceWith<boolean>(
pageToClose
.close()
.then(() => true)
@@ -963,10 +935,8 @@ async function crawlPage(
);
return true;
}),
- new Promise<false>((r) =>
- setTimeout(() => r(false), PAGE_CLOSE_TIMEOUT_MS),
- ),
- ]),
+ timeoutRace<boolean>(PAGE_CLOSE_TIMEOUT_MS, () => false),
+ ),
);
setSpanAttributes({ "crawler.cleanup.pageClosed": pageClosed });
if (!pageClosed) {
@@ -982,7 +952,7 @@ async function crawlPage(
"crawlerWorker.crawlPage.cleanup.closeContext",
{ attributes: { "job.id": jobId } },
async () =>
- Promise.race([
+ raceWith<boolean>(
context
.close()
.then(() => true)
@@ -992,10 +962,8 @@ async function crawlPage(
);
return true; // Error means it's likely already closed
}),
- new Promise<false>((r) =>
- setTimeout(() => r(false), CONTEXT_CLOSE_TIMEOUT_MS),
- ),
- ]),
+ timeoutRace<boolean>(CONTEXT_CLOSE_TIMEOUT_MS, () => false),
+ ),
);
setSpanAttributes({
"crawler.cleanup.contextClosed": contextClosed,
@@ -1876,16 +1844,16 @@ async function crawlAndParseUrl(
let readableContent = parsedReadableContent;
- const screenshotAssetInfo = await Promise.race([
+ const screenshotAssetInfo = await raceWith(
storeScreenshot(screenshot, userId, jobId),
- abortPromise(abortSignal),
- ]);
+ abortRace(abortSignal),
+ );
abortSignal.throwIfAborted();
- const pdfAssetInfo = await Promise.race([
+ const pdfAssetInfo = await raceWith(
storePdf(pdf, userId, jobId),
- abortPromise(abortSignal),
- ]);
+ abortRace(abortSignal),
+ );
abortSignal.throwIfAborted();
const htmlContentAssetInfo = await storeHtmlContent(