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: feishu external approval runner (#3339)
p0nyeaac9d2c1f98
diff --git a/api/external_approval.go b/api/external_approval.goindex 533e44178d..409c01e9bc 100644--- a/api/external_approval.go+++ b/api/external_approval.go@@ -51,7 +51,9 @@ type ExternalApprovalCreate struct {}// ExternalApprovalFind is the API message for finding ExternalApprovals.-type ExternalApprovalFind struct{}+type ExternalApprovalFind struct {+ IssueID *int+}// ExternalApprovalPatch is the API message for patching an ExternalApproval.type ExternalApprovalPatch struct {diff --git a/plugin/app/feishu/feishu.go b/plugin/app/feishu/feishu.goindex 6e14b1da17..5765e4c049 100644--- a/plugin/app/feishu/feishu.go+++ b/plugin/app/feishu/feishu.go@@ -46,9 +46,24 @@ func NewProvider() *Provider {type TokenCtx struct {AppID stringAppSecret string- Token string}+// ApprovalStatus is the status of an external approval.+type ApprovalStatus string++const (+ // ApprovalStatusPending is the approval status for pending approvals.+ ApprovalStatusPending = ApprovalStatus("PENDING")+ // ApprovalStatusApproved is the approval status for approved approvals.+ ApprovalStatusApproved = ApprovalStatus("APPROVED")+ // ApprovalStatusRejected is the approval status for rejected approvals.+ ApprovalStatusRejected = ApprovalStatus("REJECTED")+ // ApprovalStatusCanceled is the approval status for canceled approvals.+ ApprovalStatusCanceled = ApprovalStatus("CANCELED")+ // ApprovalStatusDeleted is the approval status for deleted approvals.+ ApprovalStatusDeleted = ApprovalStatus("DELETED")+)+// tenantAccessTokenResponse is the response of GetTenantAccessToken.type tenantAccessTokenResponse struct {Code int `json:"code"`@@ -93,7 +108,7 @@ type getExternalApprovalResponse struct {Code int `json:"code"`Msg string `json:"msg"`Data struct {- Status string `json:"status"`+ Status ApprovalStatus `json:"status"`} `json:"data"`}@@ -216,10 +231,10 @@ const (}`)-func (p *Provider) tokenRefresher(appID, appSecret string) tokenRefresher {+func (p *Provider) tokenRefresher(tokenCtx TokenCtx) tokenRefresher {return func(ctx context.Context, client *http.Client, oldToken *string) error {const url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"- body := strings.NewReader(fmt.Sprintf(getTenantAccessTokenReq, appID, appSecret))+ body := strings.NewReader(fmt.Sprintf(getTenantAccessTokenReq, tokenCtx.AppID, tokenCtx.AppSecret))req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body)if err != nil {return errors.Wrapf(err, "construct POST %s", url)@@ -255,8 +270,9 @@ func (p *Provider) tokenRefresher(appID, appSecret string) tokenRefresher {}}-func do(ctx context.Context, client *http.Client, method, url string, token *string, body []byte, tokenRefresher tokenRefresher) (code int, header http.Header, respBody string, err error) {- return retry(ctx, client, token, tokenRefresher, requester(ctx, client, method, url, token, body))+func (p *Provider) do(ctx context.Context, client *http.Client, method, url string, body []byte, tokenRefresher tokenRefresher) (code int, header http.Header, respBody string, err error) {+ token := p.Token.Load().(string)+ return retry(ctx, client, &token, tokenRefresher, requester(ctx, client, method, url, &token, body))}// The type of body is []byte because it could be read multiple times but io.Reader can only be read once.@@ -324,7 +340,7 @@ func retry(ctx context.Context, client *http.Client, token *string, tokenRefreshfunc (p *Provider) CreateApprovalDefinition(ctx context.Context, tokenCtx TokenCtx, approvalCode string) (string, error) {body := []byte(fmt.Sprintf(createApprovalDefinitionReq, approvalCode))const url = "https://open.feishu.cn/open-apis/approval/v4/approvals"- code, _, b, err := do(ctx, p.client, http.MethodPost, url, &tokenCtx.Token, body, p.tokenRefresher(tokenCtx.AppID, tokenCtx.AppSecret))+ code, _, b, err := p.do(ctx, p.client, http.MethodPost, url, body, p.tokenRefresher(tokenCtx))if err != nil {return "", errors.Wrapf(err, "POST %s", url)}@@ -345,7 +361,7 @@ func (p *Provider) CreateApprovalDefinition(ctx context.Context, tokenCtx TokenCreturn response.Data.ApprovalCode, nil}-// CreateExternalApproval creates an approval instance and returns instance code.+// CreateExternalApproval creates an external approval and returns instance code.// The requester requests the approval of the approver.// example approvalCode: 813718CE-F38D-45CA-A5C1-ACF4F564B526// example requesterID & approverID: ou_3cda9c969f737aaa05e6915dce306cb9@@ -374,7 +390,7 @@ func (p *Provider) CreateExternalApproval(ctx context.Context, tokenCtx TokenCtxif err != nil {return "", errors.Wrapf(err, "failed to marshal payload %+v", payload)}- code, _, b, err := do(ctx, p.client, http.MethodPost, url, &tokenCtx.Token, body, p.tokenRefresher(tokenCtx.AppID, tokenCtx.AppSecret))+ code, _, b, err := p.do(ctx, p.client, http.MethodPost, url, body, p.tokenRefresher(tokenCtx))if err != nil {return "", errors.Wrapf(err, "POST %s", url)}@@ -388,18 +404,18 @@ func (p *Provider) CreateExternalApproval(ctx context.Context, tokenCtx TokenCtx}if response.Code != 0 {- return "", errors.Errorf("failed to create approval instance, code %d, msg %s", response.Code, response.Msg)+ return "", errors.Errorf("failed to create external approval, code %d, msg %s", response.Code, response.Msg)}return response.Data.InstanceCode, nil}-// GetExternalApprovalStatus gets and returns the status of an approval instance.+// GetExternalApprovalStatus gets and returns the status of an external approval.// example instanceCode: 81D31358-93AF-92D6-7425-01A5D67C4E71// https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/approval-v4/instance/get-func (p *Provider) GetExternalApprovalStatus(ctx context.Context, tokenCtx TokenCtx, instanceCode string) (string, error) {+func (p *Provider) GetExternalApprovalStatus(ctx context.Context, tokenCtx TokenCtx, instanceCode string) (ApprovalStatus, error) {url := fmt.Sprintf("https://open.feishu.cn/open-apis/approval/v4/instances/%s", instanceCode)- code, _, b, err := do(ctx, p.client, http.MethodGet, url, &tokenCtx.Token, nil, p.tokenRefresher(tokenCtx.AppID, tokenCtx.AppSecret))+ code, _, b, err := p.do(ctx, p.client, http.MethodGet, url, nil, p.tokenRefresher(tokenCtx))if err != nil {return "", errors.Wrapf(err, "GET %s", url)}@@ -412,18 +428,18 @@ func (p *Provider) GetExternalApprovalStatus(ctx context.Context, tokenCtx Tokenreturn "", errors.Wrap(err, "failed to unmarshal response to GetExternalApprovalResponse")}if response.Code != 0 {- return "", errors.Errorf("failed to get approval instance, code %d, msg %s", response.Code, response.Msg)+ return "", errors.Errorf("failed to get external approval, code %d, msg %s", response.Code, response.Msg)}return response.Data.Status, nil}-// CancelExternalApproval cancels an approval instance.+// CancelExternalApproval cancels an external approval.// https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/approval-v4/instance/cancelfunc (p *Provider) CancelExternalApproval(ctx context.Context, tokenCtx TokenCtx, approvalCode, instanceCode, userID string) error {const url = "https://open.feishu.cn/open-apis/approval/v4/instances/cancel"body := []byte(fmt.Sprintf(cancelExternalApprovalReq, approvalCode, instanceCode, userID))- code, _, b, err := do(ctx, p.client, http.MethodPost, url, &tokenCtx.Token, body, p.tokenRefresher(tokenCtx.AppID, tokenCtx.AppSecret))+ code, _, b, err := p.do(ctx, p.client, http.MethodPost, url, body, p.tokenRefresher(tokenCtx))if err != nil {return errors.Wrapf(err, "POST %s", url)}@@ -437,7 +453,7 @@ func (p *Provider) CancelExternalApproval(ctx context.Context, tokenCtx TokenCtx}if response.Code != 0 {- return errors.Errorf("failed to create approval instance, code %d, msg %s", response.Code, response.Msg)+ return errors.Errorf("failed to create external approval, code %d, msg %s", response.Code, response.Msg)}return nil@@ -456,7 +472,7 @@ func (p *Provider) GetIDByEmail(ctx context.Context, tokenCtx TokenCtx, emails [return nil, err}- code, _, b, err := do(ctx, p.client, http.MethodPost, url, &tokenCtx.Token, body, p.tokenRefresher(tokenCtx.AppID, tokenCtx.AppSecret))+ code, _, b, err := p.do(ctx, p.client, http.MethodPost, url, body, p.tokenRefresher(tokenCtx))if err != nil {return nil, err}diff --git a/plugin/app/feishu/feishu_test.go b/plugin/app/feishu/feishu_test.goindex 998ebbdf66..1f43e9879d 100644--- a/plugin/app/feishu/feishu_test.go+++ b/plugin/app/feishu/feishu_test.go@@ -128,7 +128,7 @@ func TestProvider_GetExternalApprovalStatus(t *testing.T) {ctx := context.Background()status, err := p.GetExternalApprovalStatus(ctx, TokenCtx{}, "")a.NoError(err)- want := "PENDING"+ want := ApprovalStatusPendinga.Equal(want, status)}diff --git a/server/application_runner.go b/server/application_runner.gonew file mode 100644index 0000000000..72deefa698--- /dev/null+++ b/server/application_runner.go@@ -0,0 +1,370 @@+package server++import (+ "context"+ "encoding/json"+ "fmt"+ "sync"+ "time"++ "github.com/pkg/errors"+ "go.uber.org/zap"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common/log"+ "github.com/bytebase/bytebase/plugin/app/feishu"+ "github.com/bytebase/bytebase/store"+)++const applicationRunnerInterval = time.Duration(60) * time.Second++// NewApplicationRunner returns a ApplicationRunner.+func NewApplicationRunner(store *store.Store, activityManager *ActivityManager) *ApplicationRunner {+ return &ApplicationRunner{+ store: store,+ activityManager: activityManager,+ p: feishu.NewProvider(),+ }+}++// ApplicationRunner is a runner which periodically checks external approval status and approve the correspoding stages.+type ApplicationRunner struct {+ store *store.Store+ activityManager *ActivityManager+ p *feishu.Provider+}++// Run runs the ApplicationRunner.+func (r *ApplicationRunner) Run(ctx context.Context, wg *sync.WaitGroup) {+ ticker := time.NewTicker(taskSchedulerInterval)+ defer ticker.Stop()+ defer wg.Done()+ log.Debug(fmt.Sprintf("Application runner started and will run every %v", applicationRunnerInterval))+ for {+ select {+ case <-ticker.C:+ func() {+ settingName := api.SettingAppIM+ setting, err := r.store.GetSetting(ctx, &api.SettingFind{Name: &settingName})+ if err != nil {+ log.Error("failed to get setting by settingName", zap.String("settingName", string(settingName)), zap.Error(err))+ return+ }+ if setting == nil {+ return+ }+ var value api.SettingAppIMValue+ if err := json.Unmarshal([]byte(setting.Value), &value); err != nil {+ log.Error("failed to unmarshal", zap.Error(err))+ return+ }+ if !value.ExternalApproval.Enabled {+ return+ }++ externalApprovalList, err := r.store.FindExternalApproval(ctx, &api.ExternalApprovalFind{})+ if err != nil {+ log.Error("failed to find external approval list", zap.Error(err))+ return+ }++ for _, externalApproval := range externalApprovalList {+ switch externalApproval.Type {+ case api.ExternalApprovalTypeFeishu:+ var payload api.ExternalApprovalPayloadFeishu+ if err := json.Unmarshal([]byte(externalApproval.Payload), &payload); err != nil {+ log.Error("failed to unmarshal to ExternalApprovalPayloadFeishu", zap.String("payload", externalApproval.Payload), zap.Error(err))+ continue+ }++ issue, err := r.store.GetIssueByID(ctx, externalApproval.IssueID)+ stage := getActiveStage(issue.Pipeline.StageList)+ if stage == nil {+ stage = issue.Pipeline.StageList[len(issue.Pipeline.StageList)-1]+ }+ if err != nil {+ log.Error("failed to get issue by issue id", zap.Int("issueID", externalApproval.IssueID), zap.Error(err))+ continue+ }+ if issue.Status != api.IssueOpen {+ if _, err := r.cancelOldExternalApprovalIfNeeded(ctx, issue, stage, &value); err != nil {+ log.Error("failed to cancel external approval", zap.Error(err))+ continue+ }+ }++ status, err := r.p.GetExternalApprovalStatus(ctx, feishu.TokenCtx{+ AppID: value.AppID,+ AppSecret: value.AppSecret,+ }, payload.InstanceCode)+ if err != nil {+ log.Error("failed to get external approval", zap.String("instanceCode", payload.InstanceCode), zap.Error(err))+ continue+ }++ if status == feishu.ApprovalStatusApproved {+ // double check+ if stage.ID == payload.StageID && payload.AssigneeID == issue.AssigneeID {+ // approve stage+ if err := func() error {+ var taskIDList []int+ var tasks []*api.Task+ for _, task := range stage.TaskList {+ if task.Status == api.TaskPendingApproval {+ taskIDList = append(taskIDList, task.ID)+ tasks = append(tasks, task)+ }+ }+ taskStatusPatch := &api.TaskStatusPatch{+ IDList: taskIDList,+ UpdaterID: externalApproval.ApproverID,+ Status: api.TaskPending,+ }+ _, err := r.store.PatchTaskStatus(ctx, taskStatusPatch)+ if err != nil {+ return errors.Wrapf(err, "failed to update task status, task id list: %+v", taskIDList)+ }+ if err := r.activityManager.BatchCreateTaskStatusUpdateApprovalActivity(ctx, taskStatusPatch, issue, stage, tasks); err != nil {+ return errors.Wrapf(err, "failed to create task status update activity")+ }+ return nil+ }(); err != nil {+ log.Error("failed to approve stage", zap.Error(err))+ }++ if _, err := r.store.PatchExternalApproval(ctx, &api.ExternalApprovalPatch{+ // Archive external approval.+ ID: externalApproval.ID,+ RowStatus: api.Archived,+ }); err != nil {+ log.Error("failed to archive external apporval", zap.Error(err))+ }+ }+ } else if status != feishu.ApprovalStatusPending {+ if _, err := r.store.PatchExternalApproval(ctx, &api.ExternalApprovalPatch{+ // Archive external approval if it's not pending.+ ID: externalApproval.ID,+ RowStatus: api.Archived,+ }); err != nil {+ log.Error("failed to archive external apporval", zap.Error(err))+ }+ }++ default:+ log.Error("Unknown ExternalApproval.Type", zap.Any("ExternalApproval", externalApproval))+ }+ }+ }()+ case <-ctx.Done():+ return+ }+ }+}++func (r *ApplicationRunner) cancelOldExternalApprovalIfNeeded(ctx context.Context, issue *api.Issue, stage *api.Stage, settingValue *api.SettingAppIMValue) (*api.ExternalApproval, error) {+ approval, err := r.store.GetExternalApprovalByIssueID(ctx, issue.ID)+ if err != nil {+ return nil, err+ }+ if approval == nil {+ return nil, nil+ }+ var payload api.ExternalApprovalPayloadFeishu+ if err := json.Unmarshal([]byte(approval.Payload), &payload); err != nil {+ return nil, err+ }++ cancelOld := func() bool {+ if payload.StageID != stage.ID {+ return true+ }+ if payload.AssigneeID != issue.AssigneeID {+ return true+ }+ pendingApprovalCount := 0+ for _, task := range stage.TaskList {+ if task.Status == api.TaskPendingApproval {+ pendingApprovalCount+++ }+ }+ return pendingApprovalCount == 0+ }()++ if cancelOld {+ _, err := r.store.PatchExternalApproval(ctx, &api.ExternalApprovalPatch{ID: approval.ID, RowStatus: api.Archived})+ if err != nil {+ return nil, err+ }+ if err := r.p.CancelExternalApproval(ctx,+ feishu.TokenCtx{+ AppID: settingValue.AppID,+ AppSecret: settingValue.AppSecret,+ },+ settingValue.ExternalApproval.ApprovalCode,+ payload.InstanceCode,+ payload.RequesterID,+ ); err != nil {+ return nil, err+ }+ }+ return approval, nil+}++func (*ApplicationRunner) shouldCreateExternalApproval(issue *api.Issue, stage *api.Stage, oldApproval *api.ExternalApproval) (bool, error) {+ if oldApproval != nil {+ var oldPayload api.ExternalApprovalPayloadFeishu+ if err := json.Unmarshal([]byte(oldApproval.Payload), &oldPayload); err != nil {+ return false, err+ }+ // nothing changes+ if oldPayload.StageID == stage.ID && oldPayload.AssigneeID == issue.AssigneeID {+ return false, nil+ }+ }+ pendingApprovalCount := 0+ for _, task := range stage.TaskList {+ if task.Status == api.TaskPendingApproval {+ pendingApprovalCount+++ }+ for _, taskCheck := range task.TaskCheckRunList {+ if taskCheck.Status != api.TaskCheckRunDone {+ return false, nil+ }+ var payload api.TaskCheckRunResultPayload+ if err := json.Unmarshal([]byte(taskCheck.Result), &payload); err != nil {+ return false, err+ }+ for _, result := range payload.ResultList {+ if result.Status == api.TaskCheckStatusError {+ return false, nil+ }+ }+ }+ }+ if pendingApprovalCount == 0 {+ return false, nil+ }+ return true, nil+}++func (r *ApplicationRunner) createExternalApproval(ctx context.Context, s *Server, issue *api.Issue, stage *api.Stage, settingValue *api.SettingAppIMValue) error {+ users, err := r.p.GetIDByEmail(ctx,+ feishu.TokenCtx{+ AppID: settingValue.AppID,+ AppSecret: settingValue.AppSecret,+ },+ []string{issue.Creator.Email, issue.Assignee.Email})+ log.Info("appp", zap.Any("users", users))+ if err != nil {+ log.Error("failed to get id by email", zap.Any("resp", users))+ return err+ }+ instanceCode, err := r.p.CreateExternalApproval(ctx,+ feishu.TokenCtx{+ AppID: settingValue.AppID,+ AppSecret: settingValue.AppSecret,+ },+ feishu.Content{+ Issue: issue.Name,+ Stage: stage.Name,+ },+ settingValue.ExternalApproval.ApprovalCode,+ users[issue.Creator.Email],+ users[issue.Assignee.Email])+ if err != nil {+ return err+ }++ payload := api.ExternalApprovalPayloadFeishu{+ StageID: stage.ID,+ AssigneeID: issue.AssigneeID,+ InstanceCode: instanceCode,+ RequesterID: users[issue.Creator.Email],+ }+ b, err := json.Marshal(payload)+ if err != nil {+ return err+ }+ _, err = s.store.CreateExternalApproval(ctx, &api.ExternalApprovalCreate{+ IssueID: issue.ID,+ ApproverID: issue.AssigneeID,+ RequesterID: issue.CreatorID,+ Type: api.ExternalApprovalTypeFeishu,+ Payload: string(b),+ })+ if err != nil {+ return err+ }+ return nil+}++// ScheduleApproval tries to cancel old external apporvals and create new external approvals if needed.+func (r *ApplicationRunner) ScheduleApproval(s *Server, pipeline *api.Pipeline) {+ ctx := context.Background()+ settingName := api.SettingAppIM+ setting, err := s.store.GetSetting(ctx, &api.SettingFind{Name: &settingName})+ if err != nil {+ log.Error("failed to get setting by settingName", zap.String("settingName", string(settingName)), zap.Error(err))+ return+ }+ var settingValue api.SettingAppIMValue+ if err := json.Unmarshal([]byte(setting.Value), &settingValue); err != nil {+ log.Error("failed to unmarshal to settingValue", zap.Error(err))+ return+ }++ if !settingValue.ExternalApproval.Enabled {+ return+ }++ if settingValue.ExternalApproval.ApprovalCode == "" {+ log.Error("no approval code", zap.Any("settingValue", settingValue))+ return+ }++ find := &api.IssueFind{+ PipelineID: &pipeline.ID,+ StatusList: []api.IssueStatus{api.IssueOpen},+ }+ issues, err := s.store.FindIssueStripped(ctx, find)+ if err != nil {+ log.Error("failed to find issues", zap.Any("issueFind", find), zap.Error(err))+ return+ }+ if len(issues) > 1 {+ log.Error("expect 0 or 1 issue, get more than 1 issues", zap.Any("issues", issues))+ return+ }+ if len(issues) == 0 {+ // no containing issue, skip+ return+ }+ issue := issues[0]+ stage := getActiveStage(pipeline.StageList)+ if stage == nil {+ stage = pipeline.StageList[len(pipeline.StageList)-1]+ }++ oldApproval, err := r.cancelOldExternalApprovalIfNeeded(ctx, issue, stage, &settingValue)+ if err != nil {+ log.Error("failed to cancelOldExternalApprovalIfNeeded", zap.Error(err))+ }++ // createExternalApprovalIfNeeded+ // check if we need to create a new external approval+ // 1. has one or more PENDING_APPROVAL tasks.+ // 2. all task checks are done and the results have no errors.+ ok, err := r.shouldCreateExternalApproval(issue, stage, oldApproval)+ if err != nil {+ log.Error("failed to check shouldCreateExternalApproval", zap.Error(err))+ return+ }+ if !ok {+ return+ }++ if err := r.createExternalApproval(ctx, s, issue, stage, &settingValue); err != nil {+ log.Error("failed to create external approval", zap.Error(err))+ return+ }+}diff --git a/server/server.go b/server/server.goindex d9ed740900..903c86039e 100644--- a/server/server.go+++ b/server/server.go@@ -50,6 +50,7 @@ type Server struct {SchemaSyncer *SchemaSyncerBackupRunner *BackupRunnerAnomalyScanner *AnomalyScanner+ ApplicationRunner *ApplicationRunnerrunnerWG sync.WaitGroupActivityManager *ActivityManager@@ -200,6 +201,8 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {s.secret = config.secrets.workspaceID = config.workspaceID+ s.ActivityManager = NewActivityManager(s, storeInstance)+e := echo.New()e.Debug = prof.Debuge.HideBanner = true@@ -289,6 +292,8 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {// Backup runners.BackupRunner = NewBackupRunner(s, prof.BackupRunnerInterval)+ s.ApplicationRunner = NewApplicationRunner(s.store, s.ActivityManager)+// Anomaly scanners.AnomalyScanner = NewAnomalyScanner(s)@@ -380,7 +385,6 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {p := prometheus.NewPrometheus("api", nil)p.Use(e)- s.ActivityManager = NewActivityManager(s, storeInstance)s.LicenseService, err = enterpriseService.NewLicenseService(prof.Mode, s.store)if err != nil {return nil, errors.Wrap(err, "failed to create license service")@@ -497,6 +501,8 @@ func (s *Server) Run(ctx context.Context, port int) error {go s.BackupRunner.Run(ctx, &s.runnerWG)s.runnerWG.Add(1)go s.AnomalyScanner.Run(ctx, &s.runnerWG)+ s.runnerWG.Add(1)+ go s.ApplicationRunner.Run(ctx, &s.runnerWG)if s.MetricReporter != nil {s.runnerWG.Add(1)diff --git a/server/setting.go b/server/setting.goindex a3a2f3f42b..87294ac60a 100644--- a/server/setting.go+++ b/server/setting.go@@ -1,6 +1,8 @@package serverimport (+ "encoding/json"+ "errors""fmt""net/http"@@ -9,15 +11,14 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/app/feishu")-var (- // Some settings contain secret info so we only return settings that are needed by the client.- whitelistSettings = []api.SettingName{- api.SettingBrandingLogo,- api.SettingAppIM,- }-)+// Some settings contain secret info so we only return settings that are needed by the client.+var whitelistSettings = []api.SettingName{+ api.SettingBrandingLogo,+ api.SettingAppIM,+}func (s *Server) registerSettingRoutes(g *echo.Group) {g.GET("/setting", func(c echo.Context) error {@@ -60,6 +61,30 @@ func (s *Server) registerSettingRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Malformed update setting request").SetInternal(err)}+ if settingPatch.Name == api.SettingAppIM {+ var value api.SettingAppIMValue+ if err := json.Unmarshal([]byte(settingPatch.Value), &value); err != nil {+ return err+ }+ if value.IMType != (api.IMTypeFeishu) {+ return errors.New("unknown IM type")+ }+ p := s.ApplicationRunner.p+ approvalCode, err := p.CreateApprovalDefinition(ctx, feishu.TokenCtx{+ AppID: value.AppID,+ AppSecret: value.AppSecret,+ }, "")+ if err != nil {+ return err+ }+ value.ExternalApproval.ApprovalCode = approvalCode+ b, err := json.Marshal(value)+ if err != nil {+ return err+ }+ settingPatch.Value = string(b)+ }+setting, err := s.store.PatchSetting(ctx, settingPatch)if err != nil {if common.ErrorCode(err) == common.NotFound {diff --git a/server/task_scheduler.go b/server/task_scheduler.goindex c47b9f145e..0dd8628157 100644--- a/server/task_scheduler.go+++ b/server/task_scheduler.go@@ -11,12 +11,12 @@ import ("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"-- "go.uber.org/zap")const (@@ -83,13 +83,14 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {log.Error("Failed to retrieve open pipelines", zap.Error(err))return}- for _, pipeline := range pipelineList {+ for i, pipeline := range pipelineList {if err := s.server.ScheduleActiveStage(ctx, pipeline); err != nil {log.Error("Failed to schedule tasks in the active stage",zap.Int("pipeline_id", pipeline.ID),zap.Error(err),)}+ s.server.ApplicationRunner.ScheduleApproval(s.server, pipelineList[i])}// Inspect all running tasksdiff --git a/store/external_approval.go b/store/external_approval.goindex 6fe048a2c2..50413a35be 100644--- a/store/external_approval.go+++ b/store/external_approval.go@@ -8,6 +8,7 @@ import ("github.com/pkg/errors""github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common")type externalApprovalRaw struct {@@ -76,6 +77,25 @@ func (s *Store) FindExternalApproval(ctx context.Context, find *api.ExternalApprreturn externalApprovalList, nil}+// GetExternalApprovalByIssueID gets an ExternalApproval by IssueID.+func (s *Store) GetExternalApprovalByIssueID(ctx context.Context, issueID int) (*api.ExternalApproval, error) {+ rawList, err := s.findExternalApprovalRaw(ctx, &api.ExternalApprovalFind{IssueID: &issueID})+ if err != nil {+ return nil, errors.Wrapf(err, "failed to get ApprovalInstance by issueID %v", issueID)+ }+ if len(rawList) == 0 {+ return nil, nil+ } else if len(rawList) > 1 {+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d externalApprovals with issueID %d, expect 1", len(rawList), issueID)}+ }+ externalApprovalRaw := rawList[0]+ externalApproval, err := s.composeExternalApproval(ctx, externalApprovalRaw)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to compose ExternalApproval with externalApprovalRaw[%+v]", externalApprovalRaw)+ }+ return externalApproval, nil+}+// PatchExternalApproval patches an ExternalApproval.func (s *Store) PatchExternalApproval(ctx context.Context, patch *api.ExternalApprovalPatch) (*api.ExternalApproval, error) {externalApprovalRaw, err := s.patchExternalApprovalRaw(ctx, patch)@@ -198,9 +218,12 @@ func (*Store) createExternalApprovalImpl(ctx context.Context, tx *Tx, create *apreturn &externalApprovalRaw, nil}-func (*Store) findExternalApprovalImpl(ctx context.Context, tx *Tx, _ *api.ExternalApprovalFind) ([]*externalApprovalRaw, error) {+func (*Store) findExternalApprovalImpl(ctx context.Context, tx *Tx, find *api.ExternalApprovalFind) ([]*externalApprovalRaw, error) {where, args := []string{"1 = 1"}, []interface{}{}where, args = append(where, fmt.Sprintf("row_status = $%d", len(args)+1)), append(args, api.Normal)+ if v := find.IssueID; v != nil {+ where, args = append(where, fmt.Sprintf("issue_id = $%d", len(args)+1)), append(args, *v)+ }rows, err := tx.QueryContext(ctx, `SELECTid,diff --git a/store/setting.go b/store/setting.goindex efb32d34f7..416f39e147 100644--- a/store/setting.go+++ b/store/setting.go@@ -77,6 +77,22 @@ func (s *Store) FindSetting(ctx context.Context, find *api.SettingFind) ([]*api.return settingList, nil}+// GetSetting gets an instance of Setting.+func (s *Store) GetSetting(ctx context.Context, find *api.SettingFind) (*api.Setting, error) {+ settingRaw, err := s.getSettingRaw(ctx, find)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to get Setting with SettingFind[%+v]", find)+ }+ if settingRaw == nil {+ return nil, nil+ }+ setting, err := s.composeSetting(ctx, settingRaw)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to compose Setting with settingRaw[%+v]", settingRaw)+ }+ return setting, nil+}+// PatchSetting patches an instance of Setting.func (s *Store) PatchSetting(ctx context.Context, patch *api.SettingPatch) (*api.Setting, error) {settingRaw, err := s.patchSettingRaw(ctx, patch)