SPB Git

Repository Public

http.ts 10.6 KB 199 lines typescript

1// HTTP core: authentication, timeouts, safe retries, idempotency keys, typed errors. No dependency: global fetch only.2import { ConnectionError, SPMailError, TimeoutError, errorFromResponse } from "./errors.js"34export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>56export interface SPMailOptions {7  /** API key `spm_<prefix>_<secret>`. Keep it server-side: never ship it to a browser you do not control. */8  apiKey: string9  /** Origin of the SP Mail instance (default `https://mail.spboucher.ai`); `/api/v1` is appended when missing. */10  baseUrl?: string11  /** Custom fetch (tests, proxies, runtimes without a global fetch). */12  fetch?: FetchLike13  /** Time budget of each HTTP attempt (default 30 000 ms). */14  timeoutMs?: number15  /** Retries after the first attempt, for retryable failures only (default 2). */16  maxRetries?: number17  /** Longest `Retry-After` the client is willing to sleep through; beyond it the 429 is thrown (default 60 000 ms). */18  maxRetryDelayMs?: number19  /** Allow a plain `http://` base URL on a host that is not loopback (default false: the key would travel in clear). */20  allowInsecureHttp?: boolean21  /** Extra headers sent with every request (e.g. `User-Agent`). `Authorization` cannot be overridden here. */22  defaultHeaders?: Record<string, string>23}2425export interface RequestOptions {26  /** `Idempotency-Key` for a creating POST. Generated automatically when omitted; pass your own to make a retry of YOUR process idempotent. */27  idempotencyKey?: string28  signal?: AbortSignal29  timeoutMs?: number30  maxRetries?: number31  headers?: Record<string, string>32}3334export interface InternalRequest extends RequestOptions {35  method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"36  path: string37  query?: Record<string, unknown>38  body?: unknown39  /** Raw body (file upload) with its content type. */40  raw?: { data: BodyInit; contentType: string }41  /** The route accepts `Idempotency-Key` (docs/API.md §1): one is generated when the caller gave none. */42  idempotent?: boolean43  /** The request is naturally repeatable (same effect twice), although not a GET. */44  repeatable?: boolean45  /** Read the answer as bytes: resolves to `{ data: Uint8Array, headers: Headers }` instead of parsed JSON. */46  binary?: boolean47  /** No Authorization header (public routes). */48  anonymous?: boolean49}5051const sleep = (ms: number, signal?: AbortSignal) =>52  new Promise<void>((resolve, reject) => {53    if (signal?.aborted) return reject(signal.reason)54    const t = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve() }, ms)55    const onAbort = () => { clearTimeout(t); reject(signal!.reason) }56    signal?.addEventListener("abort", onAbort, { once: true })57  })5859export function newIdempotencyKey(): string {60  const c = globalThis.crypto61  if (c?.randomUUID) return `sdk-${c.randomUUID()}`62  const b = new Uint8Array(16)63  c.getRandomValues(b)64  return `sdk-${Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("")}`65}6667function retryAfterSeconds(h: Headers): number | null {68  const v = h.get("retry-after")69  if (!v) return null70  if (/^\d+(\.\d+)?$/.test(v.trim())) return Number(v)71  const at = Date.parse(v)72  return Number.isNaN(at) ? null : Math.max(0, (at - Date.now()) / 1000)73}7475export function buildQuery(query?: Record<string, unknown>): string {76  if (!query) return ""77  const parts: string[] = []78  for (const [k, v] of Object.entries(query)) {79    if (v === undefined || v === null) continue80    const s = Array.isArray(v) ? v.join(",") : v instanceof Date ? v.toISOString() : String(v)81    parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(s)}`)82  }83  return parts.length ? `?${parts.join("&")}` : ""84}8586export class HttpClient {87  // Private fields: the key never shows up in console.log(client), JSON.stringify(client) or util.inspect.88  readonly #apiKey: string89  readonly #fetch: FetchLike90  readonly baseUrl: string91  readonly timeoutMs: number92  readonly maxRetries: number93  readonly maxRetryDelayMs: number94  readonly #defaultHeaders: Record<string, string>9596  constructor(o: SPMailOptions) {97    if (!o || typeof o.apiKey !== "string" || !o.apiKey.trim()) throw new TypeError("SPMail: `apiKey` is required (use the SPMAIL_API_KEY environment variable, never a literal in source)")98    this.#apiKey = o.apiKey.trim()99    const f = o.fetch ?? (globalThis.fetch as FetchLike | undefined)100    if (!f) throw new TypeError("SPMail: no global fetch in this runtime; pass `fetch` in the options")101    this.#fetch = o.fetch ?? ((input, init) => (globalThis.fetch as FetchLike)(input, init))102    let base = (o.baseUrl ?? "https://mail.spboucher.ai").trim().replace(/\/+$/, "")103    if (!/\/api\/v1$/.test(base)) base += "/api/v1"104    let u: URL105    try { u = new URL(base) } catch { throw new TypeError("SPMail: `baseUrl` is not a valid URL") }106    if (u.protocol !== "https:" && u.protocol !== "http:") throw new TypeError("SPMail: `baseUrl` must be http(s)")107    const loopback = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]"108    if (u.protocol === "http:" && !loopback && !o.allowInsecureHttp) throw new TypeError("SPMail: refusing a plain http:// base URL (the API key would travel in clear); use https or set `allowInsecureHttp`")109    if (u.username || u.password || u.search) throw new TypeError("SPMail: `baseUrl` must not carry credentials or a query string")110    this.baseUrl = base111    this.timeoutMs = o.timeoutMs ?? 30_000112    this.maxRetries = Math.max(0, o.maxRetries ?? 2)113    this.maxRetryDelayMs = o.maxRetryDelayMs ?? 60_000114    this.#defaultHeaders = { ...(o.defaultHeaders ?? {}) }115  }116117  /** Exponential backoff with full jitter: 0.5 s, 1 s, 2 s … capped at 8 s. */118  #backoff(attempt: number): number {119    const cap = Math.min(8000, 500 * 2 ** attempt)120    return cap / 2 + Math.random() * (cap / 2)121  }122123  async request<T>(r: InternalRequest): Promise<T> {124    const url = `${this.baseUrl}${r.path}${buildQuery(r.query)}`125    const headers: Record<string, string> = { accept: r.binary ? "application/octet-stream" : "application/json", ...this.#defaultHeaders, ...(r.headers ?? {}) }126    if (!r.anonymous) headers.authorization = `Bearer ${this.#apiKey}`127    let body: BodyInit | undefined128    if (r.raw) { body = r.raw.data; headers["content-type"] = r.raw.contentType }129    else if (r.body !== undefined) { body = JSON.stringify(r.body); headers["content-type"] = "application/json" }130    // One key for the whole call: every retry of this call replays the same key, so a send can never be duplicated.131    const key = r.idempotent ? (r.idempotencyKey ?? newIdempotencyKey()) : undefined132    if (key !== undefined) {133      if (!/^[\x20-\x7e]{1,200}$/.test(key)) throw new TypeError("SPMail: `idempotencyKey` must be 1–200 printable ASCII characters")134      headers["idempotency-key"] = key135    }136    const safe = r.method === "GET" || r.method === "PUT" || r.method === "DELETE" || !!r.repeatable || key !== undefined137    const maxRetries = Math.max(0, r.maxRetries ?? this.maxRetries)138    const timeoutMs = r.timeoutMs ?? this.timeoutMs139140    for (let attempt = 0; ; attempt++) {141      const ctl = new AbortController()142      let timedOut = false143      const timer = setTimeout(() => { timedOut = true; ctl.abort() }, timeoutMs)144      const onAbort = () => ctl.abort()145      if (r.signal?.aborted) { clearTimeout(timer); throw new ConnectionError({ status: 0, code: "aborted", message: "Request aborted by the caller" }) }146      r.signal?.addEventListener("abort", onAbort, { once: true })147      let res: Response148      try {149        res = await this.#fetch(url, { method: r.method, headers, body, signal: ctl.signal, redirect: "error" })150      } catch (cause) {151        clearTimeout(timer)152        r.signal?.removeEventListener("abort", onAbort)153        if (r.signal?.aborted) throw new ConnectionError({ status: 0, code: "aborted", message: "Request aborted by the caller" }, { cause })154        const err = timedOut155          ? new TimeoutError({ status: 0, code: "timeout", message: `No answer from SP Mail within ${timeoutMs} ms (${r.method} ${r.path})` }, { cause })156          : new ConnectionError({ status: 0, code: "connection_error", message: `Could not reach SP Mail (${r.method} ${r.path}): ${cause instanceof Error ? cause.message : "network error"}` }, { cause })157        if (safe && attempt < maxRetries) { await sleep(this.#backoff(attempt), r.signal).catch(() => { throw err }); continue }158        throw err159      }160      try {161        if (res.ok) {162          if (r.binary) return { data: new Uint8Array(await res.arrayBuffer()), headers: res.headers } as T163          if (res.status === 204) return undefined as T164          return (await res.json()) as T165        }166        const requestId = res.headers.get("x-request-id")167        const retryAfterSec = retryAfterSeconds(res.headers)168        let code = "http_error"169        let message = `SP Mail answered ${res.status}`170        let details: unknown171        try {172          const j = (await res.json()) as { error?: { code?: string; message?: string; details?: unknown } | string; message?: string }173          if (j && typeof j.error === "object" && j.error) { code = j.error.code ?? code; message = j.error.message ?? message; details = j.error.details }174          else if (j && typeof j.error === "string") { code = j.error; message = j.message ?? message } // legacy envelope175        } catch { /* not JSON: keep the generic message */ }176        const err = errorFromResponse({ status: res.status, code, message, details, requestId, retryAfterSec })177        if (attempt < maxRetries) {178          // 429 rate_limited: the request was refused before being processed — repeating it is safe for any method.179          if (res.status === 429 && code !== "daily_send_limit_exceeded") {180            const wait = retryAfterSec !== null ? retryAfterSec * 1000 + Math.random() * 250 : this.#backoff(attempt)181            if (wait <= this.maxRetryDelayMs) { await sleep(wait, r.signal).catch(() => { throw err }); continue }182          } else if (safe && (res.status === 502 || res.status === 503 || res.status === 504 || code === "idempotency_in_progress")) {183            await sleep(this.#backoff(attempt), r.signal).catch(() => { throw err })184            continue185          }186        }187        throw err188      } catch (e) {189        if (e instanceof SPMailError) throw e190        if (timedOut) throw new TimeoutError({ status: 0, code: "timeout", message: `SP Mail did not finish answering within ${timeoutMs} ms (${r.method} ${r.path})` }, { cause: e })191        throw new ConnectionError({ status: 0, code: "connection_error", message: `Invalid answer from SP Mail (${r.method} ${r.path})` }, { cause: e })192      } finally {193        clearTimeout(timer)194        r.signal?.removeEventListener("abort", onAbort)195      }196    }197  }198}199
Files main
Menu

Theme