All files / convex/lib discordRestTransport.ts

100% Statements 194/194
100% Branches 65/65
100% Functions 7/7
100% Lines 194/194

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1951x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 365x 365x 1x 364x 365x 365x 365x 365x 365x 365x 15x 15x 15x 15x 15x 7x 6x 15x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 15x 15x 5x 5x 5x 5x 365x 365x 20x 20x 20x 16x 16x 16x 16x 16x 16x 16x 20x 20x 20x 365x 365x 1x 1x 362x 362x 324x 324x 324x 324x 324x 360x 5x 5x 5x 5x 5x 5x 5x 5x 360x 1x 31x 31x 31x 31x 31x 31x 1x 1x 31x 31x 31x 31x 31x 31x 31x 31x 10x 31x 1x 1x 31x 1x 1x 31x 31x 31x 31x 31x 31x 31x 1x 35x 35x 20x 20x 35x 35x 15x 32x 1x 1x 35x 1x 15x 15x 15x 15x 4x 4x 15x 15x 11x 15x 15x 3x 3x 15x 15x 15x 1x 1x 15x 1x 22x 22x 22x 11x 22x 12x 12x 22x 22x 10x 22x 3x 3x 22x 22x 22x 1x 1x 1x 1x  
import { createLogger } from "@workspace/logger"
 
const DISCORD_FETCH_TIMEOUT_MS = 10_000
const DISCORD_RATE_LIMIT_MAX_RETRIES = 2
const DISCORD_RATE_LIMIT_WAIT_BUDGET_MS = 5_000
const discordRestLog = createLogger("backend.discord-rest")
 
export type DiscordJsonResponse = {
  ok: boolean
  status: number
  json?: unknown
}
 
type DiscordRestTransportOptions = {
  fetch?: typeof fetch
  sleep?: (delayMs: number) => Promise<void>
  requestTimeoutMs?: number
  maxRateLimitRetries?: number
  rateLimitWaitBudgetMs?: number
  expectedErrorStatuses?: readonly number[]
}
 
export async function fetchDiscordJson(
  url: string,
  init: RequestInit,
  options: DiscordRestTransportOptions = {}
): Promise<DiscordJsonResponse | null> {
  const fetchImpl = options.fetch ?? fetch
  const sleep = options.sleep ?? wait
  const requestTimeoutMs = options.requestTimeoutMs ?? DISCORD_FETCH_TIMEOUT_MS
  const maxRateLimitRetries =
    options.maxRateLimitRetries ?? DISCORD_RATE_LIMIT_MAX_RETRIES
  const rateLimitWaitBudgetMs =
    options.rateLimitWaitBudgetMs ?? DISCORD_RATE_LIMIT_WAIT_BUDGET_MS
  let retries = 0
  let waitedMs = 0
 
  try {
    while (true) {
      const timeoutSignal = AbortSignal.timeout(requestTimeoutMs)
      const signal = init.signal
        ? AbortSignal.any([init.signal, timeoutSignal])
        : timeoutSignal
      const response = await fetchImpl(url, {
        ...init,
        signal,
      })
 
      if (response.status === 429) {
        const retryDelayMs = await getRetryDelayMs(response)
        await discardResponseBody(response)
 
        if (
          retryDelayMs === null ||
          retries >= maxRateLimitRetries ||
          retryDelayMs > rateLimitWaitBudgetMs - waitedMs
        ) {
          discordRestLog.warn("Discord REST rate-limit retry exhausted.", {
            ...getDiscordRequestLogContext(url, init),
            status: response.status,
            retryDelayMs,
            retries,
            waitedMs,
            waitBudgetMs: rateLimitWaitBudgetMs,
          })
 
          return { ok: false, status: response.status }
        }
 
        retries += 1
        waitedMs += retryDelayMs
        await sleep(retryDelayMs)
        continue
      }
 
      if (!response.ok) {
        await discardResponseBody(response)
 
        if (options.expectedErrorStatuses?.includes(response.status) !== true) {
          discordRestLog.warn("Discord REST request failed.", {
            ...getDiscordRequestLogContext(url, init),
            status: response.status,
            retries,
            waitedMs,
          })
        }
 
        return { ok: false, status: response.status }
      }
 
      if (response.status === 204) {
        return { ok: true, status: response.status }
      }
 
      return {
        ok: true,
        status: response.status,
        json: await response.json(),
      }
    }
  } catch (error) {
    discordRestLog.error("Discord REST request failed before a response.", {
      ...getDiscordRequestLogContext(url, init),
      errorType: error instanceof Error ? error.name : typeof error,
      retries,
      waitedMs,
    })
    return null
  }
}
 
function getDiscordRequestLogContext(url: string, init: RequestInit) {
  let endpoint = "<invalid-url>"
 
  try {
    endpoint = new URL(url).pathname
  } catch {
    // The transport will surface the actual request failure separately.
  }
 
  let authScheme = "none"
 
  try {
    const authorization = new Headers(init.headers).get("Authorization")
    const scheme = authorization?.split(/\s+/, 1)[0]?.toLowerCase()
 
    if (scheme === "bot" || scheme === "bearer") {
      authScheme = scheme
    } else if (scheme) {
      authScheme = "other"
    }
  } catch {
    authScheme = "unreadable"
  }
 
  return {
    method: init.method?.toUpperCase() ?? "GET",
    endpoint,
    authScheme,
  }
}
 
async function discardResponseBody(response: Response): Promise<void> {
  if (response.body === null || response.bodyUsed) {
    return
  }
 
  try {
    await response.body.cancel()
  } catch {
    // Preserving the Discord status is more useful than surfacing cleanup errors.
  }
}
 
async function getRetryDelayMs(response: Response): Promise<number | null> {
  const headerDelay = parseRetryDelayMs(response.headers.get("Retry-After"))
 
  if (headerDelay !== null) {
    return headerDelay
  }
 
  try {
    const body: unknown = await response.json()
 
    if (typeof body !== "object" || body === null || !("retry_after" in body)) {
      return null
    }
 
    return parseRetryDelayMs(body.retry_after)
  } catch {
    return null
  }
}
 
function parseRetryDelayMs(value: unknown): number | null {
  if (
    (typeof value !== "number" && typeof value !== "string") ||
    (typeof value === "string" && value.trim() === "")
  ) {
    return null
  }
 
  const seconds = Number(value)
 
  if (!Number.isFinite(seconds) || seconds < 0) {
    return null
  }
 
  return Math.ceil(seconds * 1_000)
}
 
async function wait(delayMs: number): Promise<void> {
  await new Promise((resolve) => setTimeout(resolve, delayMs))
}