Browse Source

oss走代理

Pchen0 10 hours ago
parent
commit
2e75b58623
1 changed files with 69 additions and 19 deletions
  1. 69 19
      lib/Lepao/Worker.js

+ 69 - 19
lib/Lepao/Worker.js

@@ -21,6 +21,7 @@ const {
 const generateGyrFromPath = require('../../plugin/Lepao/generateGyrFromPath')
 const { syncAccountInfo } = require('./syncAccountInfo')
 const { postLepaoSchool } = require('./lepaoSchoolHttp')
+const QgProxyManager = require('./QgProxyManager')
 const { insertLedgerRecord } = require('./CountLedger')
 
 const Logger = require('../Logger')
@@ -68,6 +69,67 @@ class Worker {
         return new Promise(r => setTimeout(r, ms))
     }
 
+    buildOssBaseClientConfig(sts) {
+        return {
+            bucket: sts.bucket,
+            region: sts.region || 'oss-cn-hangzhou',
+            accessKeyId: sts.AccessKeyId,
+            accessKeySecret: sts.AccessKeySecret,
+            stsToken: sts.SecurityToken,
+            secure: true
+        }
+    }
+
+    buildProxyUrlFromFragment(fragment) {
+        if (!fragment || fragment.proxy === false || !fragment.proxy) return null
+        const { host, port, auth } = fragment.proxy
+        let userPart = ''
+        if (auth && String(auth.username || '').length > 0) {
+            const u = encodeURIComponent(auth.username)
+            const p = encodeURIComponent(auth.password != null ? String(auth.password) : '')
+            userPart = `${u}:${p}@`
+        }
+        return `http://${userPart}${host}:${port}`
+    }
+
+    async createOssClientWithProxy(sts, scene = 'unknown') {
+        const base = this.buildOssBaseClientConfig(sts)
+        try {
+            const proxyEnabled = await QgProxyManager.isOutboundProxyEnabled()
+            if (!proxyEnabled) return { client: new OSS(base), viaProxy: false }
+
+            const frag = await QgProxyManager.getOutboundAxiosFragment({ forceRefresh: false })
+            const proxyUrl = this.buildProxyUrlFromFragment(frag)
+            if (!proxyUrl) return { client: new OSS(base), viaProxy: false }
+
+            this.logger.info(`[lepao.oss] ${scene} 上传出站=HTTP代理 ${frag.proxy.host}:${frag.proxy.port}`)
+            return {
+                client: new OSS({
+                    ...base,
+                    enableProxy: true,
+                    proxy: proxyUrl
+                }),
+                viaProxy: true
+            }
+        } catch (e) {
+            this.logger.warn(`[lepao.oss] ${scene} 代理配置异常,降级直连: ${e.message || e}`)
+            return { client: new OSS(base), viaProxy: false }
+        }
+    }
+
+    async putOssWithFallback(sts, ossPath, content, scene = 'unknown') {
+        const primary = await this.createOssClientWithProxy(sts, scene)
+        try {
+            await primary.client.put(ossPath, content)
+            return
+        } catch (e1) {
+            if (!primary.viaProxy) throw e1
+            this.logger.warn(`[lepao.oss] ${scene} 代理上传失败,回退直连: ${e1.message || e1}`)
+            const directClient = new OSS(this.buildOssBaseClientConfig(sts))
+            await directClient.put(ossPath, content)
+        }
+    }
+
     isRunSuccess(bindResponse) {
         const payload = bindResponse?.data
         if (!bindResponse || bindResponse.status !== 1 || !payload) {
@@ -1123,15 +1185,7 @@ class Worker {
             const boundary = String(Date.now())
             const timestamp = String(Date.now())
             const ossPath = `Public/Upload/file/run_record/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
-            const client = new OSS({
-                bucket: sts.bucket,
-                region: sts.region || 'oss-cn-hangzhou',
-                accessKeyId: sts.AccessKeyId,
-                accessKeySecret: sts.AccessKeySecret,
-                stsToken: sts.SecurityToken,
-                secure: true
-            })
-            await client.put(ossPath, Buffer.from(pathResult, 'utf-8'))
+            await this.putOssWithFallback(sts, ossPath, Buffer.from(pathResult, 'utf-8'), 'run_record')
 
             return { oss_path: ossPath, point_data: point_data }
         })
@@ -1154,16 +1208,12 @@ class Worker {
             const boundary = String(Date.now())
             const timestamp = String(Date.now())
             const ossPath = `Public/Upload/file/run_gyroscope/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
-            const client = new OSS({
-                bucket: sts.bucket,
-                region: sts.region || 'oss-cn-hangzhou',
-                accessKeyId: sts.AccessKeyId,
-                accessKeySecret: sts.AccessKeySecret,
-                stsToken: sts.SecurityToken,
-                secure: true
-            })
-
-            await client.put(ossPath, Buffer.from(JSON.stringify(gyrData), 'utf-8'))
+            await this.putOssWithFallback(
+                sts,
+                ossPath,
+                Buffer.from(JSON.stringify(gyrData), 'utf-8'),
+                'run_gyroscope'
+            )
 
             const data = {
                 uid: req.uid,