Skip to content

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

feat: auto resolve finished issue (#6075)

p0ny670c1a2a3fa8
diff --git a/backend/api/v1/review_service.go b/backend/api/v1/review_service.go
index 2b945277ab..fdb57bea47 100644
--- a/backend/api/v1/review_service.go
+++ b/backend/api/v1/review_service.go
@@ -18,6 +18,7 @@ import (
"github.com/bytebase/bytebase/backend/component/activity"
"github.com/bytebase/bytebase/backend/component/state"
api "github.com/bytebase/bytebase/backend/legacyapi"
+ "github.com/bytebase/bytebase/backend/runner/taskrun"
"github.com/bytebase/bytebase/backend/store"
"github.com/bytebase/bytebase/backend/utils"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
@@ -29,14 +30,16 @@ type ReviewService struct {
v1pb.UnimplementedReviewServiceServer
store *store.Store
activityManager *activity.Manager
+ taskScheduler *taskrun.Scheduler
stateCfg *state.State
}
// NewReviewService creates a new ReviewService.
-func NewReviewService(store *store.Store, activityManager *activity.Manager, stateCfg *state.State) *ReviewService {
+func NewReviewService(store *store.Store, activityManager *activity.Manager, taskScheduler *taskrun.Scheduler, stateCfg *state.State) *ReviewService {
return &ReviewService{
store: store,
activityManager: activityManager,
+ taskScheduler: taskScheduler,
stateCfg: stateCfg,
}
}
@@ -121,8 +124,13 @@ func (s *ReviewService) ApproveReview(ctx context.Context, request *v1pb.Approve
PrincipalId: int32(principalID),
})
+ approved, err := utils.CheckApprovalApproved(payload.Approval)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to check if the approval is approved, error: %v", err)
+ }
+
// Grant the privilege if the issue is approved.
- if len(payload.Approval.Approvers) > 0 && issue.Type == api.IssueGrantRequest {
+ if approved && issue.Type == api.IssueGrantRequest {
policy, err := s.store.GetProjectPolicy(ctx, &store.GetProjectPolicyMessage{ProjectID: &issue.Project.ResourceID})
if err != nil {
return nil, err
@@ -237,6 +245,8 @@ func (s *ReviewService) ApproveReview(ctx context.Context, request *v1pb.Approve
log.Error("failed to create activity after approving review", zap.Error(err))
}
+ s.onReviewApproved(ctx, issue)
+
review, err := convertToReview(ctx, s.store, issue)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to convert to review, error: %v", err)
@@ -423,3 +433,26 @@ func convertToApprovalNode(node *storepb.ApprovalNode) *v1pb.ApprovalNode {
}
return v1node
}
+
+func (s *ReviewService) onReviewApproved(ctx context.Context, issue *store.IssueMessage) {
+ if issue.Type == api.IssueGrantRequest {
+ if err := func() error {
+ payload := &storepb.IssuePayload{}
+ if err := protojson.Unmarshal([]byte(issue.Payload), payload); err != nil {
+ return errors.Wrap(err, "failed to unmarshal issue payload")
+ }
+ approved, err := utils.CheckApprovalApproved(payload.Approval)
+ if err != nil {
+ return errors.Wrap(err, "failed to check if the approval is approved")
+ }
+ if approved {
+ if err := s.taskScheduler.ChangeIssueStatus(ctx, issue, api.IssueDone, api.SystemBotID, ""); err != nil {
+ return errors.Wrap(err, "failed to update issue status")
+ }
+ }
+ return nil
+ }(); err != nil {
+ log.Debug("failed to update issue status to done if grant request issue is approved", zap.Error(err))
+ }
+ }
+}
diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.go
index 4c32c63f05..b9bda91097 100644
--- a/backend/runner/taskrun/scheduler.go
+++ b/backend/runner/taskrun/scheduler.go
@@ -307,50 +307,6 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
)
return
}
-
- issue, err := s.store.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &task.PipelineID})
- if err != nil {
- 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 && issue.PipelineUID != nil {
- stages, err := s.store.ListStageV2(ctx, *issue.PipelineUID)
- if err != nil {
- return
- }
- activeStage := utils.GetActiveStage(stages)
- if activeStage != nil && activeStage.ID != task.StageID {
- environmentID := activeStage.EnvironmentID
- ok, err := s.CanPrincipalBeAssignee(ctx, issue.Assignee.ID, environmentID, issue.Project.UID, issue.Type)
- if err != nil {
- log.Error("failed to check if the current assignee still fits in the new assignee group", zap.Error(err))
- return
- }
- if !ok {
- // reassign the issue to a new assignee if the current one doesn't fit.
- assignee, err := s.GetDefaultAssignee(ctx, environmentID, issue.Project.UID, issue.Type)
- if err != nil {
- log.Error("failed to get a default assignee", zap.Error(err))
- return
- }
- if _, err := s.store.UpdateIssueV2(ctx, issue.UID, &store.UpdateIssueMessage{Assignee: assignee}, api.SystemBotID); err != nil {
- log.Error("failed to update the issue assignee", zap.Error(err))
- return
- }
- }
- }
-
- s.metricReporter.Report(ctx, &metric.Metric{
- Name: metricAPI.TaskStatusMetricName,
- Value: 1,
- Labels: map[string]any{
- "type": task.Type,
- "value": taskStatusPatch.Status,
- },
- })
- }
return
}
}(ctx, task, executor)
@@ -1243,9 +1199,18 @@ func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *store.IssueMes
}
func (s *Scheduler) onTaskStatusPatched(ctx context.Context, issue *store.IssueMessage, taskPatched *store.TaskMessage) error {
+ s.metricReporter.Report(ctx, &metric.Metric{
+ Name: metricAPI.TaskStatusMetricName,
+ Value: 1,
+ Labels: map[string]any{
+ "type": taskPatched.Type,
+ "value": taskPatched.Status,
+ },
+ })
+
stages, err := s.store.ListStageV2(ctx, taskPatched.PipelineID)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to list stages")
}
var taskStage, nextStage *store.StageMessage
for i, stage := range stages {
@@ -1261,20 +1226,48 @@ func (s *Scheduler) onTaskStatusPatched(ctx context.Context, issue *store.IssueM
return errors.New("failed to find corresponding stage of the task in the issue pipeline")
}
+ if !taskStage.Active && nextStage != nil {
+ // Every task in this stage has finished, we are moving to the next stage.
+ // The current assignee doesn't fit in the new assignee group, we will reassign a new one based on the new assignee group.
+ func() {
+ environmentID := nextStage.EnvironmentID
+ ok, err := s.CanPrincipalBeAssignee(ctx, issue.Assignee.ID, environmentID, issue.Project.UID, issue.Type)
+ if err != nil {
+ log.Error("failed to check if the current assignee still fits in the new assignee group", zap.Error(err))
+ return
+ }
+ if !ok {
+ // reassign the issue to a new assignee if the current one doesn't fit.
+ assignee, err := s.GetDefaultAssignee(ctx, environmentID, issue.Project.UID, issue.Type)
+ if err != nil {
+ log.Error("failed to get a default assignee", zap.Error(err))
+ return
+ }
+ if _, err := s.store.UpdateIssueV2(ctx, issue.UID, &store.UpdateIssueMessage{Assignee: assignee}, api.SystemBotID); err != nil {
+ log.Error("failed to update the issue assignee", zap.Error(err))
+ return
+ }
+ }
+ }()
+ }
+ if !taskStage.Active && nextStage == nil {
+ // Every task in the pipeline has finished.
+ // Resolve the issue automatically for the user.
+ if err := s.ChangeIssueStatus(ctx, issue, api.IssueDone, api.SystemBotID, ""); err != nil {
+ log.Error("failed to change the issue status to done automatically after completing every task", zap.Error(err))
+ }
+ }
+
tasks, err := s.store.ListTasks(ctx, &api.TaskFind{PipelineID: &taskPatched.PipelineID, StageID: &taskPatched.StageID})
if err != nil {
- return err
+ return errors.Wrap(err, "failed to list tasks")
}
stageTaskHasPendingApproval := false
stageTaskAllTerminated := true
- stageTaskAllDone := true
for _, task := range tasks {
if task.Status == api.TaskPendingApproval {
stageTaskHasPendingApproval = true
}
- if task.Status != api.TaskDone {
- stageTaskAllDone = false
- }
if !terminatedTaskStatus[task.Status] {
stageTaskAllTerminated = false
}
@@ -1291,54 +1284,64 @@ func (s *Scheduler) onTaskStatusPatched(ctx context.Context, issue *store.IssueM
// every task in the stage terminated
// create "stage ends" activity.
if stageTaskAllTerminated {
- createActivityPayload := api.ActivityPipelineStageStatusUpdatePayload{
- StageID: taskStage.ID,
- StageStatusUpdateType: api.StageStatusUpdateTypeEnd,
- IssueName: issue.Title,
- StageName: taskStage.Name,
- }
- bytes, err := json.Marshal(createActivityPayload)
- if err != nil {
- return errors.Wrap(err, "failed to create ActivityPipelineStageStatusUpdate activity")
- }
- activityCreate := &api.ActivityCreate{
- CreatorID: api.SystemBotID,
- ContainerID: *issue.PipelineUID,
- Type: api.ActivityPipelineStageStatusUpdate,
- Level: api.ActivityInfo,
- Payload: string(bytes),
- }
- if _, err := s.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{
- Issue: issue,
- }); err != nil {
- return errors.Wrap(err, "failed to create ActivityPipelineStageStatusUpdate activity")
+ if err := func() error {
+ createActivityPayload := api.ActivityPipelineStageStatusUpdatePayload{
+ StageID: taskStage.ID,
+ StageStatusUpdateType: api.StageStatusUpdateTypeEnd,
+ IssueName: issue.Title,
+ StageName: taskStage.Name,
+ }
+ bytes, err := json.Marshal(createActivityPayload)
+ if err != nil {
+ return errors.Wrap(err, "failed to marshal ActivityPipelineStageStatusUpdate payload")
+ }
+ activityCreate := &api.ActivityCreate{
+ CreatorID: api.SystemBotID,
+ ContainerID: *issue.PipelineUID,
+ Type: api.ActivityPipelineStageStatusUpdate,
+ Level: api.ActivityInfo,
+ Payload: string(bytes),
+ }
+ if _, err := s.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{
+ Issue: issue,
+ }); err != nil {
+ return errors.Wrap(err, "failed to create activity")
+ }
+ return nil
+ }(); err != nil {
+ log.Error("failed to create ActivityPipelineStageStatusUpdate activity", zap.Error(err))
}
}
// every task in the stage completes and this is not the last stage.
// create "stage begins" activity.
- if stageTaskAllDone && nextStage != nil {
- createActivityPayload := api.ActivityPipelineStageStatusUpdatePayload{
- StageID: nextStage.ID,
- StageStatusUpdateType: api.StageStatusUpdateTypeBegin,
- IssueName: issue.Title,
- StageName: nextStage.Name,
- }
- bytes, err := json.Marshal(createActivityPayload)
- if err != nil {
- return errors.Wrap(err, "failed to create ActivityPipelineStageStatusUpdate activity")
- }
- activityCreate := &api.ActivityCreate{
- CreatorID: api.SystemBotID,
- ContainerID: *issue.PipelineUID,
- Type: api.ActivityPipelineStageStatusUpdate,
- Level: api.ActivityInfo,
- Payload: string(bytes),
- }
- if _, err := s.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{
- Issue: issue,
- }); err != nil {
- return errors.Wrap(err, "failed to create ActivityPipelineStageStatusUpdate activity")
+ if !taskStage.Active && nextStage != nil {
+ if err := func() error {
+ createActivityPayload := api.ActivityPipelineStageStatusUpdatePayload{
+ StageID: nextStage.ID,
+ StageStatusUpdateType: api.StageStatusUpdateTypeBegin,
+ IssueName: issue.Title,
+ StageName: nextStage.Name,
+ }
+ bytes, err := json.Marshal(createActivityPayload)
+ if err != nil {
+ return errors.Wrap(err, "failed to marshal ActivityPipelineStageStatusUpdate payload")
+ }
+ activityCreate := &api.ActivityCreate{
+ CreatorID: api.SystemBotID,
+ ContainerID: *issue.PipelineUID,
+ Type: api.ActivityPipelineStageStatusUpdate,
+ Level: api.ActivityInfo,
+ Payload: string(bytes),
+ }
+ if _, err := s.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{
+ Issue: issue,
+ }); err != nil {
+ return errors.Wrap(err, "failed to create activity")
+ }
+ return nil
+ }(); err != nil {
+ log.Error("failed to create ActivityPipelineStageStatusUpdate activity", zap.Error(err))
}
}
@@ -1347,7 +1350,7 @@ func (s *Scheduler) onTaskStatusPatched(ctx context.Context, issue *store.IssueM
if taskPatched.Status == api.TaskPending && issue.Project.Workflow == api.UIWorkflow && !stageTaskHasPendingApproval {
needAttention := false
if _, err := s.store.UpdateIssueV2(ctx, issue.UID, &store.UpdateIssueMessage{NeedAttention: &needAttention}, api.SystemBotID); err != nil {
- return errors.Wrapf(err, "failed to patch issue assigneeNeedAttention after finding out that there isn't any pendingApproval task in the stage")
+ log.Error("failed to patch issue assigneeNeedAttention after finding out that there isn't any pendingApproval task in the stage", zap.Error(err))
}
}
diff --git a/backend/server/server.go b/backend/server/server.go
index 3aecc0e3db..43fc7f30d9 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -570,7 +570,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {
v1pb.RegisterSQLServiceServer(s.grpcServer, v1.NewSQLService())
v1pb.RegisterExternalVersionControlServiceServer(s.grpcServer, v1.NewExternalVersionControlService(s.store))
v1pb.RegisterRiskServiceServer(s.grpcServer, v1.NewRiskService(s.store, s.licenseService))
- v1pb.RegisterReviewServiceServer(s.grpcServer, v1.NewReviewService(s.store, s.ActivityManager, s.stateCfg))
+ v1pb.RegisterReviewServiceServer(s.grpcServer, v1.NewReviewService(s.store, s.ActivityManager, s.TaskScheduler, s.stateCfg))
v1pb.RegisterRoleServiceServer(s.grpcServer, v1.NewRoleService(s.store, s.licenseService))
reflection.Register(s.grpcServer)
diff --git a/backend/store/stage.go b/backend/store/stage.go
index a61bf05dde..52c50a3202 100644
--- a/backend/store/stage.go
+++ b/backend/store/stage.go
@@ -12,7 +12,7 @@ type StageMessage struct {
Name string
EnvironmentID int
PipelineID int
- // The earliest stage with incompleted tasks.
+ // Active is true if not all tasks are done within the stage.
Active bool
// Output only.
ID int
@@ -95,11 +95,11 @@ func (s *Store) ListStageV2(ctx context.Context, pipelineUID int) ([]*StageMessa
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
SELECT
- id,
- pipeline_id,
- environment_id,
- name,
- (SELECT COUNT(1) > 0 FROM task as other_task WHERE other_task.pipeline_id = stage.pipeline_id AND other_task.stage_id <= stage.id AND other_task.status != 'DONE')
+ stage.id,
+ stage.pipeline_id,
+ stage.environment_id,
+ stage.name,
+ (SELECT COUNT(1) > 0 FROM task WHERE task.pipeline_id = stage.pipeline_id AND task.stage_id <= stage.id AND task.status != 'DONE')
FROM stage
WHERE %s ORDER BY id ASC`, strings.Join(where, " AND ")),
args...,
diff --git a/backend/utils/utils.go b/backend/utils/utils.go
index b99c112bae..7372f2f8d4 100644
--- a/backend/utils/utils.go
+++ b/backend/utils/utils.go
@@ -219,7 +219,7 @@ func NewMigrationContext(config GhostConfig) (*base.MigrationContext, error) {
return migrationContext, nil
}
-// GetActiveStage returns an active stage among all stages.
+// GetActiveStage returns the first active stage among all stages.
func GetActiveStage(stages []*store.StageMessage) *store.StageMessage {
for _, stage := range stages {
if stage.Active {
@@ -664,25 +664,30 @@ func FindNextPendingStep(template *storepb.ApprovalTemplate, approvers []*storep
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 {
+// CheckApprovalApproved checks if the approval is approved.
+func CheckApprovalApproved(approval *storepb.IssuePayloadApproval) (bool, error) {
+ if approval == nil || !approval.ApprovalFindingDone {
return false, nil
}
- if issuePayload.Approval.ApprovalFindingError != "" {
+ if approval.ApprovalFindingError != "" {
return false, nil
}
- if len(issuePayload.Approval.ApprovalTemplates) == 0 {
+ if len(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))
+ if len(approval.ApprovalTemplates) != 1 {
+ return false, errors.Errorf("expecting one approval template but got %d", len(approval.ApprovalTemplates))
+ }
+ return FindNextPendingStep(approval.ApprovalTemplates[0], approval.Approvers) == nil, nil
+}
+
+// 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")
}
- return FindNextPendingStep(issuePayload.Approval.ApprovalTemplates[0], issuePayload.Approval.Approvers) == nil, nil
+ return CheckApprovalApproved(issuePayload.Approval)
}
// SkipApprovalStepIfNeeded skips approval steps if no user can approve the step.