Add health check and retry logic and circuit breaker

This commit is contained in:
SepehrYahyaee
2026-09-28 17:01:53 +03:30
parent 22371f4a03
commit 03fa5e0f20
67 changed files with 3101 additions and 410 deletions
+10 -4
View File
@@ -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!);
}