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: add API for patching status for all tasks in a stage (#1480)
Danny Xu876faf8d757a
diff --git a/api/stage.go b/api/stage.goindex 034452a5b2..59626cc19f 100644--- a/api/stage.go+++ b/api/stage.go@@ -51,6 +51,19 @@ type StageFind struct {PipelineID *int}+// StageAllTaskStatusPatch is the API message for patching task status for all tasks in a stage.+type StageAllTaskStatusPatch struct {+ ID int++ // Standard fields+ // Value is assigned from the jwt subject field passed by the client.+ UpdaterID int++ // Domain specific fields+ Status TaskStatus `jsonapi:"attr,status"`+ Comment *string `jsonapi:"attr,comment"`+}+func (find *StageFind) String() string {str, err := json.Marshal(*find)if err != nil {diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csvindex f22dd1e9c8..8163c24fe1 100644--- a/server/acl_casbin_policy_dba.csv+++ b/server/acl_casbin_policy_dba.csv@@ -71,6 +71,7 @@ p, DBA, /inbox/{id}, PATCH_SELFp, DBA, /bookmark, POSTp, DBA, /bookmark/user/{userID}, GET_SELFp, DBA, /bookmark/{id}, DELETE_SELF+p, DBA, /pipeline/{pipelineID}/stage/{stageID}/status, PATCHp, DBA, /pipeline/{pipelineID}/task/{taskID}, PATCHp, DBA, /pipeline/{pipelineID}/task/{taskID}/status, PATCHp, DBA, /pipeline/{pipelineID}/task/{taskID}/check, POSTdiff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csvindex b03dad51f1..ce4e215431 100644--- a/server/acl_casbin_policy_developer.csv+++ b/server/acl_casbin_policy_developer.csv@@ -65,6 +65,7 @@ p, DEVELOPER, /inbox/{id}, PATCH_SELFp, DEVELOPER, /bookmark, POSTp, DEVELOPER, /bookmark/user/{userID}, GET_SELFp, DEVELOPER, /bookmark/{id}, DELETE_SELF+p, DEVELOPER, /pipeline/{pipelineID}/stage/{stageID}/status, PATCHp, DEVELOPER, /pipeline/{pipelineID}/task/{taskID}, PATCHp, DEVELOPER, /pipeline/{pipelineID}/task/{taskID}/status, PATCHp, DEVELOPER, /pipeline/{pipelineID}/task/{taskID}/check, POSTdiff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csvindex 710e5ad99b..a8c456a287 100644--- a/server/acl_casbin_policy_owner.csv+++ b/server/acl_casbin_policy_owner.csv@@ -75,6 +75,7 @@ p, OWNER, /inbox/{id}, PATCH_SELFp, OWNER, /bookmark, POSTp, OWNER, /bookmark/user/{userID}, GET_SELFp, OWNER, /bookmark/{id}, DELETE_SELF+p, OWNER, /pipeline/{pipelineID}/stage/{stageID}/status, PATCHp, OWNER, /pipeline/{pipelineID}/task/{taskID}, PATCHp, OWNER, /pipeline/{pipelineID}/task/{taskID}/status, PATCHp, OWNER, /pipeline/{pipelineID}/task/{taskID}/check, POSTdiff --git a/server/server.go b/server/server.goindex 824783029b..e525e5b751 100644--- a/server/server.go+++ b/server/server.go@@ -295,6 +295,7 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {s.registerIssueRoutes(apiGroup)s.registerIssueSubscriberRoutes(apiGroup)s.registerTaskRoutes(apiGroup)+ s.registerStageRoutes(apiGroup)s.registerActivityRoutes(apiGroup)s.registerInboxRoutes(apiGroup)s.registerBookmarkRoutes(apiGroup)diff --git a/server/stage.go b/server/stage.gonew file mode 100644index 0000000000..1421643324--- /dev/null+++ b/server/stage.go@@ -0,0 +1,67 @@+package server++import (+ "fmt"+ "net/http"+ "strconv"++ "github.com/google/jsonapi"+ "github.com/labstack/echo/v4"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+)++func (s *Server) registerStageRoutes(g *echo.Group) {+ // This function patches the status of all tasks in the stage.+ g.PATCH("/pipeline/:pipelineID/stage/:stageID/status", func(c echo.Context) error {+ ctx := c.Request().Context()+ stageID, err := strconv.Atoi(c.Param("stageID"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Stage ID is not a number: %s", c.Param("stageID"))).SetInternal(err)+ }+ pipelineID, err := strconv.Atoi(c.Param("pipelineID"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Pipeline ID is not a number: %s", c.Param("pipelineID"))).SetInternal(err)+ }++ currentPrincipalID := c.Get(getPrincipalIDContextKey()).(int)+ stageAllTaskStatusPatch := &api.StageAllTaskStatusPatch{+ ID: stageID,+ UpdaterID: currentPrincipalID,+ }+ if err := jsonapi.UnmarshalPayload(c.Request().Body, stageAllTaskStatusPatch); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed update stage tasks status request").SetInternal(err)+ }++ if err := s.validateIssueAssignee(ctx, currentPrincipalID, pipelineID); err != nil {+ return err+ }++ tasks, err := s.store.FindTask(ctx, &api.TaskFind{PipelineID: &pipelineID, StageID: &stageID}, true /* returnOnErr */)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get tasks").SetInternal(err)+ }+ var tasksPatched []*api.Task+ for _, task := range tasks {+ taskPatched, err := s.changeTaskStatusWithPatch(ctx, task, &api.TaskStatusPatch{+ ID: task.ID,+ UpdaterID: stageAllTaskStatusPatch.UpdaterID,+ Status: stageAllTaskStatusPatch.Status,+ })+ if err != nil {+ if common.ErrorCode(err) == common.Invalid {+ return echo.NewHTTPError(http.StatusBadRequest, common.ErrorMessage(err))+ }+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update task \"%v\" status", task.Name)).SetInternal(err)+ }+ tasksPatched = append(tasksPatched, taskPatched)+ }++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, tasksPatched); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal update tasks status response").SetInternal(err)+ }+ return nil+ })+}diff --git a/server/task.go b/server/task.goindex b3693c3d41..d53892155b 100644--- a/server/task.go+++ b/server/task.go@@ -301,23 +301,8 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Task not found with ID %d", taskID))}- issue, err := s.store.GetIssueByPipelineID(ctx, task.PipelineID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find issue").SetInternal(err)- }- if issue == nil {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Issue not found by pipeline ID: %d", task.PipelineID))- }- if issue.AssigneeID == api.SystemBotID {- currentPrincipal, err := s.store.GetPrincipalByID(ctx, currentPrincipalID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find principal").SetInternal(err)- }- if currentPrincipal.Role != api.Owner && currentPrincipal.Role != api.DBA {- return echo.NewHTTPError(http.StatusUnauthorized, "Only allow Owner/DBA system account to update this task status")- }- } else if issue.AssigneeID != currentPrincipalID {- return echo.NewHTTPError(http.StatusUnauthorized, "Only allow the assignee to update task status")+ if err := s.validateIssueAssignee(ctx, currentPrincipalID, task.PipelineID); err != nil {+ return err}taskPatched, err := s.changeTaskStatusWithPatch(ctx, task, taskStatusPatch)@@ -364,6 +349,28 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {})}+func (s *Server) validateIssueAssignee(ctx context.Context, currentPrincipalID, pipelineID int) error {+ issue, err := s.store.GetIssueByPipelineID(ctx, pipelineID)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find issue").SetInternal(err)+ }+ if issue == nil {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Issue not found by pipeline ID: %d", pipelineID))+ }+ if issue.AssigneeID == api.SystemBotID {+ currentPrincipal, err := s.store.GetPrincipalByID(ctx, currentPrincipalID)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find principal").SetInternal(err)+ }+ if currentPrincipal.Role != api.Owner && currentPrincipal.Role != api.DBA {+ return echo.NewHTTPError(http.StatusUnauthorized, "Only allow Owner/DBA system account to update task status")+ }+ } else if issue.AssigneeID != currentPrincipalID {+ return echo.NewHTTPError(http.StatusUnauthorized, "Only allow the assignee to update task status")+ }+ return nil+}+func (s *Server) changeTaskStatus(ctx context.Context, task *api.Task, newStatus api.TaskStatus, updaterID int) (*api.Task, error) {taskStatusPatch := &api.TaskStatusPatch{ID: task.ID,diff --git a/tests/tenant_test.go b/tests/tenant_test.goindex 469457b8f7..ef77098dbb 100644--- a/tests/tenant_test.go+++ b/tests/tenant_test.go@@ -392,7 +392,8 @@ func TestTenantVCS(t *testing.T) {a.NoError(err)a.Equal(len(issues), 1)issue := issues[0]- status, err := ctl.waitIssuePipeline(issue.ID)+ // Test pipeline stage patch status.+ status, err := ctl.waitIssuePipelineWithStageApproval(issue.ID)a.NoError(err)a.Equal(status, api.TaskDone)diff --git a/tests/tests.go b/tests/tests.goindex 4f429aa1d7..e10a2e32f2 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -728,6 +728,33 @@ func (ctl *controller) patchTaskStatus(taskStatusPatch api.TaskStatusPatch, pipereturn task, nil}+// patchStageAllTaskStatus patches the status of all tasks in the pipeline stage.+func (ctl *controller) patchStageAllTaskStatus(stageAllTaskStatusPatch api.StageAllTaskStatusPatch, pipelineID int) ([]*api.Task, error) {+ buf := new(bytes.Buffer)+ if err := jsonapi.MarshalPayload(buf, &stageAllTaskStatusPatch); err != nil {+ return nil, fmt.Errorf("failed to marshal StageAllTaskStatusPatch, error: %w", err)+ }++ body, err := ctl.patch(fmt.Sprintf("/pipeline/%d/stage/%d/status", pipelineID, stageAllTaskStatusPatch.ID), buf)+ if err != nil {+ return nil, err+ }++ var tasks []*api.Task+ untypedTasks, err := jsonapi.UnmarshalManyPayload(body, reflect.TypeOf(new(api.Task)))+ if err != nil {+ return nil, fmt.Errorf("fail to unmarshal get tasks response, error: %w", err)+ }+ for _, t := range untypedTasks {+ task, ok := t.(*api.Task)+ if !ok {+ return nil, fmt.Errorf("fail to convert task")+ }+ tasks = append(tasks, task)+ }+ return tasks, nil+}+// approveIssueNext approves the next pending approval task.func (ctl *controller) approveIssueNext(issue *api.Issue) error {for _, stage := range issue.Pipeline.StageList {@@ -749,6 +776,34 @@ func (ctl *controller) approveIssueNext(issue *api.Issue) error {return nil}+// approveIssueTasksWithStageApproval approves all pending approval tasks in the next stage.+func (ctl *controller) approveIssueTasksWithStageApproval(issue *api.Issue) error {+ stageID := 0+ for _, stage := range issue.Pipeline.StageList {+ for _, task := range stage.TaskList {+ if task.Status == api.TaskPendingApproval {+ stageID = stage.ID+ break+ }+ }+ if stageID != 0 {+ break+ }+ }+ if stageID != 0 {+ if _, err := ctl.patchStageAllTaskStatus(+ api.StageAllTaskStatusPatch{+ ID: stageID,+ Status: api.TaskPending,+ },+ issue.Pipeline.ID,+ ); err != nil {+ return fmt.Errorf("failed to patch task status for stage %d, error: %w", stageID, err)+ }+ }+ return nil+}+// getAggregatedTaskStatus gets pipeline status.func getAggregatedTaskStatus(issue *api.Issue) (api.TaskStatus, error) {running := false@@ -780,6 +835,16 @@ func getAggregatedTaskStatus(issue *api.Issue) (api.TaskStatus, error) {// waitIssuePipeline waits for pipeline to finish and approves tasks when necessary.func (ctl *controller) waitIssuePipeline(id int) (api.TaskStatus, error) {+ return ctl.waitIssuePipelineImpl(id, ctl.approveIssueNext)+}++// waitIssuePipelineWithStageApproval waits for pipeline to finish and approves tasks when necessary.+func (ctl *controller) waitIssuePipelineWithStageApproval(id int) (api.TaskStatus, error) {+ return ctl.waitIssuePipelineImpl(id, ctl.approveIssueTasksWithStageApproval)+}++// waitIssuePipelineImpl waits for pipeline to finish and approves tasks when necessary.+func (ctl *controller) waitIssuePipelineImpl(id int, approveFunc func(issue *api.Issue) error) (api.TaskStatus, error) {// Sleep for two seconds between issues so that we don't get migration version conflict because we are using second-level timestamp for the version string. We choose sleep because it mimics the user's behavior.time.Sleep(2 * time.Second)@@ -798,7 +863,7 @@ func (ctl *controller) waitIssuePipeline(id int) (api.TaskStatus, error) {}switch status {case api.TaskPendingApproval:- if err := ctl.approveIssueNext(issue); err != nil {+ if err := approveFunc(issue); err != nil {return api.TaskFailed, err}case api.TaskFailed: