|
- export async function waitForHttp(url, options = {}) {
- const timeoutMs = options.timeoutMs || 60000;
- const intervalMs = options.intervalMs || 500;
- const attemptTimeoutMs = options.attemptTimeoutMs || 5000;
- const start = Date.now();
- let lastError;
-
- while (Date.now() - start < timeoutMs) {
- const remainingMs = timeoutMs - (Date.now() - start);
- if (remainingMs <= 0) break;
-
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), Math.min(attemptTimeoutMs, remainingMs));
- timeout.unref?.();
-
- try {
- const response = await fetch(url, { cache: 'no-store', signal: controller.signal });
- if (response.ok) return response;
- lastError = new Error(`HTTP ${response.status}`);
- } catch (error) {
- lastError = error;
- } finally {
- clearTimeout(timeout);
- }
-
- const remainingAfterAttemptMs = timeoutMs - (Date.now() - start);
- if (remainingAfterAttemptMs <= 0) break;
- await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remainingAfterAttemptMs)));
- }
-
- throw new Error(`Timed out waiting for ${url}: ${lastError?.message || 'no response'}`);
- }
|