Files
openclaw/src/node-host/with-timeout.ts
Bin Deng c0cd3c3c08 fix: add safety timeout to session.compact() to prevent lane deadlock (#16533)
Merged via /review-pr -> /prepare-pr -> /merge-pr.

Prepared head SHA: 21e4045add
Co-authored-by: BinHPdev <219093083+BinHPdev@users.noreply.github.com>
Co-authored-by: gumadeiras <5599352+gumadeiras@users.noreply.github.com>
Reviewed-by: @gumadeiras
2026-02-14 17:54:12 -05:00

36 lines
1.1 KiB
TypeScript

export async function withTimeout<T>(
work: (signal: AbortSignal | undefined) => Promise<T>,
timeoutMs?: number,
label?: string,
): Promise<T> {
const resolved =
typeof timeoutMs === "number" && Number.isFinite(timeoutMs)
? Math.max(1, Math.floor(timeoutMs))
: undefined;
if (!resolved) {
return await work(undefined);
}
const abortCtrl = new AbortController();
const timeoutError = new Error(`${label ?? "request"} timed out`);
const timer = setTimeout(() => abortCtrl.abort(timeoutError), resolved);
timer.unref?.();
let abortListener: (() => void) | undefined;
const abortPromise: Promise<never> = abortCtrl.signal.aborted
? Promise.reject(abortCtrl.signal.reason ?? timeoutError)
: new Promise((_, reject) => {
abortListener = () => reject(abortCtrl.signal.reason ?? timeoutError);
abortCtrl.signal.addEventListener("abort", abortListener, { once: true });
});
try {
return await Promise.race([work(abortCtrl.signal), abortPromise]);
} finally {
clearTimeout(timer);
if (abortListener) {
abortCtrl.signal.removeEventListener("abort", abortListener);
}
}
}