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 195 196 197 198 199 200 201 202 203 | 14x 14x 14x 188x 188x 188x 188x 1x 187x 97x 97x 97x 93x 4x 3x 3x 14x 14x 14x 141x 325x 231x 231x 231x 231x 231x 308x 308x 308x 296x 296x 12x 12x 12x 302x 308x 223x 222x 1x 79x 308x 79x 77x 231x 60x 296x 588x 588x 6x 290x 296x 287x 287x 3x 3x 875x 875x 864x 11x 11x 79x 79x 79x 79x 78x 78x 1x 1x 78x 78x | import type { GetTokenOptions, TokenCredential } from '../types'
import { formatAuthorizationHeader } from './token'
export const storageOAuthScope = 'https://storage.azure.com/.default'
export const keyVaultOAuthScope = 'https://vault.azure.net/.default'
export const appConfigurationOAuthScope = 'https://appconfig.azure.com/.default'
interface HeaderCredential {
getAuthorizationHeader: (scope?: string | string[], options?: GetTokenOptions) => Promise<string>
}
export type AzureRequestCredential = HeaderCredential | TokenCredential
/** Signs the complete request, as App Configuration access keys require. */
export interface RequestSigningCredential {
signRequest: (request: Request) => Promise<void>
}
export function resolveRequiredScopes(scope: string | string[]): string[] {
const scopes = (Array.isArray(scope) ? scope : [scope])
.map((value) => value.trim())
.filter((value) => value.length > 0)
if (scopes.length === 0) {
throw new TypeError('At least one non-empty scope is required')
}
return scopes
}
export async function getAuthorizationHeader(
credential: AzureRequestCredential,
scope: string | string[],
abortSignal?: AbortSignal,
): Promise<string> {
abortSignal?.throwIfAborted()
const options: [GetTokenOptions?] = abortSignal === undefined ? [] : [{ abortSignal }]
if ('getAuthorizationHeader' in credential) {
return await credential.getAuthorizationHeader(scope, ...options)
}
const token = await credential.getToken(resolveRequiredScopes(scope), ...options)
Iif (token === null) {
throw new Error('Unable to resolve a token from the configured credential')
}
return formatAuthorizationHeader(token)
}
export const defaultRetryableStatuses = [408, 429, 500, 502, 503, 504]
export const defaultMaxRetryDelayInMs = 60_000
const decimalNumber = /^-?\d+(?:\.\d+)?$/u
export interface RetryContext {
/** Zero-based number of the attempt that failed. */
attempt: number
response?: Response
error?: unknown
/** Wait the service asked for in `retry-after-ms`, `x-ms-retry-after-ms` or `Retry-After`. */
retryAfterInMs?: number
}
export interface RetryOptions {
/** Retries after the first attempt; `0` disables retries. Defaults to 3. */
maxRetries?: number
/** Base of the exponential wait. Defaults to 1000. */
retryDelayInMs?: number
/** Longest wait; a longer service wait hint stops retrying. Defaults to 60000. */
maxRetryDelayInMs?: number
/** Defaults to 408, 429, 500, 502, 503 and 504. Network errors are always retryable. */
retryableStatuses?: number[]
/** Decides whether to retry; `undefined` keeps the default decision. */
shouldRetry?: (context: RetryContext) => boolean | undefined
/** Wait before the next attempt in milliseconds; `undefined` keeps the default wait. */
retryDelay?: (context: RetryContext) => number | undefined
}
export interface RetrySettings extends RetryOptions {
signal?: AbortSignal | null
/** A stream body is consumed by the first attempt, so it is never retried. */
body?: BodyInit | null
}
/**
* Builds the request once without its body, so fetch rejects a malformed URL, method or header
* here instead of on every retry.
*/
export function validatedUrl(input: string | URL, init: RequestInit): string {
return new Request(input, { method: init.method, headers: init.headers }).url
}
/** A stream body is consumed by the first attempt; other bodies can be sent again. */
export function isReplayableBody(body: BodyInit | null | undefined): boolean {
return !(body instanceof ReadableStream)
}
/** Sends one HTTP request, retrying network errors and transient statuses after a wait. */
export async function sendWithRetry(
send: () => Promise<Response>,
{ signal, body, ...options }: RetrySettings = {},
): Promise<Response> {
const maxRetries = isReplayableBody(body) ? (options.maxRetries ?? 3) : 0
const retryDelayInMs = options.retryDelayInMs ?? 1000
const maxRetryDelayInMs = options.maxRetryDelayInMs ?? defaultMaxRetryDelayInMs
const retryableStatuses = options.retryableStatuses ?? defaultRetryableStatuses
const sendAttempt = async (attempt: number): Promise<Response> => {
signal?.throwIfAborted()
let context: RetryContext
let retryable: boolean
try {
const response = await send()
context = { attempt, response, retryAfterInMs: parseRetryAfter(response.headers) }
retryable = retryableStatuses.includes(response.status)
} catch (error) {
signal?.throwIfAborted()
context = { attempt, error }
retryable = true
}
const withinHint = (context.retryAfterInMs ?? 0) <= maxRetryDelayInMs
if (attempt >= maxRetries || !(options.shouldRetry?.(context) ?? (retryable && withinHint))) {
if (context.response !== undefined) {
return context.response
}
throw context.error
}
const delayInMs =
options.retryDelay?.(context) ??
context.retryAfterInMs ??
exponentialDelay(attempt, retryDelayInMs, maxRetryDelayInMs)
await context.response?.body?.cancel()
await wait(Math.max(0, delayInMs), signal)
return await sendAttempt(attempt + 1)
}
return await sendAttempt(0)
}
/** Exponential wait with jitter that keeps it between 80% and 100% of the exponential value. */
export function exponentialDelay(
attempt: number,
retryDelayInMs: number,
maxRetryDelayInMs: number,
): number {
return Math.min(maxRetryDelayInMs, retryDelayInMs * 2 ** attempt) * (0.8 + Math.random() * 0.2)
}
/** The first valid wait hint; a past `Retry-After` date means no wait. */
function parseRetryAfter(headers: Headers): number | undefined {
for (const name of ['retry-after-ms', 'x-ms-retry-after-ms']) {
const milliseconds = parseNonNegative(headers.get(name))
if (milliseconds !== undefined) {
return milliseconds
}
}
const retryAfter = headers.get('retry-after')?.trim()
if (retryAfter === undefined || decimalNumber.test(retryAfter)) {
const seconds = parseNonNegative(retryAfter)
return seconds === undefined ? undefined : seconds * 1000
}
const date = Date.parse(retryAfter)
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now())
}
function parseNonNegative(value: string | null | undefined): number | undefined {
const trimmed = value?.trim()
if (trimmed === undefined || !decimalNumber.test(trimmed)) {
return undefined
}
const number = Number(trimmed)
return number >= 0 ? number : undefined
}
async function wait(delayInMs: number, signal: AbortSignal | null | undefined): Promise<void> {
// The signal can abort while a discarded body is cancelled, before the listener exists.
signal?.throwIfAborted()
const cleanup = new AbortController()
try {
await new Promise<void>((resolve) => {
const timer = setTimeout(resolve, delayInMs)
signal?.addEventListener(
'abort',
() => {
clearTimeout(timer)
resolve()
},
{ signal: cleanup.signal },
)
})
} finally {
cleanup.abort()
}
signal?.throwIfAborted()
}
|