relay.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. package controller
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "log"
  8. "net/http"
  9. "strings"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-api/constant"
  12. "github.com/QuantumNous/new-api/dto"
  13. "github.com/QuantumNous/new-api/logger"
  14. "github.com/QuantumNous/new-api/middleware"
  15. "github.com/QuantumNous/new-api/model"
  16. "github.com/QuantumNous/new-api/relay"
  17. relaycommon "github.com/QuantumNous/new-api/relay/common"
  18. relayconstant "github.com/QuantumNous/new-api/relay/constant"
  19. "github.com/QuantumNous/new-api/relay/helper"
  20. "github.com/QuantumNous/new-api/service"
  21. "github.com/QuantumNous/new-api/setting"
  22. "github.com/QuantumNous/new-api/setting/operation_setting"
  23. "github.com/QuantumNous/new-api/types"
  24. "github.com/bytedance/gopkg/util/gopool"
  25. "github.com/gin-gonic/gin"
  26. "github.com/gorilla/websocket"
  27. )
  28. func relayHandler(c *gin.Context, info *relaycommon.RelayInfo) *types.NewAPIError {
  29. var err *types.NewAPIError
  30. switch info.RelayMode {
  31. case relayconstant.RelayModeImagesGenerations, relayconstant.RelayModeImagesEdits:
  32. err = relay.ImageHelper(c, info)
  33. case relayconstant.RelayModeAudioSpeech:
  34. fallthrough
  35. case relayconstant.RelayModeAudioTranslation:
  36. fallthrough
  37. case relayconstant.RelayModeAudioTranscription:
  38. err = relay.AudioHelper(c, info)
  39. case relayconstant.RelayModeRerank:
  40. err = relay.RerankHelper(c, info)
  41. case relayconstant.RelayModeEmbeddings:
  42. err = relay.EmbeddingHelper(c, info)
  43. case relayconstant.RelayModeResponses, relayconstant.RelayModeResponsesCompact:
  44. err = relay.ResponsesHelper(c, info)
  45. default:
  46. err = relay.TextHelper(c, info)
  47. }
  48. return err
  49. }
  50. func geminiRelayHandler(c *gin.Context, info *relaycommon.RelayInfo) *types.NewAPIError {
  51. var err *types.NewAPIError
  52. if strings.Contains(c.Request.URL.Path, "embed") {
  53. err = relay.GeminiEmbeddingHandler(c, info)
  54. } else {
  55. err = relay.GeminiHelper(c, info)
  56. }
  57. return err
  58. }
  59. func Relay(c *gin.Context, relayFormat types.RelayFormat) {
  60. requestId := c.GetString(common.RequestIdKey)
  61. //group := common.GetContextKeyString(c, constant.ContextKeyUsingGroup)
  62. //originalModel := common.GetContextKeyString(c, constant.ContextKeyOriginalModel)
  63. var (
  64. newAPIError *types.NewAPIError
  65. ws *websocket.Conn
  66. )
  67. if relayFormat == types.RelayFormatOpenAIRealtime {
  68. var err error
  69. ws, err = upgrader.Upgrade(c.Writer, c.Request, nil)
  70. if err != nil {
  71. helper.WssError(c, ws, types.NewError(err, types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry()).ToOpenAIError())
  72. return
  73. }
  74. defer ws.Close()
  75. }
  76. defer func() {
  77. if newAPIError != nil {
  78. logger.LogError(c, fmt.Sprintf("relay error: %s", newAPIError.Error()))
  79. newAPIError.SetMessage(common.MessageWithRequestId(newAPIError.Error(), requestId))
  80. switch relayFormat {
  81. case types.RelayFormatOpenAIRealtime:
  82. helper.WssError(c, ws, newAPIError.ToOpenAIError())
  83. case types.RelayFormatClaude:
  84. c.JSON(newAPIError.StatusCode, gin.H{
  85. "type": "error",
  86. "error": newAPIError.ToClaudeError(),
  87. })
  88. default:
  89. c.JSON(newAPIError.StatusCode, gin.H{
  90. "error": newAPIError.ToOpenAIError(),
  91. })
  92. }
  93. }
  94. }()
  95. request, err := helper.GetAndValidateRequest(c, relayFormat)
  96. if err != nil {
  97. // Map "request body too large" to 413 so clients can handle it correctly
  98. if common.IsRequestBodyTooLargeError(err) || errors.Is(err, common.ErrRequestBodyTooLarge) {
  99. newAPIError = types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusRequestEntityTooLarge, types.ErrOptionWithSkipRetry())
  100. } else {
  101. newAPIError = types.NewError(err, types.ErrorCodeInvalidRequest)
  102. }
  103. return
  104. }
  105. relayInfo, err := relaycommon.GenRelayInfo(c, relayFormat, request, ws)
  106. if err != nil {
  107. newAPIError = types.NewError(err, types.ErrorCodeGenRelayInfoFailed)
  108. return
  109. }
  110. needSensitiveCheck := setting.ShouldCheckPromptSensitive()
  111. needCountToken := constant.CountToken
  112. // Avoid building huge CombineText (strings.Join) when token counting and sensitive check are both disabled.
  113. var meta *types.TokenCountMeta
  114. if needSensitiveCheck || needCountToken {
  115. meta = request.GetTokenCountMeta()
  116. } else {
  117. meta = fastTokenCountMetaForPricing(request)
  118. }
  119. if needSensitiveCheck && meta != nil {
  120. contains, words := service.CheckSensitiveText(meta.CombineText)
  121. if contains {
  122. logger.LogWarn(c, fmt.Sprintf("user sensitive words detected: %s", strings.Join(words, ", ")))
  123. newAPIError = types.NewError(err, types.ErrorCodeSensitiveWordsDetected)
  124. return
  125. }
  126. }
  127. tokens, err := service.EstimateRequestToken(c, meta, relayInfo)
  128. if err != nil {
  129. newAPIError = types.NewError(err, types.ErrorCodeCountTokenFailed)
  130. return
  131. }
  132. relayInfo.SetEstimatePromptTokens(tokens)
  133. priceData, err := helper.ModelPriceHelper(c, relayInfo, tokens, meta)
  134. if err != nil {
  135. newAPIError = types.NewError(err, types.ErrorCodeModelPriceError)
  136. return
  137. }
  138. // common.SetContextKey(c, constant.ContextKeyTokenCountMeta, meta)
  139. if priceData.FreeModel {
  140. logger.LogInfo(c, fmt.Sprintf("模型 %s 免费,跳过预扣费", relayInfo.OriginModelName))
  141. } else {
  142. newAPIError = service.PreConsumeQuota(c, priceData.QuotaToPreConsume, relayInfo)
  143. if newAPIError != nil {
  144. return
  145. }
  146. }
  147. defer func() {
  148. // Only return quota if downstream failed and quota was actually pre-consumed
  149. if newAPIError != nil {
  150. newAPIError = service.NormalizeViolationFeeError(newAPIError)
  151. if relayInfo.FinalPreConsumedQuota != 0 {
  152. service.ReturnPreConsumedQuota(c, relayInfo)
  153. }
  154. service.ChargeViolationFeeIfNeeded(c, relayInfo, newAPIError)
  155. }
  156. }()
  157. retryParam := &service.RetryParam{
  158. Ctx: c,
  159. TokenGroup: relayInfo.TokenGroup,
  160. ModelName: relayInfo.OriginModelName,
  161. Retry: common.GetPointer(0),
  162. }
  163. for ; retryParam.GetRetry() <= common.RetryTimes; retryParam.IncreaseRetry() {
  164. channel, channelErr := getChannel(c, relayInfo, retryParam)
  165. if channelErr != nil {
  166. logger.LogError(c, channelErr.Error())
  167. newAPIError = channelErr
  168. break
  169. }
  170. addUsedChannel(c, channel.Id)
  171. requestBody, bodyErr := common.GetRequestBody(c)
  172. if bodyErr != nil {
  173. // Ensure consistent 413 for oversized bodies even when error occurs later (e.g., retry path)
  174. if common.IsRequestBodyTooLargeError(bodyErr) || errors.Is(bodyErr, common.ErrRequestBodyTooLarge) {
  175. newAPIError = types.NewErrorWithStatusCode(bodyErr, types.ErrorCodeReadRequestBodyFailed, http.StatusRequestEntityTooLarge, types.ErrOptionWithSkipRetry())
  176. } else {
  177. newAPIError = types.NewErrorWithStatusCode(bodyErr, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
  178. }
  179. break
  180. }
  181. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  182. switch relayFormat {
  183. case types.RelayFormatOpenAIRealtime:
  184. newAPIError = relay.WssHelper(c, relayInfo)
  185. case types.RelayFormatClaude:
  186. newAPIError = relay.ClaudeHelper(c, relayInfo)
  187. case types.RelayFormatGemini:
  188. newAPIError = geminiRelayHandler(c, relayInfo)
  189. default:
  190. newAPIError = relayHandler(c, relayInfo)
  191. }
  192. if newAPIError == nil {
  193. return
  194. }
  195. newAPIError = service.NormalizeViolationFeeError(newAPIError)
  196. processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError)
  197. if !shouldRetry(c, newAPIError, common.RetryTimes-retryParam.GetRetry()) {
  198. break
  199. }
  200. }
  201. useChannel := c.GetStringSlice("use_channel")
  202. if len(useChannel) > 1 {
  203. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  204. logger.LogInfo(c, retryLogStr)
  205. }
  206. }
  207. var upgrader = websocket.Upgrader{
  208. Subprotocols: []string{"realtime"}, // WS 握手支持的协议,如果有使用 Sec-WebSocket-Protocol,则必须在此声明对应的 Protocol TODO add other protocol
  209. CheckOrigin: func(r *http.Request) bool {
  210. return true // 允许跨域
  211. },
  212. }
  213. func addUsedChannel(c *gin.Context, channelId int) {
  214. useChannel := c.GetStringSlice("use_channel")
  215. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  216. c.Set("use_channel", useChannel)
  217. }
  218. func fastTokenCountMetaForPricing(request dto.Request) *types.TokenCountMeta {
  219. if request == nil {
  220. return &types.TokenCountMeta{}
  221. }
  222. meta := &types.TokenCountMeta{
  223. TokenType: types.TokenTypeTokenizer,
  224. }
  225. switch r := request.(type) {
  226. case *dto.GeneralOpenAIRequest:
  227. if r.MaxCompletionTokens > r.MaxTokens {
  228. meta.MaxTokens = int(r.MaxCompletionTokens)
  229. } else {
  230. meta.MaxTokens = int(r.MaxTokens)
  231. }
  232. case *dto.OpenAIResponsesRequest:
  233. meta.MaxTokens = int(r.MaxOutputTokens)
  234. case *dto.ClaudeRequest:
  235. meta.MaxTokens = int(r.MaxTokens)
  236. case *dto.ImageRequest:
  237. // Pricing for image requests depends on ImagePriceRatio; safe to compute even when CountToken is disabled.
  238. return r.GetTokenCountMeta()
  239. default:
  240. // Best-effort: leave CombineText empty to avoid large allocations.
  241. }
  242. return meta
  243. }
  244. func getChannel(c *gin.Context, info *relaycommon.RelayInfo, retryParam *service.RetryParam) (*model.Channel, *types.NewAPIError) {
  245. if info.ChannelMeta == nil {
  246. autoBan := c.GetBool("auto_ban")
  247. autoBanInt := 1
  248. if !autoBan {
  249. autoBanInt = 0
  250. }
  251. return &model.Channel{
  252. Id: c.GetInt("channel_id"),
  253. Type: c.GetInt("channel_type"),
  254. Name: c.GetString("channel_name"),
  255. AutoBan: &autoBanInt,
  256. }, nil
  257. }
  258. channel, selectGroup, err := service.CacheGetRandomSatisfiedChannel(retryParam)
  259. info.PriceData.GroupRatioInfo = helper.HandleGroupRatio(c, info)
  260. if err != nil {
  261. return nil, types.NewError(fmt.Errorf("获取分组 %s 下模型 %s 的可用渠道失败(retry): %s", selectGroup, info.OriginModelName, err.Error()), types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
  262. }
  263. if channel == nil {
  264. return nil, types.NewError(fmt.Errorf("分组 %s 下模型 %s 的可用渠道不存在(retry)", selectGroup, info.OriginModelName), types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
  265. }
  266. newAPIError := middleware.SetupContextForSelectedChannel(c, channel, info.OriginModelName)
  267. if newAPIError != nil {
  268. return nil, newAPIError
  269. }
  270. return channel, nil
  271. }
  272. func shouldRetry(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool {
  273. if openaiErr == nil {
  274. return false
  275. }
  276. if types.IsChannelError(openaiErr) {
  277. return true
  278. }
  279. if types.IsSkipRetryError(openaiErr) {
  280. return false
  281. }
  282. if retryTimes <= 0 {
  283. return false
  284. }
  285. if _, ok := c.Get("specific_channel_id"); ok {
  286. return false
  287. }
  288. code := openaiErr.StatusCode
  289. if code >= 200 && code < 300 {
  290. return false
  291. }
  292. if code < 100 || code > 599 {
  293. return true
  294. }
  295. return operation_setting.ShouldRetryByStatusCode(code)
  296. }
  297. func processChannelError(c *gin.Context, channelError types.ChannelError, err *types.NewAPIError) {
  298. logger.LogError(c, fmt.Sprintf("channel error (channel #%d, status code: %d): %s", channelError.ChannelId, err.StatusCode, err.Error()))
  299. // 不要使用context获取渠道信息,异步处理时可能会出现渠道信息不一致的情况
  300. // do not use context to get channel info, there may be inconsistent channel info when processing asynchronously
  301. if service.ShouldDisableChannel(channelError.ChannelType, err) && channelError.AutoBan {
  302. gopool.Go(func() {
  303. service.DisableChannel(channelError, err.ErrorWithStatusCode())
  304. })
  305. }
  306. if constant.ErrorLogEnabled && types.IsRecordErrorLog(err) {
  307. // 保存错误日志到mysql中
  308. userId := c.GetInt("id")
  309. tokenName := c.GetString("token_name")
  310. modelName := c.GetString("original_model")
  311. tokenId := c.GetInt("token_id")
  312. userGroup := c.GetString("group")
  313. channelId := c.GetInt("channel_id")
  314. other := make(map[string]interface{})
  315. if c.Request != nil && c.Request.URL != nil {
  316. other["request_path"] = c.Request.URL.Path
  317. }
  318. other["error_type"] = err.GetErrorType()
  319. other["error_code"] = err.GetErrorCode()
  320. other["status_code"] = err.StatusCode
  321. other["channel_id"] = channelId
  322. other["channel_name"] = c.GetString("channel_name")
  323. other["channel_type"] = c.GetInt("channel_type")
  324. adminInfo := make(map[string]interface{})
  325. adminInfo["use_channel"] = c.GetStringSlice("use_channel")
  326. isMultiKey := common.GetContextKeyBool(c, constant.ContextKeyChannelIsMultiKey)
  327. if isMultiKey {
  328. adminInfo["is_multi_key"] = true
  329. adminInfo["multi_key_index"] = common.GetContextKeyInt(c, constant.ContextKeyChannelMultiKeyIndex)
  330. }
  331. service.AppendChannelAffinityAdminInfo(c, adminInfo)
  332. other["admin_info"] = adminInfo
  333. model.RecordErrorLog(c, userId, channelId, modelName, tokenName, err.MaskSensitiveErrorWithStatusCode(), tokenId, 0, false, userGroup, other)
  334. }
  335. }
  336. func RelayMidjourney(c *gin.Context) {
  337. relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatMjProxy, nil, nil)
  338. if err != nil {
  339. c.JSON(http.StatusInternalServerError, gin.H{
  340. "description": fmt.Sprintf("failed to generate relay info: %s", err.Error()),
  341. "type": "upstream_error",
  342. "code": 4,
  343. })
  344. return
  345. }
  346. var mjErr *dto.MidjourneyResponse
  347. switch relayInfo.RelayMode {
  348. case relayconstant.RelayModeMidjourneyNotify:
  349. mjErr = relay.RelayMidjourneyNotify(c)
  350. case relayconstant.RelayModeMidjourneyTaskFetch, relayconstant.RelayModeMidjourneyTaskFetchByCondition:
  351. mjErr = relay.RelayMidjourneyTask(c, relayInfo.RelayMode)
  352. case relayconstant.RelayModeMidjourneyTaskImageSeed:
  353. mjErr = relay.RelayMidjourneyTaskImageSeed(c)
  354. case relayconstant.RelayModeSwapFace:
  355. mjErr = relay.RelaySwapFace(c, relayInfo)
  356. default:
  357. mjErr = relay.RelayMidjourneySubmit(c, relayInfo)
  358. }
  359. //err = relayMidjourneySubmit(c, relayMode)
  360. log.Println(mjErr)
  361. if mjErr != nil {
  362. statusCode := http.StatusBadRequest
  363. if mjErr.Code == 30 {
  364. mjErr.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  365. statusCode = http.StatusTooManyRequests
  366. }
  367. c.JSON(statusCode, gin.H{
  368. "description": fmt.Sprintf("%s %s", mjErr.Description, mjErr.Result),
  369. "type": "upstream_error",
  370. "code": mjErr.Code,
  371. })
  372. channelId := c.GetInt("channel_id")
  373. logger.LogError(c, fmt.Sprintf("relay error (channel #%d, status code %d): %s", channelId, statusCode, fmt.Sprintf("%s %s", mjErr.Description, mjErr.Result)))
  374. }
  375. }
  376. func RelayNotImplemented(c *gin.Context) {
  377. err := types.OpenAIError{
  378. Message: "API not implemented",
  379. Type: "new_api_error",
  380. Param: "",
  381. Code: "api_not_implemented",
  382. }
  383. c.JSON(http.StatusNotImplemented, gin.H{
  384. "error": err,
  385. })
  386. }
  387. func RelayNotFound(c *gin.Context) {
  388. err := types.OpenAIError{
  389. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  390. Type: "invalid_request_error",
  391. Param: "",
  392. Code: "",
  393. }
  394. c.JSON(http.StatusNotFound, gin.H{
  395. "error": err,
  396. })
  397. }
  398. func RelayTask(c *gin.Context) {
  399. retryTimes := common.RetryTimes
  400. channelId := c.GetInt("channel_id")
  401. c.Set("use_channel", []string{fmt.Sprintf("%d", channelId)})
  402. relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatTask, nil, nil)
  403. if err != nil {
  404. return
  405. }
  406. taskErr := taskRelayHandler(c, relayInfo)
  407. if taskErr == nil {
  408. retryTimes = 0
  409. }
  410. retryParam := &service.RetryParam{
  411. Ctx: c,
  412. TokenGroup: relayInfo.TokenGroup,
  413. ModelName: relayInfo.OriginModelName,
  414. Retry: common.GetPointer(0),
  415. }
  416. for ; shouldRetryTaskRelay(c, channelId, taskErr, retryTimes) && retryParam.GetRetry() < retryTimes; retryParam.IncreaseRetry() {
  417. channel, newAPIError := getChannel(c, relayInfo, retryParam)
  418. if newAPIError != nil {
  419. logger.LogError(c, fmt.Sprintf("CacheGetRandomSatisfiedChannel failed: %s", newAPIError.Error()))
  420. taskErr = service.TaskErrorWrapperLocal(newAPIError.Err, "get_channel_failed", http.StatusInternalServerError)
  421. break
  422. }
  423. channelId = channel.Id
  424. useChannel := c.GetStringSlice("use_channel")
  425. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  426. c.Set("use_channel", useChannel)
  427. logger.LogInfo(c, fmt.Sprintf("using channel #%d to retry (remain times %d)", channel.Id, retryParam.GetRetry()))
  428. //middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  429. requestBody, err := common.GetRequestBody(c)
  430. if err != nil {
  431. if common.IsRequestBodyTooLargeError(err) || errors.Is(err, common.ErrRequestBodyTooLarge) {
  432. taskErr = service.TaskErrorWrapperLocal(err, "read_request_body_failed", http.StatusRequestEntityTooLarge)
  433. } else {
  434. taskErr = service.TaskErrorWrapperLocal(err, "read_request_body_failed", http.StatusBadRequest)
  435. }
  436. break
  437. }
  438. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  439. taskErr = taskRelayHandler(c, relayInfo)
  440. }
  441. useChannel := c.GetStringSlice("use_channel")
  442. if len(useChannel) > 1 {
  443. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  444. logger.LogInfo(c, retryLogStr)
  445. }
  446. if taskErr != nil {
  447. if taskErr.StatusCode == http.StatusTooManyRequests {
  448. taskErr.Message = "当前分组上游负载已饱和,请稍后再试"
  449. }
  450. c.JSON(taskErr.StatusCode, taskErr)
  451. }
  452. }
  453. func taskRelayHandler(c *gin.Context, relayInfo *relaycommon.RelayInfo) *dto.TaskError {
  454. var err *dto.TaskError
  455. switch relayInfo.RelayMode {
  456. case relayconstant.RelayModeSunoFetch, relayconstant.RelayModeSunoFetchByID, relayconstant.RelayModeVideoFetchByID:
  457. err = relay.RelayTaskFetch(c, relayInfo.RelayMode)
  458. default:
  459. err = relay.RelayTaskSubmit(c, relayInfo)
  460. }
  461. return err
  462. }
  463. func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *dto.TaskError, retryTimes int) bool {
  464. if taskErr == nil {
  465. return false
  466. }
  467. if retryTimes <= 0 {
  468. return false
  469. }
  470. if _, ok := c.Get("specific_channel_id"); ok {
  471. return false
  472. }
  473. if taskErr.StatusCode == http.StatusTooManyRequests {
  474. return true
  475. }
  476. if taskErr.StatusCode == 307 {
  477. return true
  478. }
  479. if taskErr.StatusCode/100 == 5 {
  480. // 超时不重试
  481. if taskErr.StatusCode == 504 || taskErr.StatusCode == 524 {
  482. return false
  483. }
  484. return true
  485. }
  486. if taskErr.StatusCode == http.StatusBadRequest {
  487. return false
  488. }
  489. if taskErr.StatusCode == 408 {
  490. // azure处理超时不重试
  491. return false
  492. }
  493. if taskErr.LocalError {
  494. return false
  495. }
  496. if taskErr.StatusCode/100 == 2 {
  497. return false
  498. }
  499. return true
  500. }