Просмотр исходного кода

fix: prevent duplicate refunds on task failure #2050

CaIon 4 месяцев назад
Родитель
Сommit
09ff878d88
2 измененных файлов с 18 добавлено и 9 удалено
  1. 17 8
      controller/task_video.go
  2. 1 1
      logger/logger.go

+ 17 - 8
controller/task_video.go

@@ -115,6 +115,12 @@ func updateVideoSingleTask(ctx context.Context, adaptor channel.TaskAdaptor, cha
 		//return fmt.Errorf("task %s status is empty", taskId)
 		taskResult = relaycommon.FailTaskInfo("upstream returned empty status")
 	}
+
+	// 记录原本的状态,防止重复退款
+	shouldRefund := false
+	quota := task.Quota
+	preStatus := task.Status
+
 	task.Status = model.TaskStatus(taskResult.Status)
 	switch taskResult.Status {
 	case model.TaskStatusSubmitted:
@@ -225,7 +231,7 @@ func updateVideoSingleTask(ctx context.Context, adaptor channel.TaskAdaptor, cha
 			}
 		}
 	case model.TaskStatusFailure:
-		preStatus := task.Status
+		logger.LogJson(ctx, fmt.Sprintf("Task %s failed", taskId), task)
 		task.Status = model.TaskStatusFailure
 		task.Progress = "100%"
 		if task.FinishTime == 0 {
@@ -233,16 +239,10 @@ func updateVideoSingleTask(ctx context.Context, adaptor channel.TaskAdaptor, cha
 		}
 		task.FailReason = taskResult.Reason
 		logger.LogInfo(ctx, fmt.Sprintf("Task %s failed: %s", task.TaskID, task.FailReason))
-		quota := task.Quota
 		taskResult.Progress = "100%"
 		if quota != 0 {
 			if preStatus != model.TaskStatusFailure {
-				// 任务失败且之前状态不是失败才退还额度,防止重复退还
-				if err := model.IncreaseUserQuota(task.UserId, quota, false); err != nil {
-					logger.LogWarn(ctx, "Failed to increase user quota: "+err.Error())
-				}
-				logContent := fmt.Sprintf("Video async task failed %s, refund %s", task.TaskID, logger.LogQuota(quota))
-				model.RecordLog(task.UserId, model.LogTypeSystem, logContent)
+				shouldRefund = true
 			} else {
 				logger.LogWarn(ctx, fmt.Sprintf("Task %s already in failure status, skip refund", task.TaskID))
 			}
@@ -257,6 +257,15 @@ func updateVideoSingleTask(ctx context.Context, adaptor channel.TaskAdaptor, cha
 		common.SysLog("UpdateVideoTask task error: " + err.Error())
 	}
 
+	if shouldRefund {
+		// 任务失败且之前状态不是失败才退还额度,防止重复退还
+		if err := model.IncreaseUserQuota(task.UserId, quota, false); err != nil {
+			logger.LogWarn(ctx, "Failed to increase user quota: "+err.Error())
+		}
+		logContent := fmt.Sprintf("Video async task failed %s, refund %s", task.TaskID, logger.LogQuota(quota))
+		model.RecordLog(task.UserId, model.LogTypeSystem, logContent)
+	}
+
 	return nil
 }
 

+ 1 - 1
logger/logger.go

@@ -153,5 +153,5 @@ func LogJson(ctx context.Context, msg string, obj any) {
 		LogError(ctx, fmt.Sprintf("json marshal failed: %s", err.Error()))
 		return
 	}
-	LogInfo(ctx, fmt.Sprintf("%s | %s", msg, string(jsonStr)))
+	LogDebug(ctx, fmt.Sprintf("%s | %s", msg, string(jsonStr)))
 }