forked from Shared/esg
Add health check and retry logic and circuit breaker
This commit is contained in:
@@ -1,24 +1,30 @@
|
||||
/**
|
||||
* Races an async operation against a timeout.
|
||||
* Throws a distinguishable error for BaseProvider normalization.
|
||||
* 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<T>(
|
||||
promise: Promise<T>,
|
||||
operation: (signal: AbortSignal) => Promise<T>,
|
||||
timeoutMs: number,
|
||||
label = 'Operation',
|
||||
): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
let timeoutHandle: NodeJS.Timeout;
|
||||
|
||||
const operationPromise = Promise.resolve().then(() => operation(controller.signal));
|
||||
const timeoutPromise = new Promise<never>((_, 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([promise, timeoutPromise]);
|
||||
return await Promise.race([operationPromise, timeoutPromise]);
|
||||
} finally {
|
||||
clearTimeout(timeoutHandle!);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user