Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: move GitOps webhook stuff around (#8340)
Danny Xu425ddb369a6b
diff --git a/backend/api/gitops/gitops.go b/backend/api/gitops/gitops.gonew file mode 100644index 0000000000..b1bd314919--- /dev/null+++ b/backend/api/gitops/gitops.go@@ -0,0 +1,43 @@+// Package gitops is the package for GitOps APIs.+package gitops++import (+ v1pb "github.com/bytebase/bytebase/backend/api/v1"+ "github.com/bytebase/bytebase/backend/component/activity"+ "github.com/bytebase/bytebase/backend/component/dbfactory"+ "github.com/bytebase/bytebase/backend/component/state"+ enterpriseAPI "github.com/bytebase/bytebase/backend/enterprise/api"+ "github.com/bytebase/bytebase/backend/store"+)++// Service is the API endpoint for handling GitOps requests.+type Service struct {+ store *store.Store+ dbFactory *dbfactory.DBFactory+ activityManager *activity.Manager+ stateCfg *state.State+ licenseService enterpriseAPI.LicenseService+ rolloutService *v1pb.RolloutService+ issueService *v1pb.IssueService+}++// NewService creates a GitOps service.+func NewService(+ store *store.Store,+ dbFactory *dbfactory.DBFactory,+ activityManager *activity.Manager,+ stateCfg *state.State,+ licenseService enterpriseAPI.LicenseService,+ rolloutService *v1pb.RolloutService,+ issueService *v1pb.IssueService,+) *Service {+ return &Service{+ store: store,+ dbFactory: dbFactory,+ activityManager: activityManager,+ stateCfg: stateCfg,+ licenseService: licenseService,+ rolloutService: rolloutService,+ issueService: issueService,+ }+}diff --git a/backend/server/webhook.go b/backend/api/gitops/webhook.gosimilarity index 97%rename from backend/server/webhook.gorename to backend/api/gitops/webhook.goindex 833aaebf32..ca2a913583 100644--- a/backend/server/webhook.go+++ b/backend/api/gitops/webhook.go@@ -1,4 +1,4 @@-package server+package gitopsimport ("context"@@ -60,7 +60,7 @@ const (batchIssueNameTemplate = "%s: %s")-func (s *Server) registerWebhookRoutes(g *echo.Group) {+func (s *Service) RegisterWebhookRoutes(g *echo.Group) {g.POST("/gitlab/:id", func(c echo.Context) error {ctx := c.Request().Context()@@ -715,7 +715,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {})}-func (s *Server) sqlAdviceForMybatisMapperFiles(ctx context.Context, mybatisMapperContent map[string]string, commitID string, repoInfo *repoInfo) (map[string][]advisor.Advice, error) {+func (s *Service) sqlAdviceForMybatisMapperFiles(ctx context.Context, mybatisMapperContent map[string]string, commitID string, repoInfo *repoInfo) (map[string][]advisor.Advice, error) {if len(mybatisMapperContent) == 0 {return map[string][]advisor.Advice{}, nil}@@ -767,7 +767,7 @@ func (s *Server) sqlAdviceForMybatisMapperFiles(ctx context.Context, mybatisMappreturn sqlCheckAdvices, nil}-func (s *Server) sqlAdviceForMybatisMapperFile(ctx context.Context, datum *mybatisMapperXMLFileDatum) ([]advisor.Advice, error) {+func (s *Service) sqlAdviceForMybatisMapperFile(ctx context.Context, datum *mybatisMapperXMLFileDatum) ([]advisor.Advice, error) {var result []advisor.Advicevar environmentIDs []string// If the configuration file is found, we extract the environment from the configuration file.@@ -853,7 +853,7 @@ func (s *Server) sqlAdviceForMybatisMapperFile(ctx context.Context, datum *mybatreturn result, nil}-func (s *Server) sqlAdviceForSQLFiles(+func (s *Service) sqlAdviceForSQLFiles(ctx context.Context,repoInfoList []*repoInfo,prFiles []*vcs.PullRequestFile,@@ -909,7 +909,7 @@ func (s *Server) sqlAdviceForSQLFiles(return sqlCheckAdvice}-func (s *Server) sqlAdviceForFile(+func (s *Service) sqlAdviceForFile(ctx context.Context,fileInfo fileInfo,externalURL string,@@ -1060,7 +1060,7 @@ type repoInfo struct {vcs *store.ExternalVersionControlMessage}-func (s *Server) filterRepository(ctx context.Context, webhookEndpointID string, pushEventRepositoryID string, filter repositoryFilter) ([]*repoInfo, error) {+func (s *Service) filterRepository(ctx context.Context, webhookEndpointID string, pushEventRepositoryID string, filter repositoryFilter) ([]*repoInfo, error) {repos, err := s.store.ListRepositoryV2(ctx, &store.FindRepositoryMessage{WebhookEndpointID: &webhookEndpointID})if err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to respond webhook event for endpoint: %v", webhookEndpointID)).SetInternal(err)@@ -1136,7 +1136,7 @@ func (s *Server) filterRepository(ctx context.Context, webhookEndpointID string,return filteredRepos, nil}-func (*Server) isWebhookEventBranch(pushEventRef, branchFilter string) (bool, error) {+func (*Service) isWebhookEventBranch(pushEventRef, branchFilter string) (bool, error) {branch, err := parseBranchNameFromRefs(pushEventRef)if err != nil {return false, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid ref: %s", pushEventRef)).SetInternal(err)@@ -1184,7 +1184,7 @@ func parseBranchNameFromRefs(ref string) (string, error) {return ref[len(expectedPrefix):], nil}-func (s *Server) processPushEvent(ctx context.Context, repoInfoList []*repoInfo, baseVCSPushEvent vcs.PushEvent) ([]string, error) {+func (s *Service) processPushEvent(ctx context.Context, repoInfoList []*repoInfo, baseVCSPushEvent vcs.PushEvent) ([]string, error) {if len(repoInfoList) == 0 {return nil, errors.Errorf("empty repository list")}@@ -1264,7 +1264,7 @@ func (s *Server) processPushEvent(ctx context.Context, repoInfoList []*repoInfo,// In that case, the commits in the push event contains files which are not added in this PR/MR.// We use the compare API to get the file diffs and filter files by the diffs.// TODO(dragonly): generate distinct file change list from the commits diff instead of filter.-func (s *Server) filterFilesByCommitsDiff(+func (s *Service) filterFilesByCommitsDiff(ctx context.Context,repoInfo *repoInfo,distinctFileList []vcs.DistinctFileItem,@@ -1435,7 +1435,7 @@ func getFileInfo(fileItem vcs.DistinctFileItem, repoInfoList []*repoInfo) (*db.M// It returns "created=true" when new issue(s) has been created,// along with the creation message to be presented in the UI. An *echo.HTTPError// is returned in case of the error during the process.-func (s *Server) processFilesInProject(ctx context.Context, pushEvent vcs.PushEvent, repoInfo *repoInfo, fileInfoList []fileInfo) (string, bool, []*store.ActivityMessage, *echo.HTTPError) {+func (s *Service) processFilesInProject(ctx context.Context, pushEvent vcs.PushEvent, repoInfo *repoInfo, fileInfoList []fileInfo) (string, bool, []*store.ActivityMessage, *echo.HTTPError) {if repoInfo.project.TenantMode == api.TenantModeTenant {if err := s.licenseService.IsFeatureEnabled(api.FeatureMultiTenancy); err != nil {return "", false, nil, echo.NewHTTPError(http.StatusForbidden, err.Error())@@ -1509,7 +1509,7 @@ func (s *Server) processFilesInProject(ctx context.Context, pushEvent vcs.PushEv}// processFilesInBatchProject creates issues for a batch project.-func (s *Server) processFilesInBatchProject(ctx context.Context, pushEvent vcs.PushEvent, repoInfo *repoInfo, fileInfoList []fileInfo) (string, bool, []*store.ActivityMessage, *echo.HTTPError) {+func (s *Service) processFilesInBatchProject(ctx context.Context, pushEvent vcs.PushEvent, repoInfo *repoInfo, fileInfoList []fileInfo) (string, bool, []*store.ActivityMessage, *echo.HTTPError) {var activityCreateList []*store.ActivityMessagevar createdIssueList []string@@ -1576,7 +1576,7 @@ func sortFilesBySchemaVersion(fileInfoList []fileInfo) []fileInfo {return ret}-func (s *Server) createIssueFromMigrationDetailsV2(ctx context.Context, project *store.ProjectMessage, issueName, issueDescription string, pushEvent vcs.PushEvent, creatorID int, migrationDetailList []*api.MigrationDetail) error {+func (s *Service) createIssueFromMigrationDetailsV2(ctx context.Context, project *store.ProjectMessage, issueName, issueDescription string, pushEvent vcs.PushEvent, creatorID int, migrationDetailList []*api.MigrationDetail) error {var steps []*v1pb.Plan_Stepif len(migrationDetailList) == 1 && migrationDetailList[0].DatabaseID == 0 {migrationDetail := migrationDetailList[0]@@ -1709,7 +1709,7 @@ func getChangeType(migrationType db.MigrationType) v1pb.Plan_ChangeDatabaseConfireturn v1pb.Plan_ChangeDatabaseConfig_TYPE_UNSPECIFIED}-func (s *Server) getIssueCreatorID(ctx context.Context, email string) int {+func (s *Service) getIssueCreatorID(ctx context.Context, email string) int {creatorID := api.SystemBotIDif email != "" {committerPrincipal, err := s.store.GetUser(ctx, &store.FindUserMessage{@@ -1729,7 +1729,7 @@ func (s *Server) getIssueCreatorID(ctx context.Context, email string) int {// findProjectDatabases finds the list of databases with given name in the// project. If the environmentResourceID is not empty, it will be used as a filter condition// for the result list.-func (s *Server) findProjectDatabases(ctx context.Context, projectID int, dbName, environmentResourceID string) ([]*store.DatabaseMessage, error) {+func (s *Service) findProjectDatabases(ctx context.Context, projectID int, dbName, environmentResourceID string) ([]*store.DatabaseMessage, error) {// Retrieve the current schema from the databaseproject, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{UID: &projectID})if err != nil {@@ -1829,7 +1829,7 @@ func getIgnoredFileActivityCreate(projectID int, pushEvent vcs.PushEvent, file s}// readFileContent reads the content of the given file from the given repository.-func (s *Server) readFileContent(ctx context.Context, pushEvent vcs.PushEvent, repoInfo *repoInfo, file string) (string, error) {+func (s *Service) readFileContent(ctx context.Context, pushEvent vcs.PushEvent, repoInfo *repoInfo, file string) (string, error) {// Retrieve the latest AccessToken and RefreshToken as the previous// ReadFileContent call may have updated the stored token pair. ReadFileContent// will fetch and store the new token pair if the existing token pair has@@ -1875,7 +1875,7 @@ func (s *Server) readFileContent(ctx context.Context, pushEvent vcs.PushEvent, r// prepareIssueFromSDLFile returns the migration info and a list of update// schema details derived from the given push event for SDL.-func (s *Server) prepareIssueFromSDLFile(ctx context.Context, repoInfo *repoInfo, pushEvent vcs.PushEvent, schemaInfo *db.MigrationInfo, file string) ([]*api.MigrationDetail, []*store.ActivityMessage) {+func (s *Service) prepareIssueFromSDLFile(ctx context.Context, repoInfo *repoInfo, pushEvent vcs.PushEvent, schemaInfo *db.MigrationInfo, file string) ([]*api.MigrationDetail, []*store.ActivityMessage) {dbName := schemaInfo.Databaseif dbName == "" && repoInfo.project.TenantMode == api.TenantModeDisabled {slog.Debug("Ignored schema file without a database name", slog.String("file", file))@@ -1939,7 +1939,7 @@ func (s *Server) prepareIssueFromSDLFile(ctx context.Context, repoInfo *repoInfo// prepareIssueFromFile returns a list of update schema details derived// from the given push event for DDL.-func (s *Server) prepareIssueFromFile(+func (s *Service) prepareIssueFromFile(ctx context.Context,repoInfo *repoInfo,pushEvent vcs.PushEvent,@@ -2096,7 +2096,7 @@ func (s *Server) prepareIssueFromFile(return nil, nil}-func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases []*store.DatabaseMessage, fileName, schemaVersion, statement string, pushEvent vcs.PushEvent) error {+func (s *Service) tryUpdateTasksFromModifiedFile(ctx context.Context, databases []*store.DatabaseMessage, fileName, schemaVersion, statement string, pushEvent vcs.PushEvent) error {// For modified files, we try to update the existing issue's statement.for _, database := range databases {taskList, err := s.store.ListTasks(ctx, &api.TaskFind{@@ -2496,7 +2496,7 @@ type mybatisMapperXMLFileDatum struct {// repo: the repository will be list file tree and get file content from.// commitID: the commitID is the snapshot of the file tree and file content.// mapperFiles: the map of the mybatis mapper XML file path and content.-func (s *Server) buildMybatisMapperXMLFileData(ctx context.Context, repoInfo *repoInfo, commitID string, mapperFiles map[string]string) ([]*mybatisMapperXMLFileDatum, error) {+func (s *Service) buildMybatisMapperXMLFileData(ctx context.Context, repoInfo *repoInfo, commitID string, mapperFiles map[string]string) ([]*mybatisMapperXMLFileDatum, error) {if len(mapperFiles) == 0 {return []*mybatisMapperXMLFileDatum{}, nil}diff --git a/backend/server/webhook_test.go b/backend/api/gitops/webhook_test.gosimilarity index 99%rename from backend/server/webhook_test.gorename to backend/api/gitops/webhook_test.goindex 53ee43c02b..98a81e5076 100644--- a/backend/server/webhook_test.go+++ b/backend/api/gitops/webhook_test.go@@ -1,4 +1,4 @@-package server+package gitopsimport ("testing"diff --git a/backend/server/server.go b/backend/server/server.goindex 1ce0657963..888098df32 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -21,6 +21,7 @@ import ("github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery""github.com/bytebase/bytebase/backend/api/auth"+ "github.com/bytebase/bytebase/backend/api/gitops"v1 "github.com/bytebase/bytebase/backend/api/v1""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -297,11 +298,6 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {// Configure echo server.s.e = echo.New()- webhookGroup := s.e.Group(webhookAPIPrefix)- s.registerWebhookRoutes(webhookGroup)- apiGroup := s.e.Group(internalAPIPrefix)- s.registerDatabaseRoutes(apiGroup)-// Note: the gateway response modifier takes the external url on server startup. If the external URL is changed,// the user has to restart the server to take the latest value.gatewayModifier := auth.GatewayResponseModifier{ExternalURL: externalURL, TokenDuration: tokenDuration}@@ -413,6 +409,12 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {}s.rolloutService, s.issueService = rolloutService, issueService+ webhookGroup := s.e.Group(webhookAPIPrefix)+ gitOpsService := gitops.NewService(s.store, s.dbFactory, s.activityManager, s.stateCfg, s.licenseService, rolloutService, issueService)+ gitOpsService.RegisterWebhookRoutes(webhookGroup)+ apiGroup := s.e.Group(internalAPIPrefix)+ s.registerDatabaseRoutes(apiGroup)+reflection.Register(s.grpcServer)serverStarted = true