112 lines
6.0 KiB
JavaScript
112 lines
6.0 KiB
JavaScript
;(function (global) {
|
|
'use strict'
|
|
|
|
function abortError(message) {
|
|
const error = new Error(message || '操作已取消')
|
|
error.name = 'AbortError'
|
|
error.iwbType = 'cancelled'
|
|
return error
|
|
}
|
|
function classifyStatus(status) {
|
|
if (status === 401) return 'permission'
|
|
if (status === 403) return 'permission'
|
|
if (status === 408 || status === 504) return 'timeout'
|
|
if (status === 409) return 'conflict'
|
|
if (status === 429) return 'quota'
|
|
if (status >= 500) return 'network'
|
|
if (status >= 400) return 'validation'
|
|
return 'unknown'
|
|
}
|
|
function isRetryable(error) {
|
|
return !!(error && ['network', 'timeout', 'unavailable', 'conflict'].indexOf(error.iwbType) >= 0)
|
|
}
|
|
function wait(ms, signal, timers) {
|
|
if (signal && signal.aborted) return Promise.reject(abortError())
|
|
const set = timers && timers.setTimeout || global.setTimeout
|
|
const clear = timers && timers.clearTimeout || global.clearTimeout
|
|
if (typeof set !== 'function') return Promise.resolve()
|
|
return new Promise((resolve, reject) => {
|
|
let done = false
|
|
let timer = set(() => { done = true; if (signal) signal.removeEventListener('abort', onAbort); resolve() }, Math.max(0, Number(ms) || 0))
|
|
const onAbort = () => { if (done) return; done = true; if (typeof clear === 'function') clear(timer); if (signal) signal.removeEventListener('abort', onAbort); reject(abortError()) }
|
|
if (signal) signal.addEventListener('abort', onAbort, { once: true })
|
|
})
|
|
}
|
|
function metricAdd(metrics, name, amount) { if (metrics && typeof metrics.add === 'function') metrics.add(name, amount === undefined ? 1 : amount) }
|
|
function metricObserve(metrics, startedAt) { if (metrics && typeof metrics.observeRequest === 'function') metrics.observeRequest(Date.now() - startedAt) }
|
|
function request(input, options) {
|
|
const opt = options || {}
|
|
const fetcher = opt.fetch || global.fetch
|
|
if (typeof fetcher !== 'function') return Promise.reject(new Error('当前环境不支持网络请求'))
|
|
const timeoutMs = Math.max(0, Number(opt.timeoutMs) || 240000)
|
|
const controller = opt.controller || (typeof global.AbortController === 'function' ? new global.AbortController() : null)
|
|
const external = opt.signal
|
|
const timerSet = opt.setTimeout || global.setTimeout
|
|
const timerClear = opt.clearTimeout || global.clearTimeout
|
|
let timer = null
|
|
let timedOut = false
|
|
let timeoutNotified = false
|
|
const abortOnTimeout = opt.abortOnTimeout !== false
|
|
const onSoftTimeout = typeof opt.onSoftTimeout === 'function' ? opt.onSoftTimeout : null
|
|
const metrics = opt.metrics
|
|
const startedAt = Date.now()
|
|
metricAdd(metrics, 'requestCount')
|
|
const onAbort = () => { if (controller) controller.abort() }
|
|
if (external) {
|
|
if (external.aborted) { metricAdd(metrics, 'cancelCount'); return Promise.reject(abortError()) }
|
|
external.addEventListener('abort', onAbort, { once: true })
|
|
}
|
|
if (controller && typeof timerSet === 'function') timer = timerSet(() => {
|
|
timedOut = true
|
|
if (onSoftTimeout && !timeoutNotified) {
|
|
timeoutNotified = true
|
|
try { onSoftTimeout({ timeoutMs }) } catch (e) {
|
|
// 软超时通知回调抛错:超时本身仍会生效(下面照常 abort),但**用户没收到提示** ⇒ 留痕。
|
|
try {
|
|
const cl = global.IWBCrashLog
|
|
if (cl && typeof cl.record === 'function') cl.record('soft-timeout-notify-error', { scope: 'runtime-fetch', message: String((e && e.message) || e) })
|
|
} catch (err) { /* ignore */ }
|
|
}
|
|
}
|
|
if (abortOnTimeout) controller.abort()
|
|
}, timeoutMs)
|
|
const init = Object.assign({}, opt.init || {}, controller ? { signal: controller.signal } : {})
|
|
return Promise.resolve().then(() => fetcher(input, init)).then((response) => {
|
|
metricAdd(metrics, response && response.ok ? 'requestSuccessCount' : 'requestFailureCount')
|
|
return response
|
|
}).catch((error) => {
|
|
metricAdd(metrics, 'requestFailureCount')
|
|
if (external && external.aborted) { metricAdd(metrics, 'cancelCount'); throw abortError() }
|
|
if ((timedOut && abortOnTimeout) || (error && error.name === 'AbortError')) {
|
|
metricAdd(metrics, 'timeoutCount'); const timeout = new Error('请求超时'); timeout.name = 'TimeoutError'; timeout.iwbType = 'timeout'; throw timeout
|
|
}
|
|
const network = new Error('网络连接中断'); network.iwbType = 'network'; throw network
|
|
}).finally(() => {
|
|
metricObserve(metrics, startedAt)
|
|
if (timer !== null && typeof timerClear === 'function') timerClear(timer)
|
|
// 移除监听器失败:请求已结束,监听器随之失效 ⇒ 无害,仅注释说明
|
|
if (external) { try { external.removeEventListener('abort', onAbort) } catch (e) { /* 清理失败无害:请求已结束 */ } }
|
|
})
|
|
}
|
|
async function run(input, options) {
|
|
const opt = options || {}
|
|
const attempts = Math.max(1, Number(opt.attempts) || 1)
|
|
const baseDelay = Math.max(0, Number(opt.baseDelay) || 0)
|
|
let last = null
|
|
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
try {
|
|
const response = await request(input, opt)
|
|
if (!response || response.ok || !opt.retryHttp || !isRetryable(Object.assign(new Error('HTTP ' + response.status), { iwbType: classifyStatus(response.status) })) || attempt >= attempts - 1) return response
|
|
last = Object.assign(new Error('HTTP ' + response.status), { status: response.status, iwbType: classifyStatus(response.status) })
|
|
metricAdd(opt.metrics, 'retryCount')
|
|
} catch (error) {
|
|
last = error
|
|
if ((error && error.iwbType === 'cancelled') || attempt >= attempts - 1 || !isRetryable(error)) throw error
|
|
}
|
|
await wait(baseDelay * Math.pow(2, attempt), opt.signal, { setTimeout: opt.setTimeout || global.setTimeout, clearTimeout: opt.clearTimeout || global.clearTimeout })
|
|
}
|
|
throw last || new Error('请求失败')
|
|
}
|
|
global.IWBRuntimeFetch = { abortError, classifyStatus, isRetryable, request, run }
|
|
})(typeof window !== 'undefined' ? window : globalThis)
|