File size: 13,522 Bytes
a080db2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/**

 * @fileoverview The one REST helper every module uses.

 *

 * Centralizing REST here keeps behavior consistent across auth, runtime, and

 * core: one place builds the URL, attaches the Bearer header, parses JSON, maps

 * a non-2xx response to a typed `HttpError`, and retries only safe (idempotent)

 * calls on a transient failure. Modules never call `fetch` directly, so none of

 * them can drift on error handling or auth headers.

 *

 * Uses the global `fetch`, which exists on both a modern phone and a modern

 * server, so REST needs no platform input (unlike sockets and storage).

 *

 * See docs/issues/004-cloud-client/design.md ("The shared HTTP helper").

 */
import { HttpError } from "./errors";
import type { Logger } from "./logger";
import { systemTimers, type CloudClientTimers } from "./timers";
import type { HttpTransport } from "./transports";

/**

 * Per-request options.

 *

 * `bearer` overrides the default token source for this one call: the `/exchange`

 * call presents the subject token instead of an access token, and `/refresh`

 * presents the refresh token, so they pass `bearer` explicitly rather than going

 * through `cloud.auth`.

 *

 * `idempotent` marks a call as safe to retry on a transient network error. GET

 * is always treated as idempotent; the full-replace PUT opts in via this flag.

 * POST is never retried by default because it may not be safe to repeat.

 * `signal` cancels the request, including a pending retry delay.

 */
export interface ReqOpts {
  bearer?: string;
  idempotent?: boolean;
  signal?: AbortSignal;
}

/** The REST surface the modules consume. */
export interface HttpClient {
  get<T>(path: string, opts?: ReqOpts): Promise<T>;
  head(path: string, opts?: ReqOpts): Promise<Response>;
  post<T>(path: string, body?: unknown, opts?: ReqOpts): Promise<T>;
  postForm<T>(path: string, form: FormData, opts?: ReqOpts): Promise<T>;
  put<T>(path: string, body: unknown, opts?: ReqOpts): Promise<T>;
  delete<T>(path: string, opts?: ReqOpts): Promise<T>;
  url(path: string): string;
}

/**

 * Dependencies for the helper.

 *

 * `getToken` is the default Bearer source (for example

 * `cloud.auth.getRuntimeToken` or `cloud.auth.getCoreToken`).

 * It is optional because the auth module's own `/exchange` and `/refresh` calls

 * run before any access token exists; those calls pass `opts.bearer` directly.

 */
export interface CreateHttpClientDeps {
  baseUrl: string;
  // default Bearer source, usually cloud.auth.getRuntimeToken/getCoreToken
  getToken?: () => Promise<string>;
  logger: Logger;
  fetch?: HttpTransport;
  timers?: CloudClientTimers;
}

/** How many times to retry a transient failure on an idempotent call. */
const MAX_RETRIES = 2;
/** Base backoff in milliseconds; doubles per attempt (250, 500, ...). */
const RETRY_BASE_MS = 250;

/** Recognize only fixed native categories; never log an exception message, stack or arbitrary code. */
function nativeFailureCode(error: unknown): string | undefined {
  if (typeof error !== "object" || error === null || !("code" in error)) return undefined;
  const code = error.code;
  return typeof code === "string" &&
    [
      "E_NATIVE_HTTP_DNS",
      "E_NATIVE_HTTP_CONNECT",
      "E_NATIVE_HTTP_TIMEOUT",
      "E_NATIVE_HTTP_TLS",
      "E_NATIVE_HTTP_SOCKET",
      "E_NATIVE_HTTP_INTERRUPTED",
      "E_NATIVE_HTTP_IO",
      "E_NATIVE_HTTP_OTHER",
    ].includes(code)
    ? code
    : undefined;
}

/**

 * Join a base URL and a path without producing a double slash or dropping one.

 *

 * Done by hand (not `new URL`) so a `baseUrl` that already carries a path prefix

 * (for example a proxy mount point) is preserved rather than discarded.

 */
function joinUrl(baseUrl: string, path: string): string {
  const base = baseUrl.replace(/\/+$/, "");
  const suffix = path.replace(/^\/+/, "");
  return `${base}/${suffix}`;
}

function abortReason(signal: AbortSignal): unknown {
  if (signal.reason !== undefined) return signal.reason;
  const error = new Error("The request was aborted");
  error.name = "AbortError";
  return error;
}

function throwIfAborted(signal?: AbortSignal): void {
  if (signal?.aborted) throw abortReason(signal);
}

function isAbortError(error: unknown): boolean {
  return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
}

/**

 * Read a `Retry-After` header in its delta-seconds form (a non-negative whole

 * number of seconds). The HTTP-date form, signs, fractions, exponents and any

 * other text are ignored: a caller that wants a delay gets a number or nothing,

 * never a guess. A value too large to be an exact integer is also ignored.

 */
function parseRetryAfterSeconds(headers: Headers | undefined): number | undefined {
  const raw = headers?.get("Retry-After")?.trim();
  if (!raw || !/^\d+$/.test(raw)) return undefined;
  const seconds = Number(raw);
  return Number.isSafeInteger(seconds) ? seconds : undefined;
}

export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
  const { baseUrl, getToken, logger } = deps;
  const executeFetch = deps.fetch ?? globalThis.fetch;
  const timers = deps.timers ?? systemTimers;

  /**

   * Resolve the Bearer to attach: a per-call override wins, otherwise the

   * default token source. We never log the resolved token: tokens stay out of

   * logs everywhere in this library.

   */
  async function resolveBearer(opts?: ReqOpts): Promise<string | undefined> {
    throwIfAborted(opts?.signal);
    if (opts?.bearer) return opts.bearer;
    if (getToken) {
      const bearer = await getToken();
      throwIfAborted(opts?.signal);
      return bearer;
    }
    return undefined;
  }

  async function retryDelay(delayMs: number, signal?: AbortSignal): Promise<void> {
    throwIfAborted(signal);
    await new Promise<void>((resolve, reject) => {
      let handle: unknown;
      let timerCreated = false;
      let settled = false;
      const onAbort = () => {
        if (settled) return;
        settled = true;
        signal?.removeEventListener("abort", onAbort);
        if (timerCreated) timers.clearTimeout(handle);
        reject(abortReason(signal!));
      };
      signal?.addEventListener("abort", onAbort, { once: true });
      handle = timers.setTimeout(() => {
        if (settled) return;
        settled = true;
        signal?.removeEventListener("abort", onAbort);
        resolve();
      }, delayMs);
      timerCreated = true;
      if (signal?.aborted) {
        // An injected scheduler can run synchronously before returning its handle.
        if (settled) timers.clearTimeout(handle);
        else onAbort();
      }
    });
    throwIfAborted(signal);
  }

  /**

   * The one retry loop behind every request shape (JSON, form, bodyless).

   *

   * A network-level failure (DNS, reset, timeout) is transient and worth a

   * retry on an idempotent call. A non-2xx response is NOT transient here: it is

   * a definite answer from the server, mapped to an `HttpError` for the caller

   * to branch on (auth handles its own 401 refresh-and-retry a layer up).

   * The thrown exhaustion error keeps the network-error detail out of its

   * message to avoid leaking anything host-specific into a string a host might

   * surface to a user.

   */
  async function fetchWithRetry(args: {

    method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD";

    path: string;

    headers: Record<string, string>;

    body: string | FormData | undefined;

    idempotent: boolean;

    signal?: AbortSignal;

  }): Promise<Response> {
    const { method, path, headers, body, idempotent, signal } = args;
    const url = joinUrl(baseUrl, path);

    for (let attempt = 0; attempt <= (idempotent ? MAX_RETRIES : 0); attempt++) {
      throwIfAborted(signal);
      if (attempt > 0) {
        const backoff = RETRY_BASE_MS * 2 ** (attempt - 1);
        logger.debug("http retrying request", { method, path, attempt });
        await retryDelay(backoff, signal);
      }

      let res: Response;
      try {
        throwIfAborted(signal);
        res = await executeFetch(url, { method, headers, body, signal });
        throwIfAborted(signal);
      } catch (error) {
        throwIfAborted(signal);
        if (isAbortError(error)) throw error;
        // Transient network failure: let the loop retry.
        const nativeCode = nativeFailureCode(error);
        logger.warn("http network error", { method, path, attempt, ...(nativeCode ? { nativeCode } : {}) });
        continue;
      }

      if (!res.ok) {
        // Definite answer from the server: map to a typed error, no retry.
        throw await toHttpError(res, method, path, signal);
      }

      return res;
    }

    // Exhausted retries on a transient failure.
    throw new HttpError(`Network request failed: ${method} ${path}`, 0, "NETWORK_ERROR");
  }

  async function requestRaw(

    method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD",

    path: string,

    body: unknown,

    opts?: ReqOpts,

  ): Promise<Response> {
    const bearer = await resolveBearer(opts);
    throwIfAborted(opts?.signal);

    const headers: Record<string, string> = {};
    if (bearer) headers["Authorization"] = `Bearer ${bearer}`;

    let payload: string | undefined;
    if (body !== undefined) {
      headers["Content-Type"] = "application/json";
      payload = JSON.stringify(body);
    }

    // GET and DELETE are idempotent by HTTP semantics, so safe to retry; other
    // verbs opt in via the flag.
    const idempotent = opts?.idempotent ?? (method === "GET" || method === "DELETE" || method === "HEAD");

    return await fetchWithRetry({ method, path, headers, body: payload, idempotent, signal: opts?.signal });
  }

  async function request<T>(
    method: "GET" | "POST" | "PUT" | "DELETE",
    path: string,
    body: unknown,
    opts?: ReqOpts,
  ): Promise<T> {
    const res = await requestRaw(method, path, body, opts);
    return await parseJson<T>(res, opts?.signal);
  }

  async function requestForm<T>(path: string, form: FormData, opts?: ReqOpts): Promise<T> {
    const bearer = await resolveBearer(opts);
    throwIfAborted(opts?.signal);

    // No Content-Type here: fetch/FormData must generate the multipart
    // boundary. POST is not idempotent, so retries stay opt-in.
    const headers: Record<string, string> = {};
    if (bearer) headers["Authorization"] = `Bearer ${bearer}`;

    const res = await fetchWithRetry({
      method: "POST",
      path,
      headers,
      body: form,
      idempotent: opts?.idempotent ?? false,
      signal: opts?.signal,
    });
    return await parseJson<T>(res, opts?.signal);
  }

  /**

   * Turn a non-2xx response into an `HttpError`, reading a machine-readable

   * `code` from the JSON body when the server provides one. We swallow any body

   * parse failure here because the status is the load-bearing signal and we do

   * not want a malformed error body to mask the real status.

   */
  async function toHttpError(res: Response, method: string, path: string, signal?: AbortSignal): Promise<HttpError> {
    throwIfAborted(signal);
    let code: string | undefined;
    let detail = "";
    try {
      const data = (await res.json()) as {
        code?: string;
        message?: string;
        error?: string;
        error_description?: string;
      };
      throwIfAborted(signal);
      code = data?.code ?? data?.error;
      const message = data?.message ?? data?.error_description;
      detail = message ? `: ${message}` : "";
    } catch (error) {
      throwIfAborted(signal);
      if (isAbortError(error)) throw error;
      // No JSON body, or unparseable: fall back to status alone.
    }
    throwIfAborted(signal);
    return new HttpError(
      `HTTP ${res.status} on ${method} ${path}${detail}`,
      res.status,
      code,
      parseRetryAfterSeconds(res.headers),
    );
  }

  /**

   * Parse a successful response as JSON, tolerating an empty body (a 204 or an

   * endpoint that returns nothing) by resolving to `undefined`.

   */
  async function parseJson<T>(res: Response, signal?: AbortSignal): Promise<T> {
    throwIfAborted(signal);
    const text = await res.text();
    throwIfAborted(signal);
    if (text.length === 0) return undefined as T;
    const result = JSON.parse(text) as T;
    throwIfAborted(signal);
    return result;
  }

  return {
    get<T>(path: string, opts?: ReqOpts): Promise<T> {
      return request<T>("GET", path, undefined, opts);
    },
    head(path: string, opts?: ReqOpts): Promise<Response> {
      return requestRaw("HEAD", path, undefined, opts);
    },
    post<T>(path: string, body?: unknown, opts?: ReqOpts): Promise<T> {
      return request<T>("POST", path, body, opts);
    },
    postForm<T>(path: string, form: FormData, opts?: ReqOpts): Promise<T> {
      return requestForm<T>(path, form, opts);
    },
    put<T>(path: string, body: unknown, opts?: ReqOpts): Promise<T> {
      return request<T>("PUT", path, body, opts);
    },
    delete<T>(path: string, opts?: ReqOpts): Promise<T> {
      return request<T>("DELETE", path, undefined, opts);
    },
    url(path: string): string {
      return joinUrl(baseUrl, path);
    },
  };
}