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: dismiss stale review & check if approved when deploying (#5251)
p0ny72b97898010f
diff --git a/backend/api/v1/review_service.go b/backend/api/v1/review_service.goindex 5a930c6f6b..86e4705265 100644--- a/backend/api/v1/review_service.go+++ b/backend/api/v1/review_service.go@@ -16,6 +16,7 @@ import ("github.com/bytebase/bytebase/backend/component/activity"api "github.com/bytebase/bytebase/backend/legacyapi""github.com/bytebase/bytebase/backend/store"+ "github.com/bytebase/bytebase/backend/utils"storepb "github.com/bytebase/bytebase/proto/generated-go/store"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")@@ -77,7 +78,7 @@ func (s *ReviewService) ApproveReview(ctx context.Context, request *v1pb.Approvereturn nil, status.Errorf(codes.Internal, "expecting one approval template but got %v", len(payload.Approval.ApprovalTemplates))}- step := findPendingStep(payload.Approval.ApprovalTemplates[0], payload.Approval.Approvers)+ step := utils.FindNextPendingStep(payload.Approval.ApprovalTemplates[0], payload.Approval.Approvers)if step == nil {return nil, status.Errorf(codes.InvalidArgument, "the review has been approved")}@@ -151,15 +152,6 @@ func (s *ReviewService) ApproveReview(ctx context.Context, request *v1pb.Approvereturn review, nil}-func findPendingStep(template *storepb.ApprovalTemplate, approvers []*storepb.IssuePayloadApproval_Approver) *storepb.ApprovalStep {- // We can do the finding like this for now because we are presuming that- // one step is approved by one approver.- if len(approvers) >= len(template.Flow.Steps) {- return nil- }- return template.Flow.Steps[len(approvers)]-}-func canUserApproveStep(step *storepb.ApprovalStep, user *store.UserMessage, policy *store.IAMPolicyMessage) (bool, error) {if len(step.Nodes) != 1 {return false, errors.Errorf("expecting one node but got %v", len(step.Nodes))diff --git a/backend/bin/server/cmd/profile_dev.go b/backend/bin/server/cmd/profile_dev.goindex ce1fccfc83..c7672761e5 100644--- a/backend/bin/server/cmd/profile_dev.go+++ b/backend/bin/server/cmd/profile_dev.go@@ -16,6 +16,7 @@ func activeProfile(dataDir string) config.Profile {p.PgUser = "bbdev"p.BackupRunnerInterval = 10 * time.Secondp.AppRunnerInterval = 30 * time.Second+ p.ApprovalRunnerInterval = 30 * time.Secondp.MetricConnectionKey = "3zcZLeX3ahvlueEJqNyJysGfVAErsjjT"return p}diff --git a/backend/bin/server/cmd/profile_release.go b/backend/bin/server/cmd/profile_release.goindex d7ee8fa8be..1c3c1ae6ca 100644--- a/backend/bin/server/cmd/profile_release.go+++ b/backend/bin/server/cmd/profile_release.go@@ -16,6 +16,7 @@ func activeProfile(dataDir string) config.Profile {p.PgUser = "bb"p.BackupRunnerInterval = 10 * time.Minutep.AppRunnerInterval = 30 * time.Second+ p.ApprovalRunnerInterval = 30 * time.Secondp.MetricConnectionKey = "so9lLwj5zLjH09sxNabsyVNYSsAHn68F"return p}diff --git a/backend/component/config/profile.go b/backend/component/config/profile.goindex 002fefc4ab..f01278ebbe 100644--- a/backend/component/config/profile.go+++ b/backend/component/config/profile.go@@ -41,6 +41,8 @@ type Profile struct {DemoName string// AppRunnerInterval is the interval for application runner.AppRunnerInterval time.Duration+ // ApprovalRunnerInterval is the interval for approval runner.+ ApprovalRunnerInterval time.Duration// BackupRunnerInterval is the interval for backup runner.BackupRunnerInterval time.Duration// BackupStorageBackend is the backup storage backend.diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.goindex 477b3386c1..1da471c815 100644--- a/backend/runner/approval/runner.go+++ b/backend/runner/approval/runner.go@@ -4,6 +4,7 @@ package approvalimport ("context""encoding/json"+ "fmt""reflect""sort""strconv"@@ -17,6 +18,7 @@ import ("github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"+ "github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/component/dbfactory"api "github.com/bytebase/bytebase/backend/legacyapi""github.com/bytebase/bytebase/backend/store"@@ -25,8 +27,6 @@ import (v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")-const approvalRunnerInterval = 30 * time.Second-var riskFactors = []cel.EnvOption{// string factors// use environment.resource_id@@ -63,21 +63,24 @@ var issueTypeToRiskSource = map[api.IssueType]store.RiskSource{type Runner struct {store *store.StoredbFactory *dbfactory.DBFactory+ profile config.Profile}// NewRunner creates a new runner.-func NewRunner(store *store.Store, dbFactory *dbfactory.DBFactory) *Runner {+func NewRunner(store *store.Store, dbFactory *dbfactory.DBFactory, profile config.Profile) *Runner {return &Runner{store: store,dbFactory: dbFactory,+ profile: profile,}}// Run runs the runner.func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {- ticker := time.NewTicker(approvalRunnerInterval)+ ticker := time.NewTicker(r.profile.ApprovalRunnerInterval)defer ticker.Stop()defer wg.Done()+ log.Debug(fmt.Sprintf("Approval runner started and will run every %v", r.profile.ApprovalRunnerInterval))for {select {case <-ticker.C:@@ -97,8 +100,20 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {return errors.Wrap(err, "failed to get workspace approval setting")}for _, issue := range issues {- // no need to find for RiskSourceUnknown issues.- if issueTypeToRiskSource[issue.Type] == store.RiskSourceUnknown {+ payload := &storepb.IssuePayload{}+ if err := protojson.Unmarshal([]byte(issue.Payload), payload); err != nil {+ log.Error("failed to unmarshal issue payload", zap.Error(err))+ continue+ }+ if payload.Approval != nil && payload.Approval.ApprovalFindingDone {+ continue+ }++ // no need to find if+ // - risk source is RiskSourceUnknown+ // - risks are empty+ // - approval setting rules are empty+ if issueTypeToRiskSource[issue.Type] == store.RiskSourceUnknown || len(risks) == 0 || len(approvalSetting.Rules) == 0 {payload := &storepb.IssuePayload{Approval: &storepb.IssuePayloadApproval{ApprovalFindingDone: true,@@ -121,15 +136,6 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {continue}- payload := &storepb.IssuePayload{}- if err := protojson.Unmarshal([]byte(issue.Payload), payload); err != nil {- log.Error("failed to unmarshal issue payload", zap.Error(err))- continue- }- if payload.Approval != nil && payload.Approval.ApprovalFindingDone {- continue- }-riskLevel, done, err := getIssueRiskLevel(ctx, r.store, issue, risks)if err != nil {log.Error("failed to get issue risk level", zap.Int("issueID", issue.UID), zap.Error(err))diff --git a/backend/runner/apprun/runner.go b/backend/runner/apprun/runner.goindex 6109e60c9f..0f608bbc03 100644--- a/backend/runner/apprun/runner.go+++ b/backend/runner/apprun/runner.go@@ -159,6 +159,14 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {// Approve stage.if err := func() error {// TODO(d): optimize the active stage tasks.+ approved, err := utils.CheckIssueApproved(issue)+ if err != nil {+ return errors.Wrap(err, "failed to check if issue is approved")+ }+ if !approved {+ return nil+ }+var taskIDList []intvar tasks []*store.TaskMessagestageTasks, err := r.store.ListTasks(ctx, &api.TaskFind{PipelineID: &activeStage.PipelineID, StageID: &activeStage.ID})@@ -282,6 +290,7 @@ func (r *Runner) cancelOldExternalApprovalIfNeeded(ctx context.Context, issue *spendingApprovalCount := 0tasks, err := r.store.ListTasks(ctx, &api.TaskFind{PipelineID: &stage.PipelineID, StageID: &stage.ID})if err != nil {+ log.Warn("apprun runner: failed to list tasks", zap.Int("issueID", issue.UID), zap.Error(err))return false}for _, task := range tasks {@@ -293,6 +302,14 @@ func (r *Runner) cancelOldExternalApprovalIfNeeded(ctx context.Context, issue *sreason = api.ExternalApprovalCancelReasonNoTaskPendingApprovalreturn true}+ approved, err := utils.CheckIssueApproved(issue)+ if err != nil {+ log.Warn("apprun runner: failed to check if issue is approved", zap.Int("issueID", issue.UID), zap.Error(err))+ return false+ }+ if !approved {+ return true+ }return false}()@@ -399,6 +416,14 @@ func (r *Runner) CancelExternalApproval(ctx context.Context, issueID int, reason}func (r *Runner) shouldCreateExternalApproval(ctx context.Context, issue *store.IssueMessage, stage *store.StageMessage, oldApproval *store.ExternalApprovalMessage) (bool, error) {+ approved, err := utils.CheckIssueApproved(issue)+ if err != nil {+ return false, errors.Wrap(err, "failed to check if issue is approved")+ }+ if !approved {+ return false, nil+ }+policy, err := r.store.GetPipelineApprovalPolicy(ctx, stage.EnvironmentID)if err != nil {return false, err@@ -571,6 +596,7 @@ func (r *Runner) scheduleApproval(ctx context.Context, issue *store.IssueMessage// 1. the approval policy of the stage environment is MANUAL_APPROVAL_ALWAYS.// 2. the stage has one or more PENDING_APPROVAL tasks.// 3. all task checks of the stage are done and the results have no errors.+ // 4. the issue is approved.ok, err := r.shouldCreateExternalApproval(ctx, issue, activeStage, oldApproval)if err != nil {log.Error("failed to check shouldCreateExternalApproval", zap.Error(err))diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.goindex 6656ab8630..ffe8cdecdd 100644--- a/backend/runner/taskrun/scheduler.go+++ b/backend/runner/taskrun/scheduler.go@@ -792,6 +792,21 @@ func (s *Scheduler) scheduleAutoApprovedTasks(ctx context.Context) error {continue}+ issue, err := s.store.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &task.PipelineID})+ if err != nil {+ return err+ }+ if issue != nil {+ approved, err := utils.CheckIssueApproved(issue)+ if err != nil {+ log.Warn("taskrun scheduler: failed to check if the issue is approved when scheduling auto-deployed tasks", zap.Int("taskID", task.ID), zap.Int("issueID", issue.UID), zap.Error(err))+ continue+ }+ if !approved {+ continue+ }+ }+taskCheckRuns, err := s.store.ListTaskCheckRuns(ctx, &store.TaskCheckRunFind{TaskID: &task.ID})if err != nil {return err@@ -901,7 +916,7 @@ func (s *Scheduler) PatchTaskStatus(ctx context.Context, task *store.TaskMessage}if issue != nil {- if err := s.onTaskPatched(ctx, issue, taskPatched); err != nil {+ if err := s.onTaskStatusPatched(ctx, issue, taskPatched); err != nil {return err}}@@ -1183,7 +1198,7 @@ func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *store.IssueMesreturn nil}-func (s *Scheduler) onTaskPatched(ctx context.Context, issue *store.IssueMessage, taskPatched *store.TaskMessage) error {+func (s *Scheduler) onTaskStatusPatched(ctx context.Context, issue *store.IssueMessage, taskPatched *store.TaskMessage) error {stages, err := s.store.ListStageV2(ctx, taskPatched.PipelineID)if err != nil {return errdiff --git a/backend/server/issue.go b/backend/server/issue.goindex f6b6169c5d..c046799506 100644--- a/backend/server/issue.go+++ b/backend/server/issue.go@@ -209,6 +209,18 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {Payload: issuePatch.Payload,}+ // If we are to set AssigneeNeedAttention to true+ // make sure that CI approval is finished.+ if issuePatch.AssigneeNeedAttention != nil && *issuePatch.AssigneeNeedAttention {+ approved, err := utils.CheckIssueApproved(issue)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to check if the issue is approved").SetInternal(err)+ }+ if !approved {+ return echo.NewHTTPError(http.StatusBadRequest, "Cannot set assigneeNeedAttention because the issue is not approved")+ }+ }+if issuePatch.AssigneeID != nil {assignee, err := s.store.GetUserByID(ctx, *issuePatch.AssigneeID)if err != nil {diff --git a/backend/server/server.go b/backend/server/server.goindex 1db06a41ba..658508a054 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -399,7 +399,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {s.ApplicationRunner = apprun.NewRunner(storeInstance, s.ActivityManager, s.feishuProvider, profile)s.BackupRunner = backuprun.NewRunner(storeInstance, s.dbFactory, s.s3Client, s.stateCfg, &profile)s.RollbackRunner = rollbackrun.NewRunner(storeInstance, s.dbFactory, s.stateCfg)- s.ApprovalRunner = approval.NewRunner(storeInstance, s.dbFactory)+ s.ApprovalRunner = approval.NewRunner(storeInstance, s.dbFactory, profile)s.TaskScheduler = taskrun.NewScheduler(storeInstance, s.ApplicationRunner, s.SchemaSyncer, s.ActivityManager, s.licenseService, s.stateCfg, profile, s.MetricReporter)s.TaskScheduler.Register(api.TaskGeneral, taskrun.NewDefaultExecutor())diff --git a/backend/server/stage.go b/backend/server/stage.goindex ab533cb8e5..8396fad5e3 100644--- a/backend/server/stage.go+++ b/backend/server/stage.go@@ -29,6 +29,7 @@ func (s *Server) registerStageRoutes(g *echo.Group) {if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find stage %v", stageID)).SetInternal(err)}+var stage *store.StageMessagefor _, v := range stages {if v.ID == stageID {@@ -57,6 +58,21 @@ func (s *Server) registerStageRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Only support status transitioning from PENDING_APPROVAL to PENDING")}+ issue, err := s.store.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &pipelineID})+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch issue with pipeline ID %d", pipelineID)).SetInternal(err)+ }+ if issue == nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Issue not found with pipeline ID %d", pipelineID))+ }+ approved, err := utils.CheckIssueApproved(issue)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to check if the issue is approved").SetInternal(err)+ }+ if !approved {+ return echo.NewHTTPError(http.StatusBadRequest, "Cannot patch task status because the issue is not approved")+ }+pendingApprovalStatus := []api.TaskStatus{api.TaskPendingApproval}tasks, err := s.store.ListTasks(ctx, &api.TaskFind{PipelineID: &pipelineID, StageID: &stageID, StatusList: &pendingApprovalStatus})if err != nil {@@ -106,13 +122,6 @@ func (s *Server) registerStageRoutes(g *echo.Group) {if err := s.store.BatchPatchTaskStatus(ctx, taskIDList, api.TaskPending, currentPrincipalID); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update task %q status", taskIDList)).SetInternal(err)}- issue, err := s.store.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &pipelineID})- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "failed to fetch containing issue").SetInternal(err)- }- if issue == nil {- return echo.NewHTTPError(http.StatusNotFound, "issue not found")- }if err := s.ActivityManager.BatchCreateTaskStatusUpdateApprovalActivity(ctx, tasks, currentPrincipalID, issue, stage.Name); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "failed to create task status update activity").SetInternal(err)}diff --git a/backend/server/task.go b/backend/server/task.goindex 43ae0e13e8..ec7be572c0 100644--- a/backend/server/task.go+++ b/backend/server/task.go@@ -7,11 +7,13 @@ import ("github.com/google/jsonapi""github.com/labstack/echo/v4"+ "google.golang.org/protobuf/encoding/protojson""github.com/bytebase/bytebase/backend/common"api "github.com/bytebase/bytebase/backend/legacyapi""github.com/bytebase/bytebase/backend/store""github.com/bytebase/bytebase/backend/utils"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")func (s *Server) registerTaskRoutes(g *echo.Group) {@@ -57,6 +59,25 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {return err}}++ // dismiss stale review, re-find the approval template+ if taskPatch.Statement != nil {+ payloadBytes, err := protojson.Marshal(&storepb.IssuePayload{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ },+ })+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal issue payload").SetInternal(err)+ }+ payloadStr := string(payloadBytes)+ if _, err := s.store.UpdateIssueV2(ctx, issue.UID, &store.UpdateIssueMessage{+ Payload: &payloadStr,+ }, api.SystemBotID); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to update issue").SetInternal(err)+ }+ }+c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)return nil})@@ -110,6 +131,25 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {if err := s.TaskScheduler.PatchTask(ctx, task, taskPatch, issue); err != nil {return err}++ // dismiss stale review, re-find the approval template+ if taskPatch.Statement != nil {+ payloadBytes, err := protojson.Marshal(&storepb.IssuePayload{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ },+ })+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal issue payload").SetInternal(err)+ }+ payloadStr := string(payloadBytes)+ if _, err := s.store.UpdateIssueV2(ctx, issue.UID, &store.UpdateIssueMessage{+ Payload: &payloadStr,+ }, api.SystemBotID); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to update issue").SetInternal(err)+ }+ }+composedTaskPatched, err := s.store.GetTaskByID(ctx, task.ID)if err != nil {return err@@ -155,6 +195,21 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {}if taskStatusPatch.Status == api.TaskPending {+ issue, err := s.store.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &task.PipelineID})+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch issue with pipeline ID %d", task.PipelineID)).SetInternal(err)+ }+ if issue == nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Issue not found with pipeline ID %d", task.PipelineID))+ }+ approved, err := utils.CheckIssueApproved(issue)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to check if the issue is approved").SetInternal(err)+ }+ if !approved {+ return echo.NewHTTPError(http.StatusBadRequest, "Cannot patch task status because the issue is not approved")+ }+instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})if err != nil {return errdiff --git a/backend/server/webhook.go b/backend/server/webhook.goindex 69ae8f67da..fb6dcece78 100644--- a/backend/server/webhook.go+++ b/backend/server/webhook.go@@ -20,6 +20,7 @@ import ("github.com/labstack/echo/v4""github.com/pkg/errors""go.uber.org/zap"+ "google.golang.org/protobuf/encoding/protojson""gopkg.in/yaml.v3""github.com/bytebase/bytebase/backend/common"@@ -35,6 +36,7 @@ import ("github.com/bytebase/bytebase/backend/plugin/vcs/gitlab""github.com/bytebase/bytebase/backend/store""github.com/bytebase/bytebase/backend/utils"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")const (@@ -1393,6 +1395,28 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [log.Error("Failed to patch task with the same migration version", zap.Int("issueID", issue.UID), zap.Int("taskID", task.ID), zap.Error(err))return nil}++ // dismiss stale review, re-find the approval template+ // it's ok if we failed+ if err := func() error {+ payloadBytes, err := protojson.Marshal(&storepb.IssuePayload{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ },+ })+ if err != nil {+ return errors.Wrap(err, "failed to marshal issue payload")+ }+ payloadStr := string(payloadBytes)+ if _, err := s.store.UpdateIssueV2(ctx, issue.UID, &store.UpdateIssueMessage{+ Payload: &payloadStr,+ }, api.SystemBotID); err != nil {+ return errors.Wrap(err, "failed to update issue payload")+ }+ return nil+ }(); err != nil {+ log.Warn("Failed to dismiss stale review", zap.Error(err))+ }}return nil}diff --git a/backend/tests/external_approval_test.go b/backend/tests/external_approval_test.goindex 9364562635..6580e777cf 100644--- a/backend/tests/external_approval_test.go+++ b/backend/tests/external_approval_test.go@@ -143,6 +143,8 @@ func TestExternalApprovalFeishu_AllUserCanBeFound(t *testing.T) {})a.NoError(err)+ // TODO(p0ny): remove me after supporting get review.+ time.Sleep(10 * time.Second)attention := trueissue, err = ctl.patchIssue(issue.ID, api.IssuePatch{AssigneeNeedAttention: &attention,@@ -299,6 +301,8 @@ func TestExternalApprovalFeishu_AssigneeCanBeFound(t *testing.T) {})a.NoError(err)+ // TODO(p0ny): remove me after supporting get review.+ time.Sleep(10 * time.Second)attention := trueissue, err = ctl.patchIssue(issue.ID, api.IssuePatch{AssigneeNeedAttention: &attention,diff --git a/backend/tests/issue.go b/backend/tests/issue.goindex 6662b98673..06e873abca 100644--- a/backend/tests/issue.go+++ b/backend/tests/issue.go@@ -299,7 +299,7 @@ func (ctl *controller) waitIssuePipelineTaskImpl(id int, approveFunc func(issuereturn api.TaskDone, nil}if err := approveFunc(issue); err != nil {- if strings.Contains(err.Error(), "The task has not passed all the checks yet") {+ if strings.Contains(err.Error(), "The task has not passed all the checks yet") || strings.Contains(err.Error(), "Cannot patch task status because the issue is not approved") {continue}// "invalid task status transition" error means this task has been approved.diff --git a/backend/tests/tests.go b/backend/tests/tests.goindex 738d3a5482..16ec34d223 100644--- a/backend/tests/tests.go+++ b/backend/tests/tests.go@@ -294,19 +294,20 @@ func (ctl *controller) initWorkspaceProfile() error {// We require port as an argument of GetTestProfile so that test can run in parallel in different ports.func getTestProfile(dataDir, resourceDir string, port int, readOnly bool, feishuAPIURL string) componentConfig.Profile {return componentConfig.Profile{- Mode: testReleaseMode,- ExternalURL: fmt.Sprintf("http://localhost:%d", port),- GrpcPort: port + 1,- DatastorePort: port + 2,- SampleDatabasePort: port + 3,- PgUser: "bbtest",- Readonly: readOnly,- DataDir: dataDir,- ResourceDir: resourceDir,- AppRunnerInterval: 1 * time.Second,- BackupRunnerInterval: 10 * time.Second,- BackupStorageBackend: api.BackupStorageBackendLocal,- FeishuAPIURL: feishuAPIURL,+ Mode: testReleaseMode,+ ExternalURL: fmt.Sprintf("http://localhost:%d", port),+ GrpcPort: port + 1,+ DatastorePort: port + 2,+ SampleDatabasePort: port + 3,+ PgUser: "bbtest",+ Readonly: readOnly,+ DataDir: dataDir,+ ResourceDir: resourceDir,+ AppRunnerInterval: 1 * time.Second,+ ApprovalRunnerInterval: 1 * time.Second,+ BackupRunnerInterval: 10 * time.Second,+ BackupStorageBackend: api.BackupStorageBackendLocal,+ FeishuAPIURL: feishuAPIURL,}}@@ -323,6 +324,7 @@ func getTestProfileWithExternalPg(dataDir, resourceDir string, port int, pgUserDataDir: dataDir,ResourceDir: resourceDir,AppRunnerInterval: 1 * time.Second,+ ApprovalRunnerInterval: 1 * time.Second,BackupRunnerInterval: 10 * time.Second,BackupStorageBackend: api.BackupStorageBackendLocal,FeishuAPIURL: feishuAPIURL,diff --git a/backend/utils/utils.go b/backend/utils/utils.goindex a833193047..523a380e2f 100644--- a/backend/utils/utils.go+++ b/backend/utils/utils.go@@ -16,6 +16,7 @@ import (ghostsql "github.com/github/gh-ost/go/sql""github.com/pkg/errors""go.uber.org/zap"+ "google.golang.org/protobuf/encoding/protojson""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -24,6 +25,7 @@ import ("github.com/bytebase/bytebase/backend/plugin/db/oracle""github.com/bytebase/bytebase/backend/plugin/db/util""github.com/bytebase/bytebase/backend/store"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")// GetLatestSchemaVersion gets the latest schema version for a database.@@ -632,3 +634,31 @@ func EndMigration(ctx context.Context, store *store.Store, startedNs int64, inse}return err}++// FindNextPendingStep finds the next pending step in the approval flow.+func FindNextPendingStep(template *storepb.ApprovalTemplate, approvers []*storepb.IssuePayloadApproval_Approver) *storepb.ApprovalStep {+ // We can do the finding like this for now because we are presuming that+ // one step is approved by one approver.+ if len(approvers) >= len(template.Flow.Steps) {+ return nil+ }+ return template.Flow.Steps[len(approvers)]+}++// CheckIssueApproved checks if the issue is approved.+func CheckIssueApproved(issue *store.IssueMessage) (bool, error) {+ issuePayload := &storepb.IssuePayload{}+ if err := protojson.Unmarshal([]byte(issue.Payload), issuePayload); err != nil {+ return false, errors.Wrap(err, "failed to unmarshal issue payload")+ }+ if issuePayload.Approval == nil || !issuePayload.Approval.ApprovalFindingDone {+ return false, nil+ }+ if len(issuePayload.Approval.ApprovalTemplates) == 0 {+ return true, nil+ }+ if len(issuePayload.Approval.ApprovalTemplates) != 1 {+ return false, errors.Errorf("expecting one approval template but got %d", len(issuePayload.Approval.ApprovalTemplates))+ }+ return FindNextPendingStep(issuePayload.Approval.ApprovalTemplates[0], issuePayload.Approval.Approvers) == nil, nil+}