lepaoSchoolHttp.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. const axios = require('axios')
  2. const HttpsProxyAgent = require('https-proxy-agent')
  3. const QgProxyManager = require('./QgProxyManager')
  4. function sleep(ms) {
  5. return new Promise(r => setTimeout(r, ms))
  6. }
  7. /** 外层再包几轮:应对瞬时 NO_AVAILABLE_CHANNEL、网络抖动(青果函数内部已短时持锁 backoff,此处不宜再大) */
  8. async function getOutboundWithBackoff(qgOpts, rounds = 2) {
  9. let lastErr
  10. for (let i = 0; i < rounds; i++) {
  11. try {
  12. if (i > 0) await sleep(380 * i * i)
  13. return await QgProxyManager.getOutboundAxiosFragment(qgOpts)
  14. } catch (e) {
  15. lastErr = e
  16. }
  17. }
  18. throw lastErr
  19. }
  20. /**
  21. * Axios 对「HTTPS 目标 + 内置 proxy」在部分环境下会引发 ERR_FR_TOO_MANY_REDIRECTS,
  22. * 改用 HttpsProxyAgent 走 CONNECT 隧道。
  23. */
  24. function buildAxiosOutboundConfig(fragment) {
  25. if (!fragment || fragment.proxy === false || !fragment.proxy) {
  26. return { proxy: false }
  27. }
  28. const { host, port, auth } = fragment.proxy
  29. let userPart = ''
  30. if (auth && String(auth.username || '').length > 0) {
  31. const u = encodeURIComponent(auth.username)
  32. const p = encodeURIComponent(auth.password != null ? String(auth.password) : '')
  33. userPart = `${u}:${p}@`
  34. }
  35. const proxyUrl = `http://${userPart}${host}:${port}`
  36. const rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0'
  37. return {
  38. proxy: false,
  39. httpsAgent: new HttpsProxyAgent(proxyUrl, { rejectUnauthorized })
  40. }
  41. }
  42. function debugProxyEnabled() {
  43. return String(process.env.LEPAO_DEBUG_PROXY || '').trim() === '1'
  44. }
  45. function debugProxyAxiosFragment() {
  46. const host = process.env.LEPAO_DEBUG_PROXY_HOST || '127.0.0.1'
  47. const port = Number(process.env.LEPAO_DEBUG_PROXY_PORT || 9000)
  48. return {
  49. proxy: {
  50. host,
  51. port,
  52. protocol: 'http'
  53. }
  54. }
  55. }
  56. function briefUrlPath(fullUrl) {
  57. try {
  58. const u = new URL(fullUrl)
  59. return `${u.pathname}${u.search}`
  60. } catch {
  61. return fullUrl
  62. }
  63. }
  64. /** 与 Worker 日志对齐:先 traceId(如 1778232257819_dfpcft),再模块名,可选 MQ 任务 id */
  65. function lepaoHttpLogLabel(traceId, mqTaskId) {
  66. let s = ''
  67. if (traceId) s += `[${traceId}] `
  68. s += '[lepaoSchoolHttp]'
  69. if (mqTaskId) s += ` [${mqTaskId}]`
  70. return s
  71. }
  72. function isQgProxyEligibleFailure(err) {
  73. if (!err) return false
  74. const status = err.response?.status
  75. if (status === 407) return true
  76. if (status === 408) return true
  77. if (status === 500) return true
  78. if (status === 502 || status === 503 || status === 504) return true
  79. if (
  80. err.code &&
  81. ['ECONNRESET', 'ECONNABORTED', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'EPROTO', 'ERR_FR_TOO_MANY_REDIRECTS'].includes(
  82. err.code
  83. )
  84. ) {
  85. return true
  86. }
  87. if (err.isAxiosError && !err.response) return true
  88. const msg = (err.message || '').toLowerCase()
  89. if (msg.includes('timeout') || msg.includes('socket') || msg.includes('network')) return true
  90. return false
  91. }
  92. function summarizeAxiosError(err) {
  93. if (!err) return {}
  94. return {
  95. message: err.message,
  96. code: err.code,
  97. status: err.response?.status,
  98. isAxiosError: err.isAxiosError
  99. }
  100. }
  101. /** CONNECT Tunnel 后与目标站 TLS 握手前被断开——换 IP 往往无效,应少打 /get、尽快直连 */
  102. function isProxyTlsHandshakeReset(err) {
  103. if (!err) return false
  104. const code = err.code
  105. if (code !== 'ECONNRESET' && code !== 'ECONNABORTED') return false
  106. const msg = String(err.message || '')
  107. return /tls|secure\s+tls|handshake/i.test(msg)
  108. }
  109. /**
  110. * @param {*} logger Worker logger 或 null
  111. * @param {{ skipQgSnapshot?: boolean }} opts 为 true 时仅用 axios 配置的 host:port(如 Charles)
  112. */
  113. async function logSchoolOutbound(logger, phase, url, axiosMerge, opts = {}) {
  114. if (!logger?.info) return
  115. const path = briefUrlPath(url)
  116. const label = lepaoHttpLogLabel(opts.traceId, opts.mqTaskId)
  117. if (!axiosMerge || axiosMerge.proxy === false || !axiosMerge.proxy) {
  118. logger.info(`${label} ${phase} POST 出站=直连 path=${path}`)
  119. return
  120. }
  121. const conn = `${axiosMerge.proxy.host}:${axiosMerge.proxy.port}`
  122. if (opts.skipQgSnapshot) {
  123. logger.info(
  124. `${label} ${phase} POST 出站=调试HTTP代理(非青果) 连接=${conn} path=${path}`
  125. )
  126. return
  127. }
  128. const snap = await QgProxyManager.getCachedParsed()
  129. const serverRecord = snap?.server ?? conn
  130. const egress = snap?.proxyIp ?? '(暂无 proxy_ip)'
  131. const dl = snap?.deadline ?? '—'
  132. logger.info(
  133. `${label} ${phase} POST 出站=HTTP代理 节点server=${serverRecord} 连接${conn} 出口IP(proxy_ip)=${egress} deadline=${dl} path=${path}`
  134. )
  135. }
  136. /**
  137. * 对 lepao.ctbu.edu.cn 的 POST:优先隧道代理;失败快速直连并记日志(隧道池出口由服务商后台切换)。
  138. */
  139. async function postLepaoSchool(url, data, options = {}) {
  140. const {
  141. headers = {},
  142. timeout = 15000,
  143. logger = null,
  144. outboundMode = 'auto',
  145. mqTaskId = null,
  146. traceId = null
  147. } = options
  148. const logLabel = () => lepaoHttpLogLabel(traceId, mqTaskId)
  149. const doPost = async (qgProxyFragment, requestTimeout = timeout) => {
  150. const outbound = buildAxiosOutboundConfig(qgProxyFragment)
  151. return axios.post(url, data, {
  152. headers,
  153. timeout: requestTimeout,
  154. ...outbound
  155. })
  156. }
  157. // 强制直连:策略 A 用(任务内固定出站,禁止中途切换)
  158. if (outboundMode === 'direct') {
  159. await logSchoolOutbound(logger, '(强制直连)', url, { proxy: false }, { mqTaskId, traceId })
  160. return doPost({ proxy: false })
  161. }
  162. if (debugProxyEnabled()) {
  163. const dbg = debugProxyAxiosFragment()
  164. await logSchoolOutbound(logger, 'Charles调试代理', url, dbg, {
  165. skipQgSnapshot: true,
  166. mqTaskId,
  167. traceId
  168. })
  169. logger?.info?.(`${logLabel()} 使用本地调试代理 LEPAO_DEBUG_PROXY`)
  170. return doPost(dbg)
  171. }
  172. const qgOn = await QgProxyManager.isOutboundProxyEnabled()
  173. if (!qgOn) {
  174. await logSchoolOutbound(logger, '(青果出站未启用)', url, { proxy: false }, { mqTaskId, traceId })
  175. return doPost({ proxy: false })
  176. }
  177. let frag
  178. try {
  179. frag = await getOutboundWithBackoff({ forceRefresh: false }, 2)
  180. } catch (e0) {
  181. if (outboundMode === 'proxy') {
  182. const err = new Error(`代理模式提取失败: ${e0.message || e0}`)
  183. err.code = 'PROXY_REQUIRED_EXTRACT_FAILED'
  184. err.retryable = true
  185. throw err
  186. }
  187. logger?.error?.(`${logLabel()} 青果提取多次重试仍失败,改直连: ${e0.message || e0}`)
  188. await logSchoolOutbound(logger, '(青果提取异常→直连)', url, { proxy: false }, { mqTaskId, traceId })
  189. await QgProxyManager.recordFallbackDirect({
  190. reason: 'qg_extract_error',
  191. mq_task_id: mqTaskId,
  192. trace_id: traceId,
  193. ...summarizeAxiosError(e0)
  194. })
  195. return doPost({ proxy: false })
  196. }
  197. if (frag.proxy === false) {
  198. try {
  199. await sleep(400)
  200. frag = await getOutboundWithBackoff({ forceRefresh: true }, 2)
  201. } catch {
  202. /* 保持 frag 原状 */
  203. }
  204. }
  205. if (frag.proxy === false) {
  206. logger?.warn?.(`${logLabel()} 无可用青果节点,对学校 POST 将直连`)
  207. if (outboundMode === 'proxy') {
  208. const err = new Error('代理模式无可用节点')
  209. err.code = 'PROXY_REQUIRED_NO_NODE'
  210. err.retryable = true
  211. throw err
  212. }
  213. await logSchoolOutbound(logger, '(无缓存节点→直连)', url, { proxy: false }, { mqTaskId, traceId })
  214. await QgProxyManager.recordFallbackDirect({
  215. reason: 'no_proxy_available',
  216. mq_task_id: mqTaskId,
  217. trace_id: traceId
  218. })
  219. return doPost({ proxy: false })
  220. }
  221. await logSchoolOutbound(logger, '首次请求', url, frag, { mqTaskId, traceId })
  222. try {
  223. const proxyFirstTimeoutMs = 20000
  224. return await doPost(frag, proxyFirstTimeoutMs)
  225. } catch (e1) {
  226. if (outboundMode === 'proxy') {
  227. const err = new Error(`代理模式请求失败: ${e1.message || e1}`)
  228. err.code = 'PROXY_REQUIRED_REQUEST_FAILED'
  229. err.retryable = true
  230. throw err
  231. }
  232. if (!isQgProxyEligibleFailure(e1)) throw e1
  233. logger?.warn?.(
  234. `${logLabel()} 经代理首次请求失败,将直接回退直连。err=${e1.message || e1} ${JSON.stringify(
  235. summarizeAxiosError(e1)
  236. )}`
  237. )
  238. const tls1 = isProxyTlsHandshakeReset(e1)
  239. if (tls1) {
  240. logger?.warn?.(
  241. `${logLabel()} TLS 握手前经代理断开,隧道池模式直接直连(由服务商后台自动切换出口)`
  242. )
  243. await logSchoolOutbound(logger, '(TLS隧道异常→直连)', url, { proxy: false }, { mqTaskId, traceId })
  244. await QgProxyManager.recordFallbackDirect({
  245. reason: 'tls_prefinish_reset_direct',
  246. path: briefUrlPath(url),
  247. mq_task_id: mqTaskId,
  248. trace_id: traceId,
  249. ...summarizeAxiosError(e1)
  250. })
  251. return doPost({ proxy: false })
  252. }
  253. await logSchoolOutbound(logger, '(代理失败→直连)', url, { proxy: false }, { mqTaskId, traceId })
  254. await QgProxyManager.recordFallbackDirect({
  255. reason: 'proxy_post_failed_then_direct',
  256. path: briefUrlPath(url),
  257. mq_task_id: mqTaskId,
  258. trace_id: traceId,
  259. ...summarizeAxiosError(e1)
  260. })
  261. return doPost({ proxy: false })
  262. }
  263. }
  264. module.exports = {
  265. postLepaoSchool,
  266. isQgProxyEligibleFailure,
  267. debugProxyEnabled,
  268. debugProxyAxiosFragment
  269. }