task.go 8.8 KB

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