Open History to see the last commit
1export interface WaitForHttpReadyOptions {
2 readonly timeoutMs?: number;
3 readonly intervalMs?: number;
4 readonly requestTimeoutMs?: number;
5 readonly fetchImpl?: typeof fetch;
6 readonly signal?: AbortSignal;
7}
8
9const DEFAULT_TIMEOUT_MS = 10_000;
10const DEFAULT_INTERVAL_MS = 100;
11const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
12
13export class BackendReadinessAbortedError extends Error {
14 constructor() {
15 super("Backend readiness wait was aborted.");
16 this.name = "BackendReadinessAbortedError";
17 }
18}
19
20function delay(ms: number, signal: AbortSignal | undefined): Promise<void> {
21 return new Promise<void>((resolve, reject) => {
22 const timer = setTimeout(() => {
23 cleanup();
24 resolve();
25 }, ms);
26
27 const onAbort = () => {
28 cleanup();
29 reject(new BackendReadinessAbortedError());
30 };
31
32 const cleanup = () => {
33 clearTimeout(timer);
34 signal?.removeEventListener("abort", onAbort);
35 };
36
37 if (signal?.aborted) {
38 cleanup();
39 reject(new BackendReadinessAbortedError());
40 return;
41 }
42
43 signal?.addEventListener("abort", onAbort, { once: true });
44 });
45}
46
47export function isBackendReadinessAborted(error: unknown): error is BackendReadinessAbortedError {
48 return error instanceof BackendReadinessAbortedError;
49}
50
51export async function waitForHttpReady(
52 baseUrl: string,
53 options?: WaitForHttpReadyOptions,
54): Promise<void> {
55 const fetchImpl = options?.fetchImpl ?? fetch;
56 const signal = options?.signal;
57 const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
58 const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
59 const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
60 const deadline = Date.now() + timeoutMs;
61
62 for (;;) {
63 if (signal?.aborted) {
64 throw new BackendReadinessAbortedError();
65 }
66
67 const requestController = new AbortController();
68 const requestTimeout = setTimeout(() => {
69 requestController.abort();
70 }, requestTimeoutMs);
71 const abortRequest = () => {
72 requestController.abort();
73 };
74 signal?.addEventListener("abort", abortRequest, { once: true });
75
76 try {
77 const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
78 redirect: "manual",
79 signal: requestController.signal,
80 });
81 if (response.ok) {
82 return;
83 }
84 } catch (error) {
85 if (isBackendReadinessAborted(error)) {
86 throw error;
87 }
88 if (signal?.aborted) {
89 throw new BackendReadinessAbortedError();
90 }
91 // Retry until the backend becomes reachable or the deadline expires.
92 } finally {
93 clearTimeout(requestTimeout);
94 signal?.removeEventListener("abort", abortRequest);
95 }
96
97 if (Date.now() >= deadline) {
98 throw new Error(`Timed out waiting for backend readiness at ${baseUrl}.`);
99 }
100
101 await delay(intervalMs, signal);
102 }
103}