Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: unify approval notification logic and simplify helper function signatures (#18714)
Danny Xu238e3d6c3121
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.goindex 761cd8ede4..3b5e4a99bf 100644--- a/backend/api/v1/issue_service.go+++ b/backend/api/v1/issue_service.go@@ -553,12 +553,12 @@ func (s *IssueService) ApproveIssue(ctx context.Context, req *connect.Request[v1return nil, connect.NewError(connect.CodeInternal, errors.New("approval template is required"))}- rejectedRole := utils.FindRejectedRole(payload.Approval.ApprovalTemplate, payload.Approval.Approvers)+ rejectedRole := utils.FindRejectedRole(payload.Approval)if rejectedRole != "" {return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("cannot approve because the issue has been rejected"))}- role := utils.FindNextPendingRole(payload.Approval.ApprovalTemplate, payload.Approval.Approvers)+ role := utils.FindNextPendingRole(payload.Approval)if role == "" {return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("the issue has been approved"))}@@ -614,43 +614,7 @@ func (s *IssueService) ApproveIssue(ctx context.Context, req *connect.Request[v1slog.Warn("failed to create issue comment", log.BBError(err))}- func() {- if payload.Approval.ApprovalTemplate == nil {- return- }- // Notify next approvers if approval is not complete- role := utils.FindNextPendingRole(payload.Approval.ApprovalTemplate, payload.Approval.Approvers)- if role == "" {- return- }-- approvers, err := s.getApproversForRole(ctx, issue.ProjectID, role)- if err != nil {- slog.Error("failed to get approvers for next role", slog.String("role", role), log.BBError(err))- return- }-- // Get issue creator for webhook event- creator, err := s.store.GetUserByEmail(ctx, issue.CreatorEmail)- if err != nil {- slog.Warn("failed to get issue creator, using system bot", log.BBError(err))- creator = store.SystemBotUser- }-- // Send ISSUE_APPROVAL_REQUESTED webhook- s.webhookManager.CreateEvent(ctx, &webhook.Event{- Type: storepb.Activity_ISSUE_APPROVAL_REQUESTED,- Project: webhook.NewProject(project),- ApprovalRequested: &webhook.EventIssueApprovalRequested{- Creator: &webhook.User{- Name: creator.Name,- Email: creator.Email,- },- Issue: webhook.NewIssue(issue),- Approvers: approvers,- },- })- }()+ approval.NotifyApprovalRequested(ctx, s.store, s.webhookManager, issue, project)// If the issue is a grant request and approved, we will always auto close it.if issue.Type == storepb.Issue_GRANT_REQUEST {@@ -726,12 +690,12 @@ func (s *IssueService) RejectIssue(ctx context.Context, req *connect.Request[v1preturn nil, connect.NewError(connect.CodeInternal, errors.New("approval template is required"))}- rejectedRole := utils.FindRejectedRole(payload.Approval.ApprovalTemplate, payload.Approval.Approvers)+ rejectedRole := utils.FindRejectedRole(payload.Approval)if rejectedRole != "" {return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("cannot reject because the issue has been rejected"))}- role := utils.FindNextPendingRole(payload.Approval.ApprovalTemplate, payload.Approval.Approvers)+ role := utils.FindNextPendingRole(payload.Approval)if role == "" {return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("the issue has been approved"))}@@ -829,7 +793,7 @@ func (s *IssueService) RequestIssue(ctx context.Context, req *connect.Request[v1return nil, connect.NewError(connect.CodeInternal, errors.New("approval template is required"))}- rejectedRole := utils.FindRejectedRole(payload.Approval.ApprovalTemplate, payload.Approval.Approvers)+ rejectedRole := utils.FindRejectedRole(payload.Approval)if rejectedRole == "" {return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("cannot request issues because the issue is not rejected"))}@@ -862,42 +826,7 @@ func (s *IssueService) RequestIssue(ctx context.Context, req *connect.Request[v1return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update issue"))}- func() {- if payload.Approval.ApprovalTemplate == nil {- return- }- role := utils.FindNextPendingRole(payload.Approval.ApprovalTemplate, payload.Approval.Approvers)- if role == "" {- return- }-- approvers, err := s.getApproversForRole(ctx, issue.ProjectID, role)- if err != nil {- slog.Error("failed to get approvers for next role", slog.String("role", role), log.BBError(err))- return- }-- // Get issue creator for webhook event- creator, err := s.store.GetUserByEmail(ctx, issue.CreatorEmail)- if err != nil {- slog.Warn("failed to get issue creator, using system bot", log.BBError(err))- creator = store.SystemBotUser- }-- // Send ISSUE_APPROVAL_REQUESTED webhook- s.webhookManager.CreateEvent(ctx, &webhook.Event{- Type: storepb.Activity_ISSUE_APPROVAL_REQUESTED,- Project: webhook.NewProject(project),- ApprovalRequested: &webhook.EventIssueApprovalRequested{- Creator: &webhook.User{- Name: creator.Name,- Email: creator.Email,- },- Issue: webhook.NewIssue(issue),- Approvers: approvers,- },- })- }()+ approval.NotifyApprovalRequested(ctx, s.store, s.webhookManager, issue, project)if _, err := s.store.CreateIssueComments(ctx, user.Email, &store.IssueCommentMessage{IssueUID: issue.UID,@@ -1319,35 +1248,3 @@ func (s *IssueService) isUserReviewer(ctx context.Context, issue *store.IssueMesfunc canRequestIssue(issueCreatorEmail string, user *store.UserMessage) bool {return issueCreatorEmail == user.Email}--func (s *IssueService) getApproversForRole(ctx context.Context, projectID string, role string) ([]webhook.User, error) {- // Get project IAM policy- projectIAM, err := s.store.GetProjectIamPolicy(ctx, projectID)- if err != nil {- return nil, errors.Wrap(err, "failed to get project IAM policy")- }-- // Get workspace IAM policy- workspaceIAM, err := s.store.GetWorkspaceIamPolicy(ctx)- if err != nil {- return nil, errors.Wrap(err, "failed to get workspace IAM policy")- }-- // Get all users with the specified role- users := utils.GetUsersByRoleInIAMPolicy(ctx, s.store, role, projectIAM.Policy, workspaceIAM.Policy)-- // Convert to webhook.User format, filtering by END_USER principal type- approvers := make([]webhook.User, 0, len(users))- for _, user := range users {- // Only include END_USER principals as approvers- if user.Type != storepb.PrincipalType_END_USER {- continue- }- approvers = append(approvers, webhook.User{- Name: user.Name,- Email: user.Email,- })- }-- return approvers, nil-}diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.goindex 925fe6164b..ab7d7e4d97 100644--- a/backend/runner/approval/runner.go+++ b/backend/runner/approval/runner.go@@ -210,47 +210,16 @@ func findApprovalTemplateForIssue(ctx context.Context, stores *store.Store, webh}payload.RiskLevel = riskLevel- if err := updateIssueApprovalPayload(ctx, stores, issue, payload.Approval, riskLevel); err != nil {+ if _, err := stores.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.Issue{+ Approval: payload.Approval,+ RiskLevel: riskLevel,+ },+ }); err != nil {return errors.Wrap(err, "failed to update issue payload")}- func() {- if payload.Approval.ApprovalTemplate == nil {- return- }- role := utils.FindNextPendingRole(payload.Approval.ApprovalTemplate, payload.Approval.Approvers)- if role == "" {- return- }-- // Get issue creator as actor- creator, err := stores.GetUserByEmail(ctx, issue.CreatorEmail)- if err != nil {- slog.Warn("failed to get issue creator, using system bot", log.BBError(err))- creator = store.SystemBotUser- }-- // Get approvers for this role- approvers, err := getApproversForRole(ctx, stores, issue.ProjectID, role)- if err != nil {- slog.Warn("failed to get approvers", log.BBError(err))- approvers = []webhook.User{} // Continue with empty list- }-- // Trigger ISSUE_APPROVAL_REQUESTED webhook- webhookManager.CreateEvent(ctx, &webhook.Event{- Type: storepb.Activity_ISSUE_APPROVAL_REQUESTED,- Project: webhook.NewProject(project),- ApprovalRequested: &webhook.EventIssueApprovalRequested{- Creator: &webhook.User{- Name: creator.Name,- Email: creator.Email,- },- Issue: webhook.NewIssue(issue),- Approvers: approvers,- },- })- }()+ NotifyApprovalRequested(ctx, stores, webhookManager, issue, project)return nil}@@ -839,18 +808,6 @@ func getApprovalSourceFromIssue(ctx context.Context, stores *store.Store, issue}}-func updateIssueApprovalPayload(ctx context.Context, stores *store.Store, issue *store.IssueMessage, approval *storepb.IssuePayloadApproval, riskLevel storepb.RiskLevel) error {- if _, err := stores.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{- PayloadUpsert: &storepb.Issue{- Approval: approval,- RiskLevel: riskLevel,- },- }); err != nil {- return errors.Wrap(err, "failed to update issue payload")- }- return nil-}-// expandCELVars creates CEL variable maps for each combination of statement types and table names.func expandCELVars(base map[string]any, statementTypes, tableNames []string) []map[string]any {if len(statementTypes) == 0 {@@ -925,3 +882,44 @@ func getApproversForRole(ctx context.Context, stores *store.Store, projectID strreturn approvers, nil}++// NotifyApprovalRequested sends the ISSUE_APPROVAL_REQUESTED webhook event for the next pending approval stage.+// It finds the next pending role, retrieves approvers for that role, and triggers the webhook.+// This should be called after:+// - Creating an issue with an approval template+// - Approving an issue stage (to notify next stage approvers)+// - Sending back an issue (to notify the current stage approvers again)+func NotifyApprovalRequested(ctx context.Context, stores *store.Store, webhookManager *webhook.Manager, issue *store.IssueMessage, project *store.ProjectMessage) {+ role := utils.FindNextPendingRole(issue.Payload.Approval)+ if role == "" {+ return+ }++ // Get issue creator as actor+ creator, err := stores.GetUserByEmail(ctx, issue.CreatorEmail)+ if err != nil {+ slog.Warn("failed to get issue creator, using system bot", log.BBError(err))+ creator = store.SystemBotUser+ }++ // Get approvers for this role+ approvers, err := getApproversForRole(ctx, stores, issue.ProjectID, role)+ if err != nil {+ slog.Warn("failed to get approvers", log.BBError(err))+ approvers = []webhook.User{} // Continue with empty list+ }++ // Trigger ISSUE_APPROVAL_REQUESTED webhook+ webhookManager.CreateEvent(ctx, &webhook.Event{+ Type: storepb.Activity_ISSUE_APPROVAL_REQUESTED,+ Project: webhook.NewProject(project),+ ApprovalRequested: &webhook.EventIssueApprovalRequested{+ Creator: &webhook.User{+ Name: creator.Name,+ Email: creator.Email,+ },+ Issue: webhook.NewIssue(issue),+ Approvers: approvers,+ },+ })+}diff --git a/backend/utils/utils.go b/backend/utils/utils.goindex 387d0905c8..171796ebbe 100644--- a/backend/utils/utils.go+++ b/backend/utils/utils.go@@ -31,25 +31,31 @@ func DataSourceFromInstanceWithType(instance *store.InstanceMessage, dataSourceT}// FindNextPendingRole finds the next pending role in the approval flow.-func FindNextPendingRole(template *storepb.ApprovalTemplate, approvers []*storepb.IssuePayloadApproval_Approver) string {+func FindNextPendingRole(approval *storepb.IssuePayloadApproval) string {+ if approval == nil || approval.ApprovalTemplate == nil {+ return ""+ }// We can do the finding like this for now because we are presuming that// one role is approved by one approver.// and the approver status is either// APPROVED or REJECTED.- if len(approvers) >= len(template.Flow.Roles) {+ if len(approval.Approvers) >= len(approval.ApprovalTemplate.Flow.Roles) {return ""}- return template.Flow.Roles[len(approvers)]+ return approval.ApprovalTemplate.Flow.Roles[len(approval.Approvers)]}// FindRejectedRole finds the rejected role in the approval flow.-func FindRejectedRole(template *storepb.ApprovalTemplate, approvers []*storepb.IssuePayloadApproval_Approver) string {- for i, approver := range approvers {- if i >= len(template.Flow.Roles) {+func FindRejectedRole(approval *storepb.IssuePayloadApproval) string {+ if approval == nil || approval.ApprovalTemplate == nil {+ return ""+ }+ for i, approver := range approval.Approvers {+ if i >= len(approval.ApprovalTemplate.Flow.Roles) {return ""}if approver.Status == storepb.IssuePayloadApproval_Approver_REJECTED {- return template.Flow.Roles[i]+ return approval.ApprovalTemplate.Flow.Roles[i]}}return ""@@ -63,7 +69,7 @@ func CheckApprovalApproved(approval *storepb.IssuePayloadApproval) (bool, error)if approval.ApprovalTemplate == nil {return true, nil}- return FindRejectedRole(approval.ApprovalTemplate, approval.Approvers) == "" && FindNextPendingRole(approval.ApprovalTemplate, approval.Approvers) == "", nil+ return FindRejectedRole(approval) == "" && FindNextPendingRole(approval) == "", nil}// CheckIssueApproved checks if the issue is approved.