/** * Runs an async operation with a per-attempt timeout. * * The operation receives an AbortSignal so HTTP clients can stop the actual * in-flight request when the timeout wins. A timeout without cancellation * would only stop awaiting the promise and could leave sockets/slots busy. */ export async function withTimeout( operation: (signal: AbortSignal) => Promise, timeoutMs: number, label = 'Operation', ): Promise { const controller = new AbortController(); let timeoutHandle: NodeJS.Timeout; const operationPromise = Promise.resolve().then(() => operation(controller.signal)); const timeoutPromise = new Promise((_, reject) => { timeoutHandle = setTimeout(() => { const error = new Error(`${label} timed out after ${timeoutMs}ms`); (error as NodeJS.ErrnoException).code = 'ETIMEDOUT'; controller.abort(); reject(error); }, timeoutMs); }); try { return await Promise.race([operationPromise, timeoutPromise]); } finally { clearTimeout(timeoutHandle!); } }