File size: 7,028 Bytes
1187b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a508243
 
 
 
 
 
 
8f68f10
 
 
 
 
 
 
 
 
 
 
 
1187b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a508243
8f68f10
 
 
a508243
 
 
 
eac6fef
 
 
 
a508243
 
 
 
1187b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import { extractErrorMessage, parseJsonOrText } from "../utils/http";

const DEFAULT_TIMEOUT_MS = 20000;
const DEFAULT_RETRY_DELAY_MS = 250;

export class ApiError extends Error {
  status: number;
  requestId?: string;
  data?: unknown;
  url: string;

  constructor(message: string, params: { status: number; requestId?: string; data?: unknown; url: string }) {
    super(message);
    this.name = "ApiError";
    this.status = params.status;
    this.requestId = params.requestId;
    this.data = params.data;
    this.url = params.url;
  }
}

export type ApiFetchOptions = {
  timeoutMs?: number;
  retries?: number;
  retryDelayMs?: number;
  retryUnsafe?: boolean;
};

type AccessTokenProvider = () => Promise<string | null>;
let accessTokenProvider: AccessTokenProvider | null = null;

export function setApiAccessTokenProvider(provider: AccessTokenProvider | null): void {
  accessTokenProvider = provider;
}

function createRequestId(): string {
  try {
    if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
      return crypto.randomUUID();
    }
  } catch {
    // ignore
  }
  const rnd = Math.random().toString(16).slice(2);
  return `req_${Date.now().toString(36)}_${rnd}`;
}

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => window.setTimeout(resolve, ms));
}

function shouldRetryStatus(status: number): boolean {
  return status === 429 || status >= 500;
}

function isSafeMethod(method: string): boolean {
  return method === "GET" || method === "HEAD" || method === "OPTIONS";
}

function withTimeoutSignal(
  signal: AbortSignal | null | undefined,
  timeoutMs: number
): { signal: AbortSignal; cleanup: () => void } {
  const controller = new AbortController();

  const onAbort = () => controller.abort();
  if (signal) {
    if (signal.aborted) controller.abort();
    else signal.addEventListener("abort", onAbort, { once: true });
  }

  const timer = window.setTimeout(() => controller.abort(), Math.max(1, timeoutMs));

  return {
    signal: controller.signal,
    cleanup: () => {
      window.clearTimeout(timer);
      if (signal) signal.removeEventListener("abort", onAbort);
    },
  };
}

export async function apiFetch(input: string, init: RequestInit = {}, options: ApiFetchOptions = {}): Promise<Response> {
  const method = String(init.method || "GET").toUpperCase();
  const retryUnsafe = Boolean(options.retryUnsafe);
  const safe = isSafeMethod(method) || retryUnsafe;
  const retries = Math.max(0, options.retries ?? (safe ? 2 : 0));
  const retryDelayMs = Math.max(25, options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS);
  const timeoutMs = Math.max(1000, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);

  let attempt = 0;
  while (true) {
    const { signal, cleanup } = withTimeoutSignal(init.signal, timeoutMs);
    try {
      const headers = new Headers(init.headers || {});
      if (!headers.has("X-Request-ID")) {
        headers.set("X-Request-ID", createRequestId());
      }
      if (accessTokenProvider && !headers.has("Authorization")) {
        try {
          const token = await accessTokenProvider();
          if (token) headers.set("Authorization", `Bearer ${token}`);
        } catch (err: any) {
          const reason = String(err?.message || "").trim();
          const suffix = reason ? ` ${reason}` : "";
          throw new Error(`Unable to acquire access token.${suffix}`.trim());
        }
      }

      const response = await fetch(input, { ...init, method, signal, headers });
      cleanup();

      if (attempt < retries && safe && shouldRetryStatus(response.status)) {
        attempt += 1;
        await sleep(retryDelayMs * attempt);
        continue;
      }
      return response;
    } catch (err) {
      cleanup();
      if (attempt < retries && safe) {
        attempt += 1;
        await sleep(retryDelayMs * attempt);
        continue;
      }
      throw err;
    }
  }
}

async function toApiError(response: Response, url: string): Promise<ApiError> {
  const parsed = await parseJsonOrText(response);
  const message = extractErrorMessage(parsed, `${response.status} ${response.statusText || "Request failed"}`);
  return new ApiError(message, {
    status: response.status,
    requestId: response.headers.get("x-request-id") || undefined,
    data: parsed.data ?? parsed.text,
    url,
  });
}

export async function apiGetJson<T>(url: string, init: RequestInit = {}, options: ApiFetchOptions = {}): Promise<T> {
  const response = await apiFetch(url, { ...init, method: "GET" }, options);
  if (!response.ok) throw await toApiError(response, url);
  return (await response.json()) as T;
}

export async function apiPostJson<T>(
  url: string,
  body: unknown,
  init: RequestInit = {},
  options: ApiFetchOptions = {}
): Promise<T> {
  const headers = new Headers(init.headers || {});
  if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
  const response = await apiFetch(
    url,
    {
      ...init,
      method: "POST",
      headers,
      body: typeof body === "string" ? body : JSON.stringify(body),
    },
    options
  );
  if (!response.ok) throw await toApiError(response, url);
  return (await response.json()) as T;
}

export async function apiPostFormJson<T>(
  url: string,
  form: FormData,
  init: RequestInit = {},
  options: ApiFetchOptions = {}
): Promise<T> {
  const response = await apiFetch(url, { ...init, method: "POST", body: form }, options);
  if (!response.ok) throw await toApiError(response, url);
  return (await response.json()) as T;
}

export async function apiPostJsonBlob(
  url: string,
  body: unknown,
  init: RequestInit = {},
  options: ApiFetchOptions = {}
): Promise<Blob> {
  const headers = new Headers(init.headers || {});
  if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
  const response = await apiFetch(
    url,
    {
      ...init,
      method: "POST",
      headers,
      body: typeof body === "string" ? body : JSON.stringify(body),
    },
    options
  );
  if (!response.ok) throw await toApiError(response, url);
  return await response.blob();
}

export async function apiPostFormBlob(
  url: string,
  form: FormData,
  init: RequestInit = {},
  options: ApiFetchOptions = {}
): Promise<Blob> {
  const response = await apiFetch(url, { ...init, method: "POST", body: form }, options);
  if (!response.ok) throw await toApiError(response, url);
  return await response.blob();
}

export async function apiPostJsonText(
  url: string,
  body: unknown,
  init: RequestInit = {},
  options: ApiFetchOptions = {}
): Promise<string> {
  const headers = new Headers(init.headers || {});
  if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
  const response = await apiFetch(
    url,
    {
      ...init,
      method: "POST",
      headers,
      body: typeof body === "string" ? body : JSON.stringify(body),
    },
    options
  );
  if (!response.ok) throw await toApiError(response, url);
  return await response.text();
}