task.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package controller
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "github.com/gin-gonic/gin"
  9. "github.com/samber/lo"
  10. "io"
  11. "net/http"
  12. "one-api/common"
  13. "one-api/constant"
  14. "one-api/dto"
  15. "one-api/model"
  16. "one-api/service"
  17. "sort"
  18. "strconv"
  19. "time"
  20. )
  21. func UpdateTaskBulk() {
  22. //revocer
  23. //imageModel := "midjourney"
  24. for {
  25. time.Sleep(time.Duration(15) * time.Second)
  26. common.SysLog("任务进度轮询开始")
  27. ctx := context.TODO()
  28. allTasks := model.GetAllUnFinishSyncTasks(500)
  29. platformTask := make(map[constant.TaskPlatform][]*model.Task)
  30. for _, t := range allTasks {
  31. platformTask[t.Platform] = append(platformTask[t.Platform], t)
  32. }
  33. for platform, tasks := range platformTask {
  34. if len(tasks) == 0 {
  35. continue
  36. }
  37. taskChannelM := make(map[int][]string)
  38. taskM := make(map[string]*model.Task)
  39. nullTaskIds := make([]int64, 0)
  40. for _, task := range tasks {
  41. if task.TaskID == "" {
  42. // 统计失败的未完成任务
  43. nullTaskIds = append(nullTaskIds, task.ID)
  44. continue
  45. }
  46. taskM[task.TaskID] = task
  47. taskChannelM[task.ChannelId] = append(taskChannelM[task.ChannelId], task.TaskID)
  48. }
  49. if len(nullTaskIds) > 0 {
  50. err := model.TaskBulkUpdateByID(nullTaskIds, map[string]any{
  51. "status": "FAILURE",
  52. "progress": "100%",
  53. })
  54. if err != nil {
  55. common.LogError(ctx, fmt.Sprintf("Fix null task_id task error: %v", err))
  56. } else {
  57. common.LogInfo(ctx, fmt.Sprintf("Fix null task_id task success: %v", nullTaskIds))
  58. }
  59. }
  60. if len(taskChannelM) == 0 {
  61. continue
  62. }
  63. UpdateTaskByPlatform(platform, taskChannelM, taskM)
  64. }
  65. common.SysLog("任务进度轮询完成")
  66. }
  67. }
  68. func UpdateTaskByPlatform(platform constant.TaskPlatform, taskChannelM map[int][]string, taskM map[string]*model.Task) {
  69. switch platform {
  70. case constant.TaskPlatformMidjourney:
  71. //_ = UpdateMidjourneyTaskAll(context.Background(), tasks)
  72. case constant.TaskPlatformSuno:
  73. _ = UpdateSunoTaskAll(context.Background(), taskChannelM, taskM)
  74. default:
  75. common.SysLog("未知平台")
  76. }
  77. }
  78. func UpdateSunoTaskAll(ctx context.Context, taskChannelM map[int][]string, taskM map[string]*model.Task) error {
  79. for channelId, taskIds := range taskChannelM {
  80. err := updateSunoTaskAll(ctx, channelId, taskIds, taskM)
  81. if err != nil {
  82. common.LogError(ctx, fmt.Sprintf("渠道 #%d 更新异步任务失败: %d", channelId, err.Error()))
  83. }
  84. }
  85. return nil
  86. }
  87. func updateSunoTaskAll(ctx context.Context, channelId int, taskIds []string, taskM map[string]*model.Task) error {
  88. common.LogInfo(ctx, fmt.Sprintf("渠道 #%d 未完成的任务有: %d", channelId, len(taskIds)))
  89. if len(taskIds) == 0 {
  90. return nil
  91. }
  92. channel, err := model.CacheGetChannel(channelId)
  93. if err != nil {
  94. common.SysLog(fmt.Sprintf("CacheGetChannel: %v", err))
  95. err = model.TaskBulkUpdate(taskIds, map[string]any{
  96. "fail_reason": fmt.Sprintf("获取渠道信息失败,请联系管理员,渠道ID:%d", channelId),
  97. "status": "FAILURE",
  98. "progress": "100%",
  99. })
  100. if err != nil {
  101. common.SysError(fmt.Sprintf("UpdateMidjourneyTask error2: %v", err))
  102. }
  103. return err
  104. }
  105. requestUrl := fmt.Sprintf("%s/fetch", *channel.BaseURL)
  106. body, _ := json.Marshal(map[string]any{
  107. "ids": taskIds,
  108. })
  109. req, err := http.NewRequest("POST", requestUrl, bytes.NewBuffer(body))
  110. if err != nil {
  111. common.SysError(fmt.Sprintf("Get Task error: %v", err))
  112. return err
  113. }
  114. defer req.Body.Close()
  115. // 设置超时时间
  116. timeout := time.Second * 15
  117. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  118. defer cancel()
  119. // 使用带有超时的 context 创建新的请求
  120. req = req.WithContext(ctx)
  121. req.Header.Set("Content-Type", "application/json")
  122. req.Header.Set("Authorization", "Bearer "+channel.Key)
  123. resp, err := service.GetHttpClient().Do(req)
  124. if err != nil {
  125. common.SysError(fmt.Sprintf("Get Task Do req error: %v", err))
  126. return err
  127. }
  128. if resp.StatusCode != http.StatusOK {
  129. common.LogError(ctx, fmt.Sprintf("Get Task status code: %d", resp.StatusCode))
  130. return errors.New(fmt.Sprintf("Get Task status code: %d", resp.StatusCode))
  131. }
  132. defer resp.Body.Close()
  133. responseBody, err := io.ReadAll(resp.Body)
  134. if err != nil {
  135. common.SysError(fmt.Sprintf("Get Task parse body error: %v", err))
  136. return err
  137. }
  138. var responseItems dto.TaskResponse[[]dto.SunoDataResponse]
  139. err = json.Unmarshal(responseBody, &responseItems)
  140. if err != nil {
  141. common.LogError(ctx, fmt.Sprintf("Get Task parse body error2: %v, req: %s, body: %s", err, string(body), string(responseBody)))
  142. return err
  143. }
  144. if !responseItems.IsSuccess() {
  145. common.SysLog(fmt.Sprintf("渠道 #%d 未完成的任务有: %d, 成功获取到任务数: %d", channelId, len(taskIds), string(responseBody)))
  146. return err
  147. }
  148. for _, responseItem := range responseItems.Data {
  149. task := taskM[responseItem.TaskID]
  150. if !checkTaskNeedUpdate(task, responseItem) {
  151. continue
  152. }
  153. task.Status = lo.If(model.TaskStatus(responseItem.Status) != "", model.TaskStatus(responseItem.Status)).Else(task.Status)
  154. task.FailReason = lo.If(responseItem.FailReason != "", responseItem.FailReason).Else(task.FailReason)
  155. task.SubmitTime = lo.If(responseItem.SubmitTime != 0, responseItem.SubmitTime).Else(task.SubmitTime)
  156. task.StartTime = lo.If(responseItem.StartTime != 0, responseItem.StartTime).Else(task.StartTime)
  157. task.FinishTime = lo.If(responseItem.FinishTime != 0, responseItem.FinishTime).Else(task.FinishTime)
  158. if responseItem.FailReason != "" || task.Status == model.TaskStatusFailure {
  159. common.LogInfo(ctx, task.TaskID+" 构建失败,"+task.FailReason)
  160. task.Progress = "100%"
  161. err = model.CacheUpdateUserQuota(task.UserId)
  162. if err != nil {
  163. common.LogError(ctx, "error update user quota cache: "+err.Error())
  164. } else {
  165. quota := task.Quota
  166. if quota != 0 {
  167. err = model.IncreaseUserQuota(task.UserId, quota)
  168. if err != nil {
  169. common.LogError(ctx, "fail to increase user quota: "+err.Error())
  170. }
  171. logContent := fmt.Sprintf("异步任务执行失败 %s,补偿 %s", task.TaskID, common.LogQuota(quota))
  172. model.RecordLog(task.UserId, model.LogTypeSystem, logContent)
  173. }
  174. }
  175. }
  176. if responseItem.Status == model.TaskStatusSuccess {
  177. task.Progress = "100%"
  178. }
  179. task.Data = responseItem.Data
  180. err = task.Update()
  181. if err != nil {
  182. common.SysError("UpdateMidjourneyTask task error: " + err.Error())
  183. }
  184. }
  185. return nil
  186. }
  187. func checkTaskNeedUpdate(oldTask *model.Task, newTask dto.SunoDataResponse) bool {
  188. if oldTask.SubmitTime != newTask.SubmitTime {
  189. return true
  190. }
  191. if oldTask.StartTime != newTask.StartTime {
  192. return true
  193. }
  194. if oldTask.FinishTime != newTask.FinishTime {
  195. return true
  196. }
  197. if string(oldTask.Status) != newTask.Status {
  198. return true
  199. }
  200. if oldTask.FailReason != newTask.FailReason {
  201. return true
  202. }
  203. if oldTask.FinishTime != newTask.FinishTime {
  204. return true
  205. }
  206. if (oldTask.Status == model.TaskStatusFailure || oldTask.Status == model.TaskStatusSuccess) && oldTask.Progress != "100%" {
  207. return true
  208. }
  209. oldData, _ := json.Marshal(oldTask.Data)
  210. newData, _ := json.Marshal(newTask.Data)
  211. sort.Slice(oldData, func(i, j int) bool {
  212. return oldData[i] < oldData[j]
  213. })
  214. sort.Slice(newData, func(i, j int) bool {
  215. return newData[i] < newData[j]
  216. })
  217. if string(oldData) != string(newData) {
  218. return true
  219. }
  220. return false
  221. }
  222. func GetAllTask(c *gin.Context) {
  223. p, _ := strconv.Atoi(c.Query("p"))
  224. if p < 0 {
  225. p = 0
  226. }
  227. startTimestamp, _ := strconv.ParseInt(c.Query("start_timestamp"), 10, 64)
  228. endTimestamp, _ := strconv.ParseInt(c.Query("end_timestamp"), 10, 64)
  229. // 解析其他查询参数
  230. queryParams := model.SyncTaskQueryParams{
  231. Platform: constant.TaskPlatform(c.Query("platform")),
  232. TaskID: c.Query("task_id"),
  233. Status: c.Query("status"),
  234. Action: c.Query("action"),
  235. StartTimestamp: startTimestamp,
  236. EndTimestamp: endTimestamp,
  237. }
  238. logs := model.TaskGetAllTasks(p*common.ItemsPerPage, common.ItemsPerPage, queryParams)
  239. if logs == nil {
  240. logs = make([]*model.Task, 0)
  241. }
  242. c.JSON(200, gin.H{
  243. "success": true,
  244. "message": "",
  245. "data": logs,
  246. })
  247. }
  248. func GetUserTask(c *gin.Context) {
  249. p, _ := strconv.Atoi(c.Query("p"))
  250. if p < 0 {
  251. p = 0
  252. }
  253. userId := c.GetInt("id")
  254. startTimestamp, _ := strconv.ParseInt(c.Query("start_timestamp"), 10, 64)
  255. endTimestamp, _ := strconv.ParseInt(c.Query("end_timestamp"), 10, 64)
  256. queryParams := model.SyncTaskQueryParams{
  257. Platform: constant.TaskPlatform(c.Query("platform")),
  258. TaskID: c.Query("task_id"),
  259. Status: c.Query("status"),
  260. Action: c.Query("action"),
  261. StartTimestamp: startTimestamp,
  262. EndTimestamp: endTimestamp,
  263. }
  264. logs := model.TaskGetAllUserTask(userId, p*common.ItemsPerPage, common.ItemsPerPage, queryParams)
  265. if logs == nil {
  266. logs = make([]*model.Task, 0)
  267. }
  268. c.JSON(200, gin.H{
  269. "success": true,
  270. "message": "",
  271. "data": logs,
  272. })
  273. }