task.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package controller
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "one-api/common"
  10. "one-api/constant"
  11. "one-api/dto"
  12. "one-api/logger"
  13. "one-api/model"
  14. "one-api/relay"
  15. "sort"
  16. "strconv"
  17. "time"
  18. "github.com/gin-gonic/gin"
  19. "github.com/samber/lo"
  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. logger.LogError(ctx, fmt.Sprintf("Fix null task_id task error: %v", err))
  56. } else {
  57. logger.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. if err := UpdateVideoTaskAll(context.Background(), platform, taskChannelM, taskM); err != nil {
  76. common.SysLog(fmt.Sprintf("UpdateVideoTaskAll fail: %s", err))
  77. }
  78. }
  79. }
  80. func UpdateSunoTaskAll(ctx context.Context, taskChannelM map[int][]string, taskM map[string]*model.Task) error {
  81. for channelId, taskIds := range taskChannelM {
  82. err := updateSunoTaskAll(ctx, channelId, taskIds, taskM)
  83. if err != nil {
  84. logger.LogError(ctx, fmt.Sprintf("渠道 #%d 更新异步任务失败: %d", channelId, err.Error()))
  85. }
  86. }
  87. return nil
  88. }
  89. func updateSunoTaskAll(ctx context.Context, channelId int, taskIds []string, taskM map[string]*model.Task) error {
  90. logger.LogInfo(ctx, fmt.Sprintf("渠道 #%d 未完成的任务有: %d", channelId, len(taskIds)))
  91. if len(taskIds) == 0 {
  92. return nil
  93. }
  94. channel, err := model.CacheGetChannel(channelId)
  95. if err != nil {
  96. common.SysLog(fmt.Sprintf("CacheGetChannel: %v", err))
  97. err = model.TaskBulkUpdate(taskIds, map[string]any{
  98. "fail_reason": fmt.Sprintf("获取渠道信息失败,请联系管理员,渠道ID:%d", channelId),
  99. "status": "FAILURE",
  100. "progress": "100%",
  101. })
  102. if err != nil {
  103. common.SysLog(fmt.Sprintf("UpdateMidjourneyTask error2: %v", err))
  104. }
  105. return err
  106. }
  107. adaptor := relay.GetTaskAdaptor(constant.TaskPlatformSuno)
  108. if adaptor == nil {
  109. return errors.New("adaptor not found")
  110. }
  111. resp, err := adaptor.FetchTask(*channel.BaseURL, channel.Key, map[string]any{
  112. "ids": taskIds,
  113. })
  114. if err != nil {
  115. common.SysLog(fmt.Sprintf("Get Task Do req error: %v", err))
  116. return err
  117. }
  118. if resp.StatusCode != http.StatusOK {
  119. logger.LogError(ctx, fmt.Sprintf("Get Task status code: %d", resp.StatusCode))
  120. return errors.New(fmt.Sprintf("Get Task status code: %d", resp.StatusCode))
  121. }
  122. defer resp.Body.Close()
  123. responseBody, err := io.ReadAll(resp.Body)
  124. if err != nil {
  125. common.SysLog(fmt.Sprintf("Get Task parse body error: %v", err))
  126. return err
  127. }
  128. var responseItems dto.TaskResponse[[]dto.SunoDataResponse]
  129. err = json.Unmarshal(responseBody, &responseItems)
  130. if err != nil {
  131. logger.LogError(ctx, fmt.Sprintf("Get Task parse body error2: %v, body: %s", err, string(responseBody)))
  132. return err
  133. }
  134. if !responseItems.IsSuccess() {
  135. common.SysLog(fmt.Sprintf("渠道 #%d 未完成的任务有: %d, 成功获取到任务数: %d", channelId, len(taskIds), string(responseBody)))
  136. return err
  137. }
  138. for _, responseItem := range responseItems.Data {
  139. task := taskM[responseItem.TaskID]
  140. if !checkTaskNeedUpdate(task, responseItem) {
  141. continue
  142. }
  143. task.Status = lo.If(model.TaskStatus(responseItem.Status) != "", model.TaskStatus(responseItem.Status)).Else(task.Status)
  144. task.FailReason = lo.If(responseItem.FailReason != "", responseItem.FailReason).Else(task.FailReason)
  145. task.SubmitTime = lo.If(responseItem.SubmitTime != 0, responseItem.SubmitTime).Else(task.SubmitTime)
  146. task.StartTime = lo.If(responseItem.StartTime != 0, responseItem.StartTime).Else(task.StartTime)
  147. task.FinishTime = lo.If(responseItem.FinishTime != 0, responseItem.FinishTime).Else(task.FinishTime)
  148. if responseItem.FailReason != "" || task.Status == model.TaskStatusFailure {
  149. logger.LogInfo(ctx, task.TaskID+" 构建失败,"+task.FailReason)
  150. task.Progress = "100%"
  151. //err = model.CacheUpdateUserQuota(task.UserId) ?
  152. if err != nil {
  153. logger.LogError(ctx, "error update user quota cache: "+err.Error())
  154. } else {
  155. quota := task.Quota
  156. if quota != 0 {
  157. err = model.IncreaseUserQuota(task.UserId, quota, false)
  158. if err != nil {
  159. logger.LogError(ctx, "fail to increase user quota: "+err.Error())
  160. }
  161. logContent := fmt.Sprintf("异步任务执行失败 %s,补偿 %s", task.TaskID, logger.LogQuota(quota))
  162. model.RecordLog(task.UserId, model.LogTypeSystem, logContent)
  163. }
  164. }
  165. }
  166. if responseItem.Status == model.TaskStatusSuccess {
  167. task.Progress = "100%"
  168. }
  169. task.Data = responseItem.Data
  170. err = task.Update()
  171. if err != nil {
  172. common.SysLog("UpdateMidjourneyTask task error: " + err.Error())
  173. }
  174. }
  175. return nil
  176. }
  177. func checkTaskNeedUpdate(oldTask *model.Task, newTask dto.SunoDataResponse) bool {
  178. if oldTask.SubmitTime != newTask.SubmitTime {
  179. return true
  180. }
  181. if oldTask.StartTime != newTask.StartTime {
  182. return true
  183. }
  184. if oldTask.FinishTime != newTask.FinishTime {
  185. return true
  186. }
  187. if string(oldTask.Status) != newTask.Status {
  188. return true
  189. }
  190. if oldTask.FailReason != newTask.FailReason {
  191. return true
  192. }
  193. if oldTask.FinishTime != newTask.FinishTime {
  194. return true
  195. }
  196. if (oldTask.Status == model.TaskStatusFailure || oldTask.Status == model.TaskStatusSuccess) && oldTask.Progress != "100%" {
  197. return true
  198. }
  199. oldData, _ := json.Marshal(oldTask.Data)
  200. newData, _ := json.Marshal(newTask.Data)
  201. sort.Slice(oldData, func(i, j int) bool {
  202. return oldData[i] < oldData[j]
  203. })
  204. sort.Slice(newData, func(i, j int) bool {
  205. return newData[i] < newData[j]
  206. })
  207. if string(oldData) != string(newData) {
  208. return true
  209. }
  210. return false
  211. }
  212. func GetAllTask(c *gin.Context) {
  213. pageInfo := common.GetPageQuery(c)
  214. startTimestamp, _ := strconv.ParseInt(c.Query("start_timestamp"), 10, 64)
  215. endTimestamp, _ := strconv.ParseInt(c.Query("end_timestamp"), 10, 64)
  216. // 解析其他查询参数
  217. queryParams := model.SyncTaskQueryParams{
  218. Platform: constant.TaskPlatform(c.Query("platform")),
  219. TaskID: c.Query("task_id"),
  220. Status: c.Query("status"),
  221. Action: c.Query("action"),
  222. StartTimestamp: startTimestamp,
  223. EndTimestamp: endTimestamp,
  224. ChannelID: c.Query("channel_id"),
  225. }
  226. items := model.TaskGetAllTasks(pageInfo.GetStartIdx(), pageInfo.GetPageSize(), queryParams)
  227. total := model.TaskCountAllTasks(queryParams)
  228. pageInfo.SetTotal(int(total))
  229. pageInfo.SetItems(items)
  230. common.ApiSuccess(c, pageInfo)
  231. }
  232. func GetUserTask(c *gin.Context) {
  233. pageInfo := common.GetPageQuery(c)
  234. userId := c.GetInt("id")
  235. startTimestamp, _ := strconv.ParseInt(c.Query("start_timestamp"), 10, 64)
  236. endTimestamp, _ := strconv.ParseInt(c.Query("end_timestamp"), 10, 64)
  237. queryParams := model.SyncTaskQueryParams{
  238. Platform: constant.TaskPlatform(c.Query("platform")),
  239. TaskID: c.Query("task_id"),
  240. Status: c.Query("status"),
  241. Action: c.Query("action"),
  242. StartTimestamp: startTimestamp,
  243. EndTimestamp: endTimestamp,
  244. }
  245. items := model.TaskGetAllUserTask(userId, pageInfo.GetStartIdx(), pageInfo.GetPageSize(), queryParams)
  246. total := model.TaskCountAllUserTask(userId, queryParams)
  247. pageInfo.SetTotal(int(total))
  248. pageInfo.SetItems(items)
  249. common.ApiSuccess(c, pageInfo)
  250. }