Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: batch patch task status (#3026)

p0ny61541ddf6e11
diff --git a/api/task.go b/api/task.go
index 6b9d0f6ec3..28c8af0e34 100644
--- a/api/task.go
+++ b/api/task.go
@@ -130,8 +130,7 @@ type TaskDatabaseSchemaUpdateGhostSyncPayload struct {
}
// TaskDatabaseSchemaUpdateGhostCutoverPayload is the task payload for gh-ost switching the original table and the ghost table.
-type TaskDatabaseSchemaUpdateGhostCutoverPayload struct {
-}
+type TaskDatabaseSchemaUpdateGhostCutoverPayload struct{}
// TaskDatabaseDataUpdatePayload is the task payload for database data update (DML).
type TaskDatabaseDataUpdatePayload struct {
@@ -268,7 +267,7 @@ type TaskPatch struct {
// TaskStatusPatch is the API message for patching a task status.
type TaskStatusPatch struct {
- ID int
+ IDList []int
// Standard fields
// Value is assigned from the jwt subject field passed by the client.
diff --git a/server/issue.go b/server/issue.go
index a78edba13b..befcb4cfa3 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -1231,7 +1231,7 @@ func (s *Server) changeIssueStatus(ctx context.Context, issue *api.Issue, newSta
for _, task := range stage.TaskList {
if task.Status == api.TaskRunning {
if _, err := s.patchTaskStatus(ctx, task, &api.TaskStatusPatch{
- ID: task.ID,
+ IDList: []int{task.ID},
UpdaterID: updaterID,
Status: api.TaskCanceled,
}); err != nil {
diff --git a/server/pipeline.go b/server/pipeline.go
index 2c99c9c822..a03340d515 100644
--- a/server/pipeline.go
+++ b/server/pipeline.go
@@ -29,7 +29,7 @@ func (s *Server) ScheduleActiveStage(ctx context.Context, pipeline *api.Pipeline
}
if ok {
if _, err := s.patchTaskStatus(ctx, task, &api.TaskStatusPatch{
- ID: task.ID,
+ IDList: []int{task.ID},
UpdaterID: api.SystemBotID,
Status: api.TaskPending,
}); err != nil {
diff --git a/server/stage.go b/server/stage.go
index 16b6d4182d..a2aeb88b11 100644
--- a/server/stage.go
+++ b/server/stage.go
@@ -59,7 +59,7 @@ func (s *Server) registerStageRoutes(g *echo.Group) {
var tasksPatched []*api.Task
for _, task := range tasks {
taskPatched, err := s.patchTaskStatus(ctx, task, &api.TaskStatusPatch{
- ID: task.ID,
+ IDList: []int{task.ID},
UpdaterID: stageAllTaskStatusPatch.UpdaterID,
Status: stageAllTaskStatusPatch.Status,
})
diff --git a/server/task.go b/server/task.go
index a09188ab18..fec53ef610 100644
--- a/server/task.go
+++ b/server/task.go
@@ -184,7 +184,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
currentPrincipalID := c.Get(getPrincipalIDContextKey()).(int)
taskStatusPatch := &api.TaskStatusPatch{
- ID: taskID,
+ IDList: []int{taskID},
UpdaterID: currentPrincipalID,
}
if err := jsonapi.UnmarshalPayload(c.Request().Body, taskStatusPatch); err != nil {
@@ -401,7 +401,7 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.T
// updated statement, dismiss stale approvals and transfer the status to PendingApproval.
if taskPatched.Status != api.TaskPendingApproval {
t, err := s.patchTaskStatus(ctx, taskPatched, &api.TaskStatusPatch{
- ID: taskPatch.ID,
+ IDList: []int{taskPatch.ID},
UpdaterID: taskPatch.UpdaterID,
Status: api.TaskPendingApproval,
})
@@ -523,7 +523,7 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.T
// updated earliest allowed time, dismiss stale approvals and transfer the status to PendingApproval.
if taskPatched.Status != api.TaskPendingApproval {
t, err := s.patchTaskStatus(ctx, taskPatched, &api.TaskStatusPatch{
- ID: taskPatch.ID,
+ IDList: []int{taskPatch.ID},
UpdaterID: taskPatch.UpdaterID,
Status: api.TaskPendingApproval,
})
@@ -656,6 +656,7 @@ func (s *Server) getGroupValueForTask(ctx context.Context, issue *api.Issue, tas
return nil, nil
}
+// patchTaskStatus patches a single task.
func (s *Server) patchTaskStatus(ctx context.Context, task *api.Task, taskStatusPatch *api.TaskStatusPatch) (_ *api.Task, err error) {
defer func() {
if err != nil {
@@ -675,6 +676,10 @@ func (s *Server) patchTaskStatus(ctx context.Context, task *api.Task, taskStatus
}
}
+ if len(taskStatusPatch.IDList) != 1 {
+ return nil, errors.Errorf("expect to patch 1 task, get %d", len(taskStatusPatch.IDList))
+ }
+
if taskStatusPatch.Status == api.TaskCanceled {
if !taskCancellationImplemented[task.Type] {
return nil, common.Errorf(common.NotImplemented, "Canceling task type %s is not supported", task.Type)
@@ -696,10 +701,11 @@ func (s *Server) patchTaskStatus(ctx context.Context, task *api.Task, taskStatus
taskStatusPatch.Result = &resultStr
}
- taskPatched, err := s.store.PatchTaskStatus(ctx, taskStatusPatch)
+ taskPatchedList, err := s.store.PatchTaskStatus(ctx, taskStatusPatch)
if err != nil {
return nil, errors.Wrapf(err, "failed to change task %v(%v) status", task.ID, task.Name)
}
+ taskPatched := taskPatchedList[0]
// Most tasks belong to a pipeline which in turns belongs to an issue. The followup code
// behaves differently depending on whether the task is wrapped in an issue.
@@ -901,6 +907,7 @@ func areAllTasksDone(pipeline *api.Pipeline) bool {
func (s *Server) cancelDependingTasks(ctx context.Context, task *api.Task) error {
queue := []int{task.ID}
seen := map[int]bool{task.ID: true}
+ var idList []int
for len(queue) != 0 {
fromTaskID := queue[0]
queue = queue[1:]
@@ -913,16 +920,16 @@ func (s *Server) cancelDependingTasks(ctx context.Context, task *api.Task) error
return errors.Errorf("found a cycle in task dag, visit task %v twice", dag.ToTaskID)
}
seen[dag.ToTaskID] = true
-
- if _, err := s.store.PatchTaskStatus(ctx, &api.TaskStatusPatch{
- ID: dag.ToTaskID,
- UpdaterID: api.SystemBotID,
- Status: api.TaskCanceled,
- }); err != nil {
- return err
- }
+ idList = append(idList, dag.ToTaskID)
queue = append(queue, dag.ToTaskID)
}
}
+ if _, err := s.store.PatchTaskStatus(ctx, &api.TaskStatusPatch{
+ IDList: idList,
+ UpdaterID: api.SystemBotID,
+ Status: api.TaskCanceled,
+ }); err != nil {
+ return err
+ }
return nil
}
diff --git a/server/task_scheduler.go b/server/task_scheduler.go
index 92ff9034a1..c47b9f145e 100644
--- a/server/task_scheduler.go
+++ b/server/task_scheduler.go
@@ -215,7 +215,7 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
code := common.ErrorCode(err)
result := string(bytes)
taskStatusPatch := &api.TaskStatusPatch{
- ID: task.ID,
+ IDList: []int{task.ID},
UpdaterID: api.SystemBotID,
Status: api.TaskFailed,
Code: &code,
@@ -244,7 +244,7 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
code := common.Ok
result := string(bytes)
taskStatusPatch := &api.TaskStatusPatch{
- ID: task.ID,
+ IDList: []int{task.ID},
UpdaterID: api.SystemBotID,
Status: api.TaskDone,
Code: &code,
@@ -328,7 +328,7 @@ func (s *TaskScheduler) ClearRunningTasks(ctx context.Context) error {
}
for _, task := range runningTasks {
if _, err := s.server.store.PatchTaskStatus(ctx, &api.TaskStatusPatch{
- ID: task.ID,
+ IDList: []int{task.ID},
UpdaterID: api.SystemBotID,
Status: api.TaskCanceled,
}); err != nil {
@@ -465,7 +465,7 @@ func (s *TaskScheduler) ScheduleIfNeeded(ctx context.Context, task *api.Task) (*
}
updatedTask, err := s.server.patchTaskStatus(ctx, task, &api.TaskStatusPatch{
- ID: task.ID,
+ IDList: []int{task.ID},
UpdaterID: api.SystemBotID,
Status: api.TaskRunning,
})
diff --git a/store/task.go b/store/task.go
index 4754c6457c..1475d33458 100644
--- a/store/task.go
+++ b/store/task.go
@@ -148,17 +148,21 @@ func (s *Store) PatchTask(ctx context.Context, patch *api.TaskPatch) (*api.Task,
return task, nil
}
-// PatchTaskStatus patches an instance of TaskStatus.
-func (s *Store) PatchTaskStatus(ctx context.Context, patch *api.TaskStatusPatch) (*api.Task, error) {
- taskRaw, err := s.patchTaskRawStatus(ctx, patch)
+// PatchTaskStatus patches a list of TaskStatus.
+func (s *Store) PatchTaskStatus(ctx context.Context, patch *api.TaskStatusPatch) ([]*api.Task, error) {
+ taskRawList, err := s.patchTaskRawStatus(ctx, patch)
if err != nil {
return nil, errors.Wrapf(err, "failed to patch TaskStatus with TaskStatusPatch[%+v]", patch)
}
- task, err := s.composeTask(ctx, taskRaw)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to compose TaskStatus with taskRaw[%+v]", taskRaw)
+ var taskList []*api.Task
+ for _, taskRaw := range taskRawList {
+ task, err := s.composeTask(ctx, taskRaw)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to compose TaskStatus with taskRaw[%+v]", taskRaw)
+ }
+ taskList = append(taskList, task)
}
- return task, nil
+ return taskList, nil
}
// CountTaskGroupByTypeAndStatus counts the number of TaskGroup and group by TaskType.
@@ -355,9 +359,9 @@ func (s *Store) patchTaskRaw(ctx context.Context, patch *api.TaskPatch) (*taskRa
return task, nil
}
-// patchTaskRawStatus updates an existing task status and the corresponding task run status atomically.
-// Returns ENOTFOUND if task does not exist.
-func (s *Store) patchTaskRawStatus(ctx context.Context, patch *api.TaskStatusPatch) (*taskRaw, error) {
+// patchTaskRawStatus updates existing task statuses and the corresponding task run statuses atomically.
+// Returns ENOTFOUND if tasks do not exist.
+func (s *Store) patchTaskRawStatus(ctx context.Context, patch *api.TaskStatusPatch) ([]*taskRaw, error) {
// Without using serializable isolation transaction, we will get race condition and have multiple task runs inserted because
// we do a read and write on task, without guaranteed consistency on task runs.
// Once we have multiple task runs, the task will get to unrecoverable state because find task run will fail with two active runs.
@@ -367,7 +371,7 @@ func (s *Store) patchTaskRawStatus(ctx context.Context, patch *api.TaskStatusPat
}
defer tx.Rollback()
- task, err := s.patchTaskStatusImpl(ctx, tx, patch)
+ taskList, err := s.patchTaskStatusImpl(ctx, tx, patch)
if err != nil {
return nil, FormatError(err)
}
@@ -376,7 +380,7 @@ func (s *Store) patchTaskRawStatus(ctx context.Context, patch *api.TaskStatusPat
return nil, FormatError(err)
}
- return task, nil
+ return taskList, nil
}
// createTaskImpl creates a new task.
@@ -640,125 +644,145 @@ func (*Store) patchTaskImpl(ctx context.Context, tx *Tx, patch *api.TaskPatch) (
return &taskRaw, nil
}
-// patchTaskStatusImpl updates a task status by ID. Returns the new state of the task after update.
-func (s *Store) patchTaskStatusImpl(ctx context.Context, tx *Tx, patch *api.TaskStatusPatch) (*taskRaw, error) {
+// patchTaskStatusImpl updates task status by IDList. Returns the new state of the tasks after update.
+func (s *Store) patchTaskStatusImpl(ctx context.Context, tx *Tx, patch *api.TaskStatusPatch) ([]*taskRaw, error) {
// Updates the corresponding task run if applicable.
// We update the task run first because updating task below returns row and it's a bit complicated to
// arrange code to prevent that opening row interfering with the task run update.
- taskFind := &api.TaskFind{
- ID: &patch.ID,
- }
- taskRawObj, err := s.getTaskRawTx(ctx, tx, taskFind)
- if err != nil {
- return nil, err
- }
- if taskRawObj == nil {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("task ID not found: %d", patch.ID)}
- }
-
- taskRunFind := &api.TaskRunFind{
- TaskID: &taskRawObj.ID,
- StatusList: &[]api.TaskRunStatus{
- api.TaskRunRunning,
- },
- }
- taskRunRaw, err := s.getTaskRunRawTx(ctx, tx, taskRunFind)
- if err != nil {
- return nil, err
- }
- if taskRunRaw == nil {
- if patch.Status == api.TaskRunning {
- taskRunCreate := &api.TaskRunCreate{
- CreatorID: patch.UpdaterID,
- TaskID: taskRawObj.ID,
- Name: fmt.Sprintf("%s %d", taskRawObj.Name, time.Now().Unix()),
- Type: taskRawObj.Type,
- Payload: taskRawObj.Payload,
- }
- // insert a running taskRun
- if _, err := s.createTaskRunImpl(ctx, tx, taskRunCreate); err != nil {
- return nil, err
- }
+ for _, id := range patch.IDList {
+ taskFind := &api.TaskFind{
+ ID: &id,
}
- } else {
- if patch.Status == api.TaskRunning {
- return nil, errors.Errorf("task is already running: %v", taskRawObj.Name)
+ taskRawObj, err := s.getTaskRawTx(ctx, tx, taskFind)
+ if err != nil {
+ return nil, err
}
- taskRunStatusPatch := &api.TaskRunStatusPatch{
- ID: &taskRunRaw.ID,
- UpdaterID: patch.UpdaterID,
- TaskID: &patch.ID,
- Code: patch.Code,
- Result: patch.Result,
- Comment: patch.Comment,
+ if taskRawObj == nil {
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("task ID not found: %d", id)}
}
- switch patch.Status {
- case api.TaskDone:
- taskRunStatusPatch.Status = api.TaskRunDone
- case api.TaskFailed:
- taskRunStatusPatch.Status = api.TaskRunFailed
- case api.TaskPending:
- case api.TaskPendingApproval:
- case api.TaskCanceled:
- taskRunStatusPatch.Status = api.TaskRunCanceled
+
+ taskRunFind := &api.TaskRunFind{
+ TaskID: &taskRawObj.ID,
+ StatusList: &[]api.TaskRunStatus{
+ api.TaskRunRunning,
+ },
}
- if _, err := s.patchTaskRunStatusImpl(ctx, tx, taskRunStatusPatch); err != nil {
+ taskRunRaw, err := s.getTaskRunRawTx(ctx, tx, taskRunFind)
+ if err != nil {
return nil, err
}
+ if taskRunRaw == nil {
+ if patch.Status == api.TaskRunning {
+ taskRunCreate := &api.TaskRunCreate{
+ CreatorID: patch.UpdaterID,
+ TaskID: taskRawObj.ID,
+ Name: fmt.Sprintf("%s %d", taskRawObj.Name, time.Now().Unix()),
+ Type: taskRawObj.Type,
+ Payload: taskRawObj.Payload,
+ }
+ // insert a running taskRun
+ if _, err := s.createTaskRunImpl(ctx, tx, taskRunCreate); err != nil {
+ return nil, err
+ }
+ }
+ } else {
+ if patch.Status == api.TaskRunning {
+ return nil, errors.Errorf("task is already running: %v", taskRawObj.Name)
+ }
+ taskRunStatusPatch := &api.TaskRunStatusPatch{
+ ID: &taskRunRaw.ID,
+ UpdaterID: patch.UpdaterID,
+ TaskID: &id,
+ Code: patch.Code,
+ Result: patch.Result,
+ Comment: patch.Comment,
+ }
+ switch patch.Status {
+ case api.TaskDone:
+ taskRunStatusPatch.Status = api.TaskRunDone
+ case api.TaskFailed:
+ taskRunStatusPatch.Status = api.TaskRunFailed
+ case api.TaskPending:
+ case api.TaskPendingApproval:
+ case api.TaskCanceled:
+ taskRunStatusPatch.Status = api.TaskRunCanceled
+ }
+ if _, err := s.patchTaskRunStatusImpl(ctx, tx, taskRunStatusPatch); err != nil {
+ return nil, err
+ }
+ }
}
// Updates the task
// Build UPDATE clause.
set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}
set, args = append(set, "status = $2"), append(args, patch.Status)
- args = append(args, patch.ID)
+ var ids []string
+ for _, id := range patch.IDList {
+ ids = append(ids, strconv.Itoa(id))
+ }
- var taskPatchedRaw *taskRaw
- var taskRaw taskRaw
// Execute update query with RETURNING.
- if err := tx.QueryRowContext(ctx, `
+ rows, err := tx.QueryContext(ctx, `
UPDATE task
SET `+strings.Join(set, ", ")+`
- WHERE id = $3
+ WHERE id in (`+strings.Join(ids, ",")+`)
RETURNING id, creator_id, created_ts, updater_id, updated_ts, pipeline_id, stage_id, instance_id, database_id, name, status, type, payload, earliest_allowed_ts
`,
args...,
- ).Scan(
- &taskRaw.ID,
- &taskRaw.CreatorID,
- &taskRaw.CreatedTs,
- &taskRaw.UpdaterID,
- &taskRaw.UpdatedTs,
- &taskRaw.PipelineID,
- &taskRaw.StageID,
- &taskRaw.InstanceID,
- &taskRaw.DatabaseID,
- &taskRaw.Name,
- &taskRaw.Status,
- &taskRaw.Type,
- &taskRaw.Payload,
- &taskRaw.EarliestAllowedTs,
- ); err != nil {
+ )
+ if err != nil {
return nil, FormatError(err)
}
- taskPatchedRaw = &taskRaw
+ defer rows.Close()
- taskRunRawList, err := s.findTaskRunImpl(ctx, tx, &api.TaskRunFind{
- TaskID: &taskRawObj.ID,
- })
- if err != nil {
- return nil, err
+ var taskRawList []*taskRaw
+ for rows.Next() {
+ var taskRaw taskRaw
+ if err := rows.Scan(
+ &taskRaw.ID,
+ &taskRaw.CreatorID,
+ &taskRaw.CreatedTs,
+ &taskRaw.UpdaterID,
+ &taskRaw.UpdatedTs,
+ &taskRaw.PipelineID,
+ &taskRaw.StageID,
+ &taskRaw.InstanceID,
+ &taskRaw.DatabaseID,
+ &taskRaw.Name,
+ &taskRaw.Status,
+ &taskRaw.Type,
+ &taskRaw.Payload,
+ &taskRaw.EarliestAllowedTs,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ taskRawList = append(taskRawList, &taskRaw)
}
- taskRawObj.TaskRunRawList = taskRunRawList
- taskCheckRunFind := &api.TaskCheckRunFind{
- TaskID: &taskRawObj.ID,
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
}
- taskCheckRunRawList, err := s.findTaskCheckRunImpl(ctx, tx, taskCheckRunFind)
- if err != nil {
- return nil, err
+
+ for _, taskRaw := range taskRawList {
+ taskRunRawList, err := s.findTaskRunImpl(ctx, tx, &api.TaskRunFind{
+ TaskID: &taskRaw.ID,
+ })
+ if err != nil {
+ return nil, err
+ }
+ taskRaw.TaskRunRawList = taskRunRawList
+
+ taskCheckRunFind := &api.TaskCheckRunFind{
+ TaskID: &taskRaw.ID,
+ }
+ taskCheckRunRawList, err := s.findTaskCheckRunImpl(ctx, tx, taskCheckRunFind)
+ if err != nil {
+ return nil, err
+ }
+ taskRaw.TaskCheckRunRawList = taskCheckRunRawList
}
- taskRawObj.TaskCheckRunRawList = taskCheckRunRawList
- return taskPatchedRaw, nil
+ return taskRawList, nil
}
diff --git a/tests/tests.go b/tests/tests.go
index aa1adebe19..208265c322 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -836,13 +836,13 @@ func (ctl *controller) patchIssueStatus(issueStatusPatch api.IssueStatusPatch) (
}
// patchTaskStatus patches the status of a task in the pipeline stage.
-func (ctl *controller) patchTaskStatus(taskStatusPatch api.TaskStatusPatch, pipelineID int) (*api.Task, error) {
+func (ctl *controller) patchTaskStatus(taskStatusPatch api.TaskStatusPatch, pipelineID int, taskID int) (*api.Task, error) {
buf := new(bytes.Buffer)
if err := jsonapi.MarshalPayload(buf, &taskStatusPatch); err != nil {
return nil, errors.Wrap(err, "failed to marshal patchTaskStatus")
}
- body, err := ctl.patch(fmt.Sprintf("/pipeline/%d/task/%d/status", pipelineID, taskStatusPatch.ID), buf)
+ body, err := ctl.patch(fmt.Sprintf("/pipeline/%d/task/%d/status", pipelineID, taskID), buf)
if err != nil {
return nil, err
}
@@ -888,10 +888,9 @@ func (ctl *controller) approveIssueNext(issue *api.Issue) error {
if task.Status == api.TaskPendingApproval {
if _, err := ctl.patchTaskStatus(
api.TaskStatusPatch{
- ID: task.ID,
Status: api.TaskPending,
},
- issue.Pipeline.ID); err != nil {
+ issue.Pipeline.ID, task.ID); err != nil {
return errors.Wrapf(err, "failed to patch task status for task %d", task.ID)
}
return nil