Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: use jsonb to update payload field for task patch (#3785)
Danny Xucd7f95b86336
diff --git a/api/task.go b/api/task.goindex 10ab85dd29..8714ff391b 100644--- a/api/task.go+++ b/api/task.go@@ -280,8 +280,10 @@ type TaskPatch struct {UpdaterID int// Domain specific fields- DatabaseID *int+ DatabaseID *int+ // Statement/SchemaVersion and Payload cannot be set at the same time.Statement *string `jsonapi:"attr,statement"`+ SchemaVersion *stringPayload *stringEarliestAllowedTs *int64 `jsonapi:"attr,earliestAllowedTs"`}diff --git a/server/runner/apprun/runner.go b/server/runner/apprun/runner.goindex f3af5eaf51..ad015dad99 100644--- a/server/runner/apprun/runner.go+++ b/server/runner/apprun/runner.go@@ -473,7 +473,7 @@ func (r *Runner) createExternalApproval(ctx context.Context, issue *api.Issue, s}for i, task := range stage.TaskList {- statement, err := getTaskStatement(task)+ statement, err := utils.GetTaskStatement(task)if err != nil {return err}@@ -523,16 +523,6 @@ func (r *Runner) createExternalApproval(ctx context.Context, issue *api.Issue, sreturn nil}-func getTaskStatement(task *api.Task) (string, error) {- var taskStatement struct {- Statement string `json:"statement"`- }- if err := json.Unmarshal([]byte(task.Payload), &taskStatement); err != nil {- return "", err- }- return taskStatement.Statement, nil-}-// scheduleApproval tries to cancel old external apporvals and create new external approvals if needed.func (r *Runner) scheduleApproval(ctx context.Context, issue *api.Issue, settingValue *api.SettingAppIMValue) {if !settingValue.ExternalApproval.Enabled {diff --git a/server/runner/taskrun/database_create_executor.go b/server/runner/taskrun/database_create_executor.goindex cf2a37acf7..15d1cbdd02 100644--- a/server/runner/taskrun/database_create_executor.go+++ b/server/runner/taskrun/database_create_executor.go@@ -199,17 +199,11 @@ func (exec *DatabaseCreateExecutor) RunOnce(ctx context.Context, task *api.Task)// The task database_id represents its related database entry both for creating and patching,// so we should sync its value right here when the related database entry created.// The new statement should include the schema from peer tenant database.- payload.Statement = statement- bytes, err := json.Marshal(payload)- if err != nil {- return true, nil, errors.Wrap(err, "Failed to construct updated task payload")- }- payloadStr := string(bytes)taskDatabaseIDPatch := &api.TaskPatch{ID: task.ID,UpdaterID: api.SystemBotID,DatabaseID: &database.ID,- Payload: &payloadStr,+ Statement: &statement,}if _, err := exec.store.PatchTask(ctx, taskDatabaseIDPatch); err != nil {return true, nil, errdiff --git a/server/runner/taskrun/scheduler.go b/server/runner/taskrun/scheduler.goindex 876a3f4adb..17d1baffcf 100644--- a/server/runner/taskrun/scheduler.go+++ b/server/runner/taskrun/scheduler.go@@ -5,11 +5,13 @@ import ("context""encoding/json""fmt"+ "net/http""sort""strconv""sync""time"+ "github.com/labstack/echo/v4""github.com/pkg/errors""go.uber.org/zap"@@ -72,6 +74,17 @@ type Scheduler struct {executorMap map[api.TaskType]Executor}+// Register will register a task executor factory.+func (s *Scheduler) Register(taskType api.TaskType, executorGetter Executor) {+ if executorGetter == nil {+ panic("scheduler: Register executor is nil for task type: " + taskType)+ }+ if _, dup := s.executorMap[taskType]; dup {+ panic("scheduler: Register called twice for task type: " + taskType)+ }+ s.executorMap[taskType] = executorGetter+}+// Run will run the task scheduler.func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {ticker := time.NewTicker(taskSchedulerInterval)@@ -270,8 +283,7 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {Code: &code,Result: &result,}- taskPatched, err := s.PatchTaskStatus(ctx, task, taskStatusPatch)- if err != nil {+ if _, err := s.PatchTaskStatus(ctx, task, taskStatusPatch); err != nil {log.Error("Failed to mark task as DONE",zap.Int("id", task.ID),zap.String("name", task.Name),@@ -280,15 +292,15 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {return}- issue, err := s.store.GetIssueByPipelineID(ctx, taskPatched.PipelineID)+ issue, err := s.store.GetIssueByPipelineID(ctx, task.PipelineID)if err != nil {- log.Error("failed to getIssueByPipelineID", zap.Int("pipelineID", taskPatched.PipelineID), zap.Error(err))+ log.Error("failed to getIssueByPipelineID", zap.Int("pipelineID", task.PipelineID), zap.Error(err))return}// The task has finished, and we may move to a new stage.// if the current assignee doesn't fit in the new assignee group, we will reassign a new one based on the new assignee group.if issue != nil {- if stage := utils.GetActiveStage(issue.Pipeline.StageList); stage != nil && stage.ID != taskPatched.StageID {+ if stage := utils.GetActiveStage(issue.Pipeline.StageList); stage != nil && stage.ID != task.StageID {environmentID := stage.EnvironmentIDok, err := s.CanPrincipalBeAssignee(ctx, issue.AssigneeID, environmentID, issue.ProjectID, issue.Type)if err != nil {@@ -325,15 +337,299 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {}}-// Register will register a task executor factory.-func (s *Scheduler) Register(taskType api.TaskType, executorGetter Executor) {- if executorGetter == nil {- panic("scheduler: Register executor is nil for task type: " + taskType)+// PatchTaskStatement patches the statement and earliest allowed time for a patch.+func (s *Scheduler) PatchTaskStatement(ctx context.Context, task *api.Task, taskPatch *api.TaskPatch, issue *api.Issue) (*api.Task, error) {+ if taskPatch.Statement != nil {+ if httpErr := s.canUpdateTaskStatement(ctx, task); httpErr != nil {+ return nil, httpErr+ }+ if issue.Project.WorkflowType == api.UIWorkflow {+ schemaVersion := common.DefaultMigrationVersion()+ taskPatch.SchemaVersion = &schemaVersion+ }}- if _, dup := s.executorMap[taskType]; dup {- panic("scheduler: Register called twice for task type: " + taskType)++ taskPatched, err := s.store.PatchTask(ctx, taskPatch)+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update task \"%v\"", task.Name)).SetInternal(err)+ }+ // Update statement or earliest allowed time, dismiss stale approvals and transfer the status to PendingApproval for Pending tasks.+ // TODO(d): revisit this as task pending is only a short-period of time.+ if taskPatched.Status == api.TaskPending {+ t, err := s.PatchTaskStatus(ctx, taskPatched, &api.TaskStatusPatch{+ IDList: []int{taskPatch.ID},+ UpdaterID: taskPatch.UpdaterID,+ Status: api.TaskPendingApproval,+ })+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to change task status to PendingApproval after updating task: %v", taskPatched.Name)).SetInternal(err)+ }+ taskPatched = t}- s.executorMap[taskType] = executorGetter+ if issue.AssigneeNeedAttention && issue.Project.WorkflowType == api.UIWorkflow {+ needAttention := false+ patch := &api.IssuePatch{+ ID: issue.ID,+ UpdaterID: api.SystemBotID,+ AssigneeNeedAttention: &needAttention,+ }+ if _, err := s.store.PatchIssue(ctx, patch); err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to try to patch issue assignee_need_attention after updating task statement").SetInternal(err)+ }+ }++ // Trigger task checks.+ if taskPatch.Statement != nil {+ // it's ok to fail.+ if err := s.applicationRunner.CancelExternalApproval(ctx, issue.ID, api.ExternalApprovalCancelReasonSQLModified); err != nil {+ log.Error("failed to cancel external approval on SQL modified", zap.Int("issue_id", issue.ID), zap.Error(err))+ }+ if taskPatched.Type == api.TaskDatabaseSchemaUpdateGhostSync {+ if _, err := s.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{+ CreatorID: taskPatched.CreatorID,+ TaskID: task.ID,+ Type: api.TaskCheckGhostSync,+ }); err != nil {+ // It's OK if we failed to trigger a check, just emit an error log+ log.Error("Failed to trigger gh-ost dry run after changing the task statement",+ zap.Int("task_id", task.ID),+ zap.String("task_name", task.Name),+ zap.Error(err),+ )+ }+ }++ if api.IsSyntaxCheckSupported(task.Database.Instance.Engine) {+ payload, err := json.Marshal(api.TaskCheckDatabaseStatementAdvisePayload{+ Statement: *taskPatch.Statement,+ DbType: task.Database.Instance.Engine,+ Charset: taskPatched.Database.CharacterSet,+ Collation: taskPatched.Database.Collation,+ })+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, errors.Wrapf(err, "failed to marshal statement advise payload: %v", task.Name))+ }+ if _, err := s.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{+ CreatorID: api.SystemBotID,+ TaskID: task.ID,+ Type: api.TaskCheckDatabaseStatementSyntax,+ Payload: string(payload),+ }); err != nil {+ // It's OK if we failed to trigger a check, just emit an error log+ log.Error("Failed to trigger syntax check after changing the task statement",+ zap.Int("task_id", task.ID),+ zap.String("task_name", task.Name),+ zap.Error(err),+ )+ }+ }++ if api.IsSQLReviewSupported(task.Database.Instance.Engine) {+ if err := s.triggerDatabaseStatementAdviseTask(ctx, *taskPatch.Statement, taskPatched); err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, errors.Wrap(err, "failed to trigger database statement advise task")).SetInternal(err)+ }+ }++ if api.IsStatementTypeCheckSupported(task.Instance.Engine) {+ payload, err := json.Marshal(api.TaskCheckDatabaseStatementTypePayload{+ Statement: *taskPatch.Statement,+ DbType: task.Instance.Engine,+ Charset: task.Database.CharacterSet,+ Collation: task.Database.Collation,+ })+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, errors.Wrapf(err, "failed to marshal check statement type payload: %v", task.Name))+ }+ if _, err := s.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{+ CreatorID: api.SystemBotID,+ TaskID: task.ID,+ Type: api.TaskCheckDatabaseStatementType,+ Payload: string(payload),+ }); err != nil {+ // It's OK if we failed to trigger a check, just emit an error log+ log.Error("Failed to trigger statement type check after changing the task statement",+ zap.Int("task_id", task.ID),+ zap.String("task_name", task.Name),+ zap.Error(err),+ )+ }+ }+ }++ // Update statement activity.+ if taskPatch.Statement != nil {+ oldStatement, err := utils.GetTaskStatement(task)+ if err != nil {+ return nil, err+ }+ newStatement := *taskPatch.Statement++ // create a task statement update activity+ payload, err := json.Marshal(api.ActivityPipelineTaskStatementUpdatePayload{+ TaskID: taskPatched.ID,+ OldStatement: oldStatement,+ NewStatement: newStatement,+ TaskName: task.Name,+ IssueName: issue.Name,+ })+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity after updating task statement: %v", taskPatched.Name).SetInternal(err)+ }+ if _, err := s.activityManager.CreateActivity(ctx, &api.ActivityCreate{+ CreatorID: taskPatched.CreatorID,+ ContainerID: taskPatched.PipelineID,+ Type: api.ActivityPipelineTaskStatementUpdate,+ Payload: string(payload),+ Level: api.ActivityInfo,+ }, &activity.Metadata{+ Issue: issue,+ }); err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after updating task statement: %v", taskPatched.Name)).SetInternal(err)+ }+ }+ // Earliest allowed time update activity.+ if taskPatch.EarliestAllowedTs != nil {+ // create an activity+ payload, err := json.Marshal(api.ActivityPipelineTaskEarliestAllowedTimeUpdatePayload{+ TaskID: taskPatched.ID,+ OldEarliestAllowedTs: task.EarliestAllowedTs,+ NewEarliestAllowedTs: taskPatched.EarliestAllowedTs,+ TaskName: task.Name,+ IssueName: issue.Name,+ })+ if err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, errors.Wrapf(err, "failed to marshal earliest allowed time activity payload: %v", task.Name))+ }+ activityCreate := &api.ActivityCreate{+ CreatorID: taskPatched.CreatorID,+ ContainerID: taskPatched.PipelineID,+ Type: api.ActivityPipelineTaskEarliestAllowedTimeUpdate,+ Payload: string(payload),+ Level: api.ActivityInfo,+ }+ if _, err := s.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{+ Issue: issue,+ }); err != nil {+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after updating task earliest allowed time: %v", taskPatched.Name)).SetInternal(err)+ }+ }+ return taskPatched, nil+}++func (s *Scheduler) triggerDatabaseStatementAdviseTask(ctx context.Context, statement string, task *api.Task) error {+ policyID, err := s.store.GetSQLReviewPolicyIDByEnvID(ctx, task.Instance.EnvironmentID)+ if err != nil {+ // It's OK if we failed to find the SQL review policy, just emit an error log+ log.Error("Failed to found SQL review policy id for task",+ zap.Int("task_id", task.ID),+ zap.String("task_name", task.Name),+ zap.Int("environment_id", task.Instance.EnvironmentID),+ zap.Error(err),+ )+ return nil+ }++ payload, err := json.Marshal(api.TaskCheckDatabaseStatementAdvisePayload{+ Statement: statement,+ DbType: task.Database.Instance.Engine,+ Charset: task.Database.CharacterSet,+ Collation: task.Database.Collation,+ PolicyID: policyID,+ })+ if err != nil {+ return errors.Wrapf(err, "failed to marshal statement advise payload: %v", task.Name)+ }++ if _, err := s.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{+ CreatorID: api.SystemBotID,+ TaskID: task.ID,+ Type: api.TaskCheckDatabaseStatementAdvise,+ Payload: string(payload),+ }); err != nil {+ // It's OK if we failed to trigger a check, just emit an error log+ log.Error("Failed to trigger statement advise task after changing task statement",+ zap.Int("task_id", task.ID),+ zap.String("task_name", task.Name),+ zap.Error(err),+ )+ }++ return nil+}++// CanPrincipalChangeTaskStatus validates if the principal has the privilege to update task status, judging from the principal role and the environment policy.+func (s *Scheduler) CanPrincipalChangeTaskStatus(ctx context.Context, principalID int, task *api.Task, toStatus api.TaskStatus) (bool, error) {+ // The creator can cancel task.+ if toStatus == api.TaskCanceled {+ if principalID == task.CreatorID {+ return true, nil+ }+ }+ // the workspace owner and DBA roles can always change task status.+ principal, err := s.store.GetPrincipalByID(ctx, principalID)+ if err != nil {+ return false, common.Wrapf(err, common.Internal, "failed to get principal by ID %d", principalID)+ }+ if principal == nil {+ return false, common.Errorf(common.NotFound, "principal not found by ID %d", principalID)+ }+ if principal.Role == api.Owner || principal.Role == api.DBA {+ return true, nil+ }++ issue, err := s.store.GetIssueByPipelineID(ctx, task.PipelineID)+ if err != nil {+ return false, common.Wrapf(err, common.Internal, "failed to find issue")+ }+ if issue == nil {+ return false, common.Errorf(common.NotFound, "issue not found by pipeline ID: %d", task.PipelineID)+ }+ groupValue, err := s.getGroupValueForTask(ctx, issue, task)+ if err != nil {+ return false, common.Wrapf(err, common.Internal, "failed to get assignee group value for taskID %d", task.ID)+ }+ if groupValue == nil {+ return false, nil+ }+ // as the policy says, the project owner has the privilege to change task status.+ if *groupValue == api.AssigneeGroupValueProjectOwner {+ member, err := s.store.GetProjectMember(ctx, &api.ProjectMemberFind{+ ProjectID: &issue.ProjectID,+ PrincipalID: &principalID,+ })+ if err != nil {+ return false, common.Wrapf(err, common.Internal, "failed to get project member by projectID %d, principalID %d", issue.ProjectID, principalID)+ }+ if member != nil && member.Role == string(api.Owner) {+ return true, nil+ }+ }+ return false, nil+}++func (s *Scheduler) getGroupValueForTask(ctx context.Context, issue *api.Issue, task *api.Task) (*api.AssigneeGroupValue, error) {+ environmentID := api.UnknownID+ for _, stage := range issue.Pipeline.StageList {+ if stage.ID == task.StageID {+ environmentID = stage.EnvironmentID+ break+ }+ }+ if environmentID == api.UnknownID {+ return nil, common.Errorf(common.NotFound, "failed to find environmentID by task.StageID %d", task.StageID)+ }++ policy, err := s.store.GetPipelineApprovalPolicy(ctx, environmentID)+ if err != nil {+ return nil, common.Wrapf(err, common.Internal, "failed to get pipeline approval policy by environmentID %d", environmentID)+ }++ for _, assigneeGroup := range policy.AssigneeGroupList {+ if assigneeGroup.IssueType == issue.Type {+ return &assigneeGroup.Value, nil+ }+ }+ return nil, nil}// ClearRunningTasks changes all RUNNING tasks to CANCELED.@@ -385,6 +681,37 @@ func (s *Scheduler) ClearRunningTasks(ctx context.Context) error {return nil}+var allowedStatementUpdateTaskTypes = map[api.TaskType]bool{+ api.TaskDatabaseCreate: true,+ api.TaskDatabaseSchemaUpdate: true,+ api.TaskDatabaseSchemaUpdateSDL: true,+ api.TaskDatabaseDataUpdate: true,+ api.TaskDatabaseSchemaUpdateGhostSync: true,+}++func (s *Scheduler) canUpdateTaskStatement(ctx context.Context, task *api.Task) *echo.HTTPError {+ if ok := allowedStatementUpdateTaskTypes[task.Type]; !ok {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("cannot update statement for task type %q", task.Type))+ }+ // Allow frontend to change the SQL statement of+ // 1. a PendingApproval task which hasn't started yet+ // 2. a Failed task which can be retried+ // 3. a Pending task which can't be scheduled because of failed task checks, task dependency or earliest allowed time+ if task.Status != api.TaskPendingApproval && task.Status != api.TaskFailed && task.Status != api.TaskPending {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("cannot update task in %q state", task.Status))+ }+ if task.Status == api.TaskPending {+ ok, err := s.CanSchedule(ctx, task)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "failed to check whether the task can be scheduled").SetInternal(err)+ }+ if ok {+ return echo.NewHTTPError(http.StatusBadRequest, "cannot update the PENDING task because it can be running at any time")+ }+ }+ return nil+}+func (s *Scheduler) passAllCheck(ctx context.Context, task *api.Task, allowedStatus api.TaskCheckStatus) (bool, error) {// schema update, data update and gh-ost sync task have required task check.if task.Type == api.TaskDatabaseSchemaUpdate || task.Type == api.TaskDatabaseSchemaUpdateSDL || task.Type == api.TaskDatabaseDataUpdate || task.Type == api.TaskDatabaseSchemaUpdateGhostSync {diff --git a/server/stage.go b/server/stage.goindex 7a6810d778..bf496dca70 100644--- a/server/stage.go+++ b/server/stage.go@@ -56,7 +56,7 @@ func (s *Server) registerStageRoutes(g *echo.Group) {// pick any task in the stage to validate// because all tasks in the same stage share the issue & environment.- ok, err := s.canPrincipalChangeTaskStatus(ctx, currentPrincipalID, tasks[0], stageAllTaskStatusPatch.Status)+ ok, err := s.TaskScheduler.CanPrincipalChangeTaskStatus(ctx, currentPrincipalID, tasks[0], stageAllTaskStatusPatch.Status)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to validate if the principal can change task status").SetInternal(err)}diff --git a/server/task.go b/server/task.goindex 8e3eb231c8..256f34afed 100644--- a/server/task.go+++ b/server/task.go@@ -1,43 +1,17 @@package serverimport (- "context"- "encoding/json""fmt""net/http""strconv""github.com/google/jsonapi""github.com/labstack/echo/v4"- "github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"- "github.com/bytebase/bytebase/common/log"- "github.com/bytebase/bytebase/server/component/activity")-func (s *Server) canUpdateTaskStatement(ctx context.Context, task *api.Task) *echo.HTTPError {- // Allow frontend to change the SQL statement of- // 1. a PendingApproval task which hasn't started yet- // 2. a Failed task which can be retried- // 3. a Pending task which can't be scheduled because of failed task checks, task dependency or earliest allowed time- if task.Status != api.TaskPendingApproval && task.Status != api.TaskFailed && task.Status != api.TaskPending {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("cannot update task in %q state", task.Status))- }- if task.Status == api.TaskPending {- ok, err := s.TaskScheduler.CanSchedule(ctx, task)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "failed to check whether the task can be scheduled").SetInternal(err)- }- if ok {- return echo.NewHTTPError(http.StatusBadRequest, "cannot update the PENDING task because it can be running at any time")- }- }- return nil-}-func (s *Server) registerTaskRoutes(g *echo.Group) {g.PATCH("/pipeline/:pipelineID/task/all", func(c echo.Context) error {ctx := c.Request().Context()@@ -65,23 +39,12 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Issue not found with pipelineID: %d", pipelineID))}- if taskPatch.Statement != nil {- // check if all tasks can update statement- for _, stage := range issue.Pipeline.StageList {- for _, task := range stage.TaskList {- if httpErr := s.canUpdateTaskStatement(ctx, task); httpErr != nil {- return httpErr- }- }- }- }-var taskPatchedList []*api.Taskfor _, stage := range issue.Pipeline.StageList {for _, task := range stage.TaskList {taskPatch := *taskPatchtaskPatch.ID = task.ID- taskPatched, httpErr := s.patchTask(ctx, task, &taskPatch, issue)+ taskPatched, httpErr := s.TaskScheduler.PatchTaskStatement(ctx, task, &taskPatch, issue)if httpErr != nil {return httpErr}@@ -137,7 +100,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {}}- taskPatched, httpErr := s.patchTask(ctx, task, taskPatch, issue)+ taskPatched, httpErr := s.TaskScheduler.PatchTaskStatement(ctx, task, taskPatch, issue)if httpErr != nil {return httpErr}@@ -173,7 +136,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Task not found with ID %d", taskID))}- ok, err := s.canPrincipalChangeTaskStatus(ctx, currentPrincipalID, task, taskStatusPatch.Status)+ ok, err := s.TaskScheduler.CanPrincipalChangeTaskStatus(ctx, currentPrincipalID, task, taskStatusPatch.Status)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to validate if the principal can change task status").SetInternal(err)}@@ -226,406 +189,3 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {return nil})}--func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.TaskPatch, issue *api.Issue) (*api.Task, *echo.HTTPError) {- var oldStatement string- var newStatement string- if taskPatch.Statement != nil {- if httpErr := s.canUpdateTaskStatement(ctx, task); httpErr != nil {- return nil, httpErr- }- newStatement = *taskPatch.Statement-- switch task.Type {- case api.TaskDatabaseSchemaUpdate:- payload := &api.TaskDatabaseSchemaUpdatePayload{}- if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- return nil, echo.NewHTTPError(http.StatusBadRequest, "Malformed database schema update payload").SetInternal(err)- }- oldStatement = payload.Statement- payload.Statement = *taskPatch.Statement- // 1. For VCS workflows, patchTask only happens when we modify the same file.- // In that case, we want to use the same schema version parsed from the file name.- // The task executor will force retry using the new SQL statement.- // 2. We should update the schema version if we've updated the SQL in the UI workflow, otherwise we will- // get migration history version conflict if the previous task has been attempted.- if issue.Project.WorkflowType == api.UIWorkflow {- payload.SchemaVersion = common.DefaultMigrationVersion()- }- bytes, err := json.Marshal(payload)- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct updated task payload").SetInternal(err)- }- payloadStr := string(bytes)- taskPatch.Payload = &payloadStr- case api.TaskDatabaseSchemaUpdateSDL:- payload := &api.TaskDatabaseSchemaUpdateSDLPayload{}- if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- return nil, echo.NewHTTPError(http.StatusBadRequest, "Malformed database schema update sdl payload").SetInternal(err)- }- oldStatement = payload.Statement- payload.Statement = *taskPatch.Statement- // 1. For VCS workflows, patchTask only happens when we modify the same file.- // In that case, we want to use the same schema version parsed from the file name.- // The task executor will force retry using the new SQL statement.- // 2. We should update the schema version if we've updated the SQL in the UI workflow, otherwise we will- // get migration history version conflict if the previous task has been attempted.- if issue.Project.WorkflowType == api.UIWorkflow {- payload.SchemaVersion = common.DefaultMigrationVersion()- }- bytes, err := json.Marshal(payload)- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct updated task payload").SetInternal(err)- }- payloadStr := string(bytes)- taskPatch.Payload = &payloadStr- case api.TaskDatabaseDataUpdate:- payload := &api.TaskDatabaseDataUpdatePayload{}- if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- return nil, echo.NewHTTPError(http.StatusBadRequest, "Malformed database data update payload").SetInternal(err)- }- oldStatement = payload.Statement- payload.Statement = *taskPatch.Statement- // 1. For VCS workflows, patchTask only happens when we modify the same file.- // In that case, we want to use the same schema version parsed from the file name.- // The task executor will force retry using the new SQL statement.- // 2. We should update the schema version if we've updated the SQL in the UI workflow, otherwise we will- // get migration history version conflict if the previous task has been attempted.- if issue.Project.WorkflowType == api.UIWorkflow {- payload.SchemaVersion = common.DefaultMigrationVersion()- }- bytes, err := json.Marshal(payload)- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct updated task payload").SetInternal(err)- }- payloadStr := string(bytes)- taskPatch.Payload = &payloadStr- case api.TaskDatabaseCreate:- payload := &api.TaskDatabaseCreatePayload{}- if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- return nil, echo.NewHTTPError(http.StatusBadRequest, "Malformed database create payload").SetInternal(err)- }- oldStatement = payload.Statement- payload.Statement = *taskPatch.Statement- bytes, err := json.Marshal(payload)- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct updated task payload").SetInternal(err)- }- payloadStr := string(bytes)- taskPatch.Payload = &payloadStr- case api.TaskDatabaseSchemaUpdateGhostSync:- payload := &api.TaskDatabaseSchemaUpdateGhostSyncPayload{}- if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- return nil, echo.NewHTTPError(http.StatusBadRequest, "Malformed database data update payload").SetInternal(err)- }- oldStatement = payload.Statement- payload.Statement = *taskPatch.Statement- // We should update the schema version if we've updated the SQL, otherwise we will- // get migration history version conflict if the previous task has been attempted.- payload.SchemaVersion = common.DefaultMigrationVersion()- bytes, err := json.Marshal(payload)- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct updated task payload").SetInternal(err)- }- payloadStr := string(bytes)- taskPatch.Payload = &payloadStr- }- }-- taskPatched, err := s.store.PatchTask(ctx, taskPatch)- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update task \"%v\"", task.Name)).SetInternal(err)- }-- // create an activity and trigger task check for statement update- if oldStatement != newStatement {- // it's ok to fail.- if err := s.ApplicationRunner.CancelExternalApproval(ctx, issue.ID, api.ExternalApprovalCancelReasonSQLModified); err != nil {- log.Error("failed to cancel external approval on SQL modified", zap.Int("issue_id", issue.ID), zap.Error(err))- }-- if issue.AssigneeNeedAttention && issue.Project.WorkflowType == api.UIWorkflow {- needAttention := false- patch := &api.IssuePatch{- ID: issue.ID,- UpdaterID: api.SystemBotID,- AssigneeNeedAttention: &needAttention,- }- if _, err := s.store.PatchIssue(ctx, patch); err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to try to patch issue assignee_need_attention after updating task statement").SetInternal(err)- }- }-- if taskPatched.Type == api.TaskDatabaseSchemaUpdate || taskPatched.Type == api.TaskDatabaseSchemaUpdateSDL || taskPatched.Type == api.TaskDatabaseDataUpdate || taskPatched.Type == api.TaskDatabaseSchemaUpdateGhostSync {- // create a task statement update activity- payload, err := json.Marshal(api.ActivityPipelineTaskStatementUpdatePayload{- TaskID: taskPatched.ID,- OldStatement: oldStatement,- NewStatement: newStatement,- TaskName: task.Name,- IssueName: issue.Name,- })- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity after updating task statement: %v", taskPatched.Name).SetInternal(err)- }-- if _, err = s.ActivityManager.CreateActivity(ctx, &api.ActivityCreate{- CreatorID: taskPatched.CreatorID,- ContainerID: taskPatched.PipelineID,- Type: api.ActivityPipelineTaskStatementUpdate,- Payload: string(payload),- Level: api.ActivityInfo,- }, &activity.Metadata{- Issue: issue,- }); err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after updating task statement: %v", taskPatched.Name)).SetInternal(err)- }-- // updated statement, dismiss stale approvals and transfer the status to PendingApproval for Pending tasks.- if taskPatched.Status == api.TaskPending {- t, err := s.TaskScheduler.PatchTaskStatus(ctx, taskPatched, &api.TaskStatusPatch{- IDList: []int{taskPatch.ID},- UpdaterID: taskPatch.UpdaterID,- Status: api.TaskPendingApproval,- })- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to change task status to PendingApproval after updating task: %v", taskPatched.Name)).SetInternal(err)- }- taskPatched = t- }-- if taskPatched.Type == api.TaskDatabaseSchemaUpdateGhostSync {- _, err = s.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{- CreatorID: taskPatched.CreatorID,- TaskID: task.ID,- Type: api.TaskCheckGhostSync,- })- if err != nil {- // It's OK if we failed to trigger a check, just emit an error log- log.Error("Failed to trigger gh-ost dry run after changing the task statement",- zap.Int("task_id", task.ID),- zap.String("task_name", task.Name),- zap.Error(err),- )- }- }-- if api.IsSyntaxCheckSupported(task.Database.Instance.Engine) {- payload, err := json.Marshal(api.TaskCheckDatabaseStatementAdvisePayload{- Statement: *taskPatch.Statement,- DbType: task.Database.Instance.Engine,- Charset: taskPatched.Database.CharacterSet,- Collation: taskPatched.Database.Collation,- })- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, errors.Wrapf(err, "failed to marshal statement advise payload: %v", task.Name))- }- _, err = s.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{- CreatorID: api.SystemBotID,- TaskID: task.ID,- Type: api.TaskCheckDatabaseStatementSyntax,- Payload: string(payload),- })- if err != nil {- // It's OK if we failed to trigger a check, just emit an error log- log.Error("Failed to trigger syntax check after changing the task statement",- zap.Int("task_id", task.ID),- zap.String("task_name", task.Name),- zap.Error(err),- )- }- }-- if api.IsSQLReviewSupported(task.Database.Instance.Engine) {- if err := s.triggerDatabaseStatementAdviseTask(ctx, *taskPatch.Statement, taskPatched); err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, errors.Wrap(err, "failed to trigger database statement advise task")).SetInternal(err)- }- }-- if api.IsStatementTypeCheckSupported(task.Instance.Engine) {- payload, err := json.Marshal(api.TaskCheckDatabaseStatementTypePayload{- Statement: *taskPatch.Statement,- DbType: task.Instance.Engine,- Charset: task.Database.CharacterSet,- Collation: task.Database.Collation,- })- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, errors.Wrapf(err, "failed to marshal check statement type payload: %v", task.Name))- }- if _, err := s.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{- CreatorID: api.SystemBotID,- TaskID: task.ID,- Type: api.TaskCheckDatabaseStatementType,- Payload: string(payload),- }); err != nil {- // It's OK if we failed to trigger a check, just emit an error log- log.Error("Failed to trigger statement type check after changing the task statement",- zap.Int("task_id", task.ID),- zap.String("task_name", task.Name),- zap.Error(err),- )- }- }- }- }-- // earliest allowed time update.- // - create an activity.- // - dismiss stale approval for Pending tasks.- if taskPatched.EarliestAllowedTs != task.EarliestAllowedTs {- // create an activity-- payload, err := json.Marshal(api.ActivityPipelineTaskEarliestAllowedTimeUpdatePayload{- TaskID: taskPatched.ID,- OldEarliestAllowedTs: task.EarliestAllowedTs,- NewEarliestAllowedTs: taskPatched.EarliestAllowedTs,- TaskName: task.Name,- IssueName: issue.Name,- })- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, errors.Wrapf(err, "failed to marshal earliest allowed time activity payload: %v", task.Name))- }- activityCreate := &api.ActivityCreate{- CreatorID: taskPatched.CreatorID,- ContainerID: taskPatched.PipelineID,- Type: api.ActivityPipelineTaskEarliestAllowedTimeUpdate,- Payload: string(payload),- Level: api.ActivityInfo,- }- if _, err := s.ActivityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{- Issue: issue,- }); err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after updating task earliest allowed time: %v", taskPatched.Name)).SetInternal(err)- }-- // updated earliest allowed time, dismiss stale approvals and transfer the status to PendingApproval for Pending tasks.- if taskPatched.Status == api.TaskPending {- t, err := s.TaskScheduler.PatchTaskStatus(ctx, taskPatched, &api.TaskStatusPatch{- IDList: []int{taskPatch.ID},- UpdaterID: taskPatch.UpdaterID,- Status: api.TaskPendingApproval,- })- if err != nil {- return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to change task status to PendingApproval after updating task: %v", taskPatched.Name)).SetInternal(err)- }- taskPatched = t- }- }- return taskPatched, nil-}--// canPrincipalChangeTaskStatus validates if the principal has the privilege to update task status, judging from the principal role and the environment policy.-func (s *Server) canPrincipalChangeTaskStatus(ctx context.Context, principalID int, task *api.Task, toStatus api.TaskStatus) (bool, error) {- // The creator can cancel task.- if toStatus == api.TaskCanceled {- if principalID == task.CreatorID {- return true, nil- }- }- // the workspace owner and DBA roles can always change task status.- principal, err := s.store.GetPrincipalByID(ctx, principalID)- if err != nil {- return false, common.Wrapf(err, common.Internal, "failed to get principal by ID %d", principalID)- }- if principal == nil {- return false, common.Errorf(common.NotFound, "principal not found by ID %d", principalID)- }- if principal.Role == api.Owner || principal.Role == api.DBA {- return true, nil- }-- issue, err := s.store.GetIssueByPipelineID(ctx, task.PipelineID)- if err != nil {- return false, common.Wrapf(err, common.Internal, "failed to find issue")- }- if issue == nil {- return false, common.Errorf(common.NotFound, "issue not found by pipeline ID: %d", task.PipelineID)- }- groupValue, err := s.getGroupValueForTask(ctx, issue, task)- if err != nil {- return false, common.Wrapf(err, common.Internal, "failed to get assignee group value for taskID %d", task.ID)- }- if groupValue == nil {- return false, nil- }- // as the policy says, the project owner has the privilege to change task status.- if *groupValue == api.AssigneeGroupValueProjectOwner {- member, err := s.store.GetProjectMember(ctx, &api.ProjectMemberFind{- ProjectID: &issue.ProjectID,- PrincipalID: &principalID,- })- if err != nil {- return false, common.Wrapf(err, common.Internal, "failed to get project member by projectID %d, principalID %d", issue.ProjectID, principalID)- }- if member != nil && member.Role == string(api.Owner) {- return true, nil- }- }- return false, nil-}--func (s *Server) getGroupValueForTask(ctx context.Context, issue *api.Issue, task *api.Task) (*api.AssigneeGroupValue, error) {- environmentID := api.UnknownID- for _, stage := range issue.Pipeline.StageList {- if stage.ID == task.StageID {- environmentID = stage.EnvironmentID- break- }- }- if environmentID == api.UnknownID {- return nil, common.Errorf(common.NotFound, "failed to find environmentID by task.StageID %d", task.StageID)- }-- policy, err := s.store.GetPipelineApprovalPolicy(ctx, environmentID)- if err != nil {- return nil, common.Wrapf(err, common.Internal, "failed to get pipeline approval policy by environmentID %d", environmentID)- }-- for _, assigneeGroup := range policy.AssigneeGroupList {- if assigneeGroup.IssueType == issue.Type {- return &assigneeGroup.Value, nil- }- }- return nil, nil-}--func (s *Server) triggerDatabaseStatementAdviseTask(ctx context.Context, statement string, task *api.Task) error {- policyID, err := s.store.GetSQLReviewPolicyIDByEnvID(ctx, task.Instance.EnvironmentID)- if err != nil {- // It's OK if we failed to find the SQL review policy, just emit an error log- log.Error("Failed to found SQL review policy id for task",- zap.Int("task_id", task.ID),- zap.String("task_name", task.Name),- zap.Int("environment_id", task.Instance.EnvironmentID),- zap.Error(err),- )- return nil- }-- payload, err := json.Marshal(api.TaskCheckDatabaseStatementAdvisePayload{- Statement: statement,- DbType: task.Database.Instance.Engine,- Charset: task.Database.CharacterSet,- Collation: task.Database.Collation,- PolicyID: policyID,- })- if err != nil {- return errors.Wrapf(err, "failed to marshal statement advise payload: %v", task.Name)- }-- if _, err := s.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{- CreatorID: api.SystemBotID,- TaskID: task.ID,- Type: api.TaskCheckDatabaseStatementAdvise,- Payload: string(payload),- }); err != nil {- // It's OK if we failed to trigger a check, just emit an error log- log.Error("Failed to trigger statement advise task after changing task statement",- zap.Int("task_id", task.ID),- zap.String("task_name", task.Name),- zap.Error(err),- )- }-- return nil-}diff --git a/server/utils/utils.go b/server/utils/utils.goindex 38c63c6f20..076346231a 100644--- a/server/utils/utils.go+++ b/server/utils/utils.go@@ -413,3 +413,14 @@ func RefreshToken(ctx context.Context, store *store.Store, webURL string) commonreturn err}}++// GetTaskStatement gets the statement of a task.+func GetTaskStatement(task *api.Task) (string, error) {+ var taskStatement struct {+ Statement string `json:"statement"`+ }+ if err := json.Unmarshal([]byte(task.Payload), &taskStatement); err != nil {+ return "", err+ }+ return taskStatement.Statement, nil+}diff --git a/server/webhook.go b/server/webhook.goindex 9352cc1edc..805d83ac15 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -1186,7 +1186,7 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [}// TODO(dragonly): Try to patch the failed migration history record to pending, and the statement to the current modified file content.log.Debug("Patching task for modified file VCS push event", zap.String("fileName", fileName), zap.Int("issueID", issue.ID), zap.Int("taskID", task.ID))- if _, err := s.patchTask(ctx, task, &taskPatch, issue); err != nil {+ if _, err := s.TaskScheduler.PatchTaskStatement(ctx, task, &taskPatch, issue); err != nil {log.Error("Failed to patch task with the same migration version", zap.Int("issueID", issue.ID), zap.Int("taskID", task.ID), zap.Error(err))return nil}diff --git a/store/task.go b/store/task.goindex 32050be966..8fbd128097 100644--- a/store/task.go+++ b/store/task.go@@ -650,6 +650,15 @@ func (*Store) patchTaskImpl(ctx context.Context, tx *Tx, patch *api.TaskPatch) (if v := patch.DatabaseID; v != nil {set, args = append(set, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, *v)}+ if (patch.Statement != nil || patch.SchemaVersion != nil) && patch.Payload != nil {+ return nil, errors.Errorf("cannot set both statement/schemaVersion and payload for TaskPatch")+ }+ if v := patch.Statement; v != nil {+ set, args = append(set, fmt.Sprintf(`payload['statement'] = to_json($%d::TEXT)`, len(args)+1)), append(args, *v)+ }+ if v := patch.SchemaVersion; v != nil {+ set, args = append(set, fmt.Sprintf(`payload['schemaVersion'] = to_json($%d::TEXT)`, len(args)+1)), append(args, *v)+ }if v := patch.Payload; v != nil {payload := "{}"if *v != "" {