Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(backend): manually trigger external approval with assignee need attention (#3699)
p0ny5b8951f472b0
diff --git a/api/issue.go b/api/issue.goindex ee49ac274a..0c033da6d2 100644--- a/api/issue.go+++ b/api/issue.go@@ -272,10 +272,11 @@ type IssuePatch struct {// Domain specific fieldsName *string `jsonapi:"attr,name"`// Status is only set manually via IssueStatusPatch- Status *IssueStatus- Description *string `jsonapi:"attr,description"`- AssigneeID *int `jsonapi:"attr,assigneeId"`- Payload *string `jsonapi:"attr,payload"`+ Status *IssueStatus+ Description *string `jsonapi:"attr,description"`+ AssigneeID *int `jsonapi:"attr,assigneeId"`+ AssigneeNeedAttention *bool `jsonapi:"attr,assigneeNeedAttention"`+ Payload *string `jsonapi:"attr,payload"`}// IssueStatusPatch is the API message for patching status of an issue.diff --git a/server/application_runner.go b/server/application_runner.goindex 09edf8ceda..d97109a9a3 100644--- a/server/application_runner.go+++ b/server/application_runner.go@@ -21,13 +21,15 @@ const (applicationRunnerInterval = time.Duration(60) * time.Second// externalApprovalCancelReasonGeneral is the general reason, used as a default.- externalApprovalCancelReasonGeneral string = "Canceled because the assignee has been changed, or all tasks of the stage have been approved or the issue is no longer open."+ externalApprovalCancelReasonGeneral string = "Canceled because the assignee has been changed, or the SQL has been modified, or all tasks of the stage have been approved or the issue is no longer open."// externalApprovalCancelReasonIssueNotOpen is used if the issue is not open.externalApprovalCancelReasonIssueNotOpen string = "Canceled because the containing issue is no longer open."// externalApprovalCancelReasonReassigned is used if the assignee has been changed.externalApprovalCancelReasonReassigned string = "Canceled because the assignee has changed."+ // externalApprovalCancelReasonSQLModified is used if the task SQL statement has been modified.+ externalApprovalCancelReasonSQLModified string = "Canceled because the SQL has been modified."// externalApprovalCancelReasonNoTaskPendingApproval is used if there is no pending approval tasks.- externalApprovalCancelReasonNoTaskPendingApproval string = "Canceled because all tasks have benn approved."+ externalApprovalCancelReasonNoTaskPendingApproval string = "Canceled because all tasks have been approved.")// NewApplicationRunner returns a ApplicationRunner.diff --git a/server/issue.go b/server/issue.goindex a16a23704e..3fbaedfa8a 100644--- a/server/issue.go+++ b/server/issue.go@@ -14,9 +14,11 @@ import ("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/plugin/db""github.com/bytebase/bytebase/plugin/db/util""github.com/bytebase/bytebase/plugin/vcs"@@ -25,15 +27,13 @@ import (func (s *Server) registerIssueRoutes(g *echo.Group) {g.POST("/issue", func(c echo.Context) error {ctx := c.Request().Context()- issueCreate := &api.IssueCreate{}+ issueCreate := &api.IssueCreate{+ CreatorID: c.Get(getPrincipalIDContextKey()).(int),+ }if err := jsonapi.UnmarshalPayload(c.Request().Body, issueCreate); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed create issue request").SetInternal(err)}- issueCreate.CreatorID = c.Get(getPrincipalIDContextKey()).(int)- // TODO(p0ny): remove this line when manually sending external approval is ready. This is to temporarily keep our auto sending behaviour.- issueCreate.AssigneeNeedAttention = true-issue, err := s.createIssue(ctx, issueCreate)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create issue").SetInternal(err)@@ -180,6 +180,10 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Malformed update issue request").SetInternal(err)}+ if issuePatch.AssigneeNeedAttention != nil && !*issuePatch.AssigneeNeedAttention {+ return echo.NewHTTPError(http.StatusBadRequest, "Cannot set assigneeNeedAttention to false")+ }+issue, err := s.store.GetIssueByID(ctx, id)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch issue ID when updating issue: %v", id)).SetInternal(err)@@ -189,6 +193,9 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {}if issuePatch.AssigneeID != nil {+ if *issuePatch.AssigneeID == issue.AssigneeID {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Cannot set assignee with user id %d because it's already the case", *issuePatch.AssigneeID))+ }stage := getActiveStage(issue.Pipeline.StageList)if stage == nil {// all stages have finished, use the last stage@@ -201,6 +208,12 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {if !ok {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Cannot set assignee with user id %d", *issuePatch.AssigneeID)).SetInternal(err)}++ // set AssigneeNeedAttention to false on assignee change+ if issue.Project.WorkflowType == api.UIWorkflow {+ needAttention := false+ issuePatch.AssigneeNeedAttention = &needAttention+ }}updatedIssue, err := s.store.PatchIssue(ctx, issuePatch)@@ -208,6 +221,13 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update issue with ID %d", id)).SetInternal(err)}+ // cancel external approval on assignee change+ if issuePatch.AssigneeID != nil {+ if err := s.ApplicationRunner.CancelExternalApproval(ctx, issue.ID, externalApprovalCancelReasonReassigned); err != nil {+ log.Error("failed to cancel external approval on assignee change", zap.Int("issue_id", issue.ID), zap.Error(err))+ }+ }+payloadList := [][]byte{}if issuePatch.Name != nil && *issuePatch.Name != issue.Name {payload, err := json.Marshal(api.ActivityIssueFieldUpdatePayload{diff --git a/server/task.go b/server/task.goindex 9d8d4447cd..a1b395537c 100644--- a/server/task.go+++ b/server/task.go@@ -154,11 +154,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {if taskPatch.Statement != nil {// Tenant mode project don't allow updating SQL statement for a single task.- project, err := s.store.GetProjectByID(ctx, issue.ProjectID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project with ID: %d", issue.ProjectID)).SetInternal(err)- }- if project.TenantMode == api.TenantModeTenant && (task.Type == api.TaskDatabaseSchemaUpdate || task.Type == api.TaskDatabaseSchemaUpdateSDL) {+ if issue.Project.TenantMode == api.TenantModeTenant && (task.Type == api.TaskDatabaseSchemaUpdate || task.Type == api.TaskDatabaseSchemaUpdateSDL) {return echo.NewHTTPError(http.StatusBadRequest, "cannot update SQL statement of a single task for projects in tenant mode")}}@@ -364,13 +360,25 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.T}// create an activity and trigger task check for statement update- if taskPatched.Type == api.TaskDatabaseSchemaUpdate || taskPatched.Type == api.TaskDatabaseSchemaUpdateSDL || taskPatched.Type == api.TaskDatabaseDataUpdate || taskPatched.Type == api.TaskDatabaseSchemaUpdateGhostSync {- if oldStatement != newStatement {- if issue == nil {- err := errors.Errorf("issue not found with pipeline ID %v", task.PipelineID)- return nil, echo.NewHTTPError(http.StatusNotFound, err).SetInternal(err)+ if oldStatement != newStatement {+ // it's ok to fail.+ if err := s.ApplicationRunner.CancelExternalApproval(ctx, issue.ID, 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 activitypayload, err := json.Marshal(api.ActivityPipelineTaskStatementUpdatePayload{TaskID: taskPatched.ID,@@ -488,10 +496,6 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.T// - dismiss stale approval for Pending tasks.if taskPatched.EarliestAllowedTs != task.EarliestAllowedTs {// create an activity- if issue == nil {- err := errors.Errorf("issue not found with pipeline ID %v", task.PipelineID)- return nil, echo.NewHTTPError(http.StatusNotFound, err.Error()).SetInternal(err)- }payload, err := json.Marshal(api.ActivityPipelineTaskEarliestAllowedTimeUpdatePayload{TaskID: taskPatched.ID,diff --git a/server/task_scheduler.go b/server/task_scheduler.goindex f7b580822b..19cdbcebdf 100644--- a/server/task_scheduler.go+++ b/server/task_scheduler.go@@ -685,6 +685,45 @@ func (s *TaskScheduler) patchTaskStatus(ctx context.Context, task *api.Task, tas}}+ // If every task in the stage completes, it means that we are moving into a new stage. We need+ // 1. cancel external approval.+ // 2. for UI workflow, set issue.AssigneeNeedAttention to false.+ if taskPatched.Status == api.TaskDone && issue != nil {+ foundStage := false+ stageTaskAllDone := true+ for _, stage := range issue.Pipeline.StageList {+ if stage.ID == taskPatched.StageID {+ foundStage = true+ for _, task := range stage.TaskList {+ if task.Status != api.TaskDone {+ stageTaskAllDone = false+ break+ }+ }+ break+ }+ }+ // every task in the stage completes+ if foundStage && stageTaskAllDone {+ // Cancel external approval, it's ok if we failed.+ if err := s.applicationRunner.CancelExternalApproval(ctx, issue.ID, externalApprovalCancelReasonNoTaskPendingApproval); err != nil {+ log.Error("failed to cancel external approval on stage tasks completion", zap.Int("issue_id", issue.ID), zap.Error(err))+ }++ if 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, errors.Wrapf(err, "failed to patch issue assigneeNeedAttention after completing the whole stage, issuePatch: %+v", patch)+ }+ }+ }+ }+// If every task in the pipeline completes, and the assignee is system bot:// Case 1: If the task is associated with an issue, then we mark the issue (including the pipeline) as DONE.// Case 2: If the task is NOT associated with an issue, then we mark the pipeline as DONE.@@ -965,6 +1004,11 @@ func (s *TaskScheduler) changeIssueStatus(ctx context.Context, issue *api.Issue,UpdaterID: updaterID,Status: &newStatus,}+ if newStatus != api.IssueOpen && issue.Project.WorkflowType == api.UIWorkflow {+ // for UI workflow, set assigneeNeedAttention to false if we are closing the issue.+ needAttention := false+ issuePatch.AssigneeNeedAttention = &needAttention+ }updatedIssue, err := s.store.PatchIssue(ctx, issuePatch)if err != nil {return nil, errors.Wrapf(err, "failed to update issue %q's status with patch %v", issue.Name, issuePatch)diff --git a/server/webhook.go b/server/webhook.goindex 3121b6f170..624b6e0565 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -1175,7 +1175,11 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [}issue, err := s.store.GetIssueByPipelineID(ctx, task.PipelineID)if err != nil {- log.Error(fmt.Sprintf("Failed to get issue by pipeline ID %d", task.PipelineID), zap.Error(err))+ log.Error("failed to get issue by pipeline ID", zap.Int("pipeline ID", task.PipelineID), zap.Error(err))+ return nil+ }+ if issue == nil {+ log.Error("issue not found by pipeline ID", zap.Int("pipeline ID", task.PipelineID), zap.Error(err))return nil}// TODO(dragonly): Try to patch the failed migration history record to pending, and the statement to the current modified file content.diff --git a/store/issue.go b/store/issue.goindex 44d22f8caf..ee5c9066ce 100644--- a/store/issue.go+++ b/store/issue.go@@ -757,6 +757,9 @@ func (*Store) patchIssueImpl(ctx context.Context, tx *Tx, patch *api.IssuePatch)if v := patch.AssigneeID; v != nil {set, args = append(set, fmt.Sprintf("assignee_id = $%d", len(args)+1)), append(args, *v)}+ if v := patch.AssigneeNeedAttention; v != nil {+ set, args = append(set, fmt.Sprintf("assignee_need_attention = $%d", len(args)+1)), append(args, *v)+ }if v := patch.Payload; v != nil {payload, err := json.Marshal(*patch.Payload)if err != nil {diff --git a/tests/external_approval_test.go b/tests/external_approval_test.goindex 4b140b5e23..893d4e4123 100644--- a/tests/external_approval_test.go+++ b/tests/external_approval_test.go@@ -144,6 +144,14 @@ func TestExternalApprovalFeishu_AllUserCanBeFound(t *testing.T) {})a.NoError(err)+ attention := true+ issue, err = ctl.patchIssue(api.IssuePatch{+ ID: issue.ID,+ AssigneeNeedAttention: &attention,+ })+ a.NoError(err)+ a.Equal(true, issue.AssigneeNeedAttention)+// Sleep for 65 seconds, giving time to ApplicationRunner to create external approvals.time.Sleep(65 * time.Second)issue, err = ctl.getIssue(issue.ID)@@ -294,6 +302,14 @@ func TestExternalApprovalFeishu_AssigneeCanBeFound(t *testing.T) {})a.NoError(err)+ attention := true+ issue, err = ctl.patchIssue(api.IssuePatch{+ ID: issue.ID,+ AssigneeNeedAttention: &attention,+ })+ a.NoError(err)+ a.Equal(true, issue.AssigneeNeedAttention)+// Sleep for 65 seconds, giving time to ApplicationRunner to create external approvals.time.Sleep(65 * time.Second)issue, err = ctl.getIssue(issue.ID)diff --git a/tests/tests.go b/tests/tests.goindex c03daa906a..0f71f27235 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -984,6 +984,24 @@ func (ctl *controller) getOnePageIssuesWithToken(issueFind api.IssueFind, tokenreturn issueResp.Issues, issueResp.NextToken, nil}+func (ctl *controller) patchIssue(issuePatch api.IssuePatch) (*api.Issue, error) {+ buf := new(bytes.Buffer)+ if err := jsonapi.MarshalPayload(buf, &issuePatch); err != nil {+ return nil, errors.Wrap(err, "failed to marshal issue patch")+ }++ body, err := ctl.patch(fmt.Sprintf("/issue/%d", issuePatch.ID), buf)+ if err != nil {+ return nil, err+ }++ issue := new(api.Issue)+ if err = jsonapi.UnmarshalPayload(body, issue); err != nil {+ return nil, errors.Wrap(err, "fail to unmarshal patch issue patch response")+ }+ return issue, nil+}+// patchIssue patches the issue with given ID.func (ctl *controller) patchIssueStatus(issueStatusPatch api.IssueStatusPatch) (*api.Issue, error) {buf := new(bytes.Buffer)