task.go 8.6 KB

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