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: migrate vcs connector proto (#11363)
Danny Xuea12e0c98c5e
diff --git a/backend/api/gitops/webhook.go b/backend/api/gitops/webhook.goindex b55535986d..6cc4f8bdb8 100644--- a/backend/api/gitops/webhook.go+++ b/backend/api/gitops/webhook.go@@ -95,7 +95,7 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {switch vcsProvider.Type {case vcs.GitHub:secretToken := c.Request().Header.Get("X-Hub-Signature-256")- ok, err := validateGitHubWebhookSignature256(secretToken, vcsConnector.WebhookSecretToken, body)+ ok, err := validateGitHubWebhookSignature256(secretToken, vcsConnector.Payload.WebhookSecretToken, body)if err != nil {return c.String(http.StatusBadRequest, fmt.Sprintf("failed to validate webhook signature %q, error %v", secretToken, err))}@@ -104,7 +104,7 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {}case vcs.GitLab:secretToken := c.Request().Header.Get("X-Gitlab-Token")- if secretToken != vcsConnector.WebhookSecretToken {+ if secretToken != vcsConnector.Payload.WebhookSecretToken {return c.String(http.StatusBadRequest, fmt.Sprintf("invalid webhook secret token %q", secretToken))}}@@ -131,12 +131,12 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {}// Check webhook branch.- ok, err := isWebhookEventBranch(pushEvent.Ref, vcsConnector.Branch)+ ok, err := isWebhookEventBranch(pushEvent.Ref, vcsConnector.Payload.Branch)if err != nil {return err}if !ok {- return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", pushEvent.Ref, vcsConnector.Branch))+ return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", pushEvent.Ref, vcsConnector.Payload.Branch))}// Squash commits.@@ -167,12 +167,12 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {}// Check webhook branch.- ok, err := isWebhookEventBranch(pushEvent.Ref, vcsConnector.Branch)+ ok, err := isWebhookEventBranch(pushEvent.Ref, vcsConnector.Payload.Branch)if err != nil {return err}if !ok {- return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", pushEvent.Ref, vcsConnector.Branch))+ return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", pushEvent.Ref, vcsConnector.Payload.Branch))}// Squash commits.@@ -228,12 +228,12 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {// Check webhook branch.ref := "refs/heads/" + change.New.Name- ok, err := isWebhookEventBranch(ref, vcsConnector.Branch)+ ok, err := isWebhookEventBranch(ref, vcsConnector.Payload.Branch)if err != nil {return err}if !ok {- return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", ref, vcsConnector.Branch))+ return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", ref, vcsConnector.Payload.Branch))}// Squash commits.@@ -250,7 +250,7 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {ctx,oauthContext,vcsProvider.InstanceURL,- vcsConnector.ExternalID,+ vcsConnector.Payload.ExternalId,before,commit.Hash,)@@ -330,12 +330,12 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {// Check webhook branch.refUpdate := pushEvent.Resource.RefUpdates[0]- ok, err := isWebhookEventBranch(refUpdate.Name, vcsConnector.Branch)+ ok, err := isWebhookEventBranch(refUpdate.Name, vcsConnector.Payload.Branch)if err != nil {return err}if !ok {- return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", refUpdate, vcsConnector.Branch))+ return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", refUpdate, vcsConnector.Payload.Branch))}// Squash commits.@@ -349,7 +349,7 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {// then we need to query the queryPullRequest API to find out if the updateRef.newObjectId// is the last commit of the Pull Request, and then we can use the PullRef.newObjectId API// to find out if it is the last commit of the Pull Request. Request ID to list the corresponding commits.- probablePullRequests, err := azure.QueryPullRequest(ctx, oauthContext, vcsConnector.ExternalID, pushEvent.Resource.RefUpdates[0].NewObjectID)+ probablePullRequests, err := azure.QueryPullRequest(ctx, oauthContext, vcsConnector.Payload.ExternalId, pushEvent.Resource.RefUpdates[0].NewObjectID)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to query pull request").SetInternal(err)}@@ -374,7 +374,7 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {}// We should backfill the commit list by the commits in the pull request.pullRequest := filterOutPullRequestList[0]- commitsInPullRequest, err := azure.GetPullRequestCommits(ctx, oauthContext, vcsConnector.ExternalID, pullRequest.ID)+ commitsInPullRequest, err := azure.GetPullRequestCommits(ctx, oauthContext, vcsConnector.Payload.ExternalId, pullRequest.ID)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get pull request commits").SetInternal(err)}@@ -397,7 +397,7 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {}slog.Debug("all commits are created by Bytebase",slog.String("repoURL", pushEvent.Resource.Repository.URL),- slog.String("repoID", vcsConnector.ExternalID),+ slog.String("repoID", vcsConnector.Payload.ExternalId),slog.String("repoName", pushEvent.Resource.Repository.Name),slog.String("commits", strings.Join(commitIDs, ", ")),)@@ -412,7 +412,7 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {// NOTE: We presume that the sequence of the commits in the code push event is the reverse order of the commit sequence(aka. stack sequence, commit first, appear last) in the repository.backfillCommits := make([]vcs.Commit, 0, len(nonBytebaseCommitList))for _, commit := range nonBytebaseCommitList {- changes, err := azure.GetChangesByCommit(ctx, oauthContext, vcsConnector.ExternalID, commit.CommitID)+ changes, err := azure.GetChangesByCommit(ctx, oauthContext, vcsConnector.Payload.ExternalId, commit.CommitID)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get changes by commit %q", commit.CommitID)).SetInternal(err)}@@ -443,15 +443,15 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {})}if len(backfillCommits) == 1 && len(backfillCommits[0].AddedList) == 1 && strings.HasSuffix(backfillCommits[0].AddedList[0], azure.SQLReviewPipelineFilePath) {- slog.Debug("start to setup pipeline", slog.String("repository", vcsConnector.ExternalID))+ slog.Debug("start to setup pipeline", slog.String("repository", vcsConnector.Payload.ExternalId))// Use workspaceID instead of repo secret as SQL review pipeline token, so that we don't need to re-create the pipeline if users disable then enable the CI.workspaceID, err := s.store.GetWorkspaceID(ctx)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get workspace id with error").SetInternal(err)}// Setup SQL review pipeline and policy.- if err := azure.EnableSQLReviewCI(ctx, oauthContext, vcsConnector.Title, vcsConnector.ExternalID, vcsConnector.Branch, workspaceID); err != nil {- slog.Error("failed to setup pipeline", log.BBError(err), slog.String("repository", vcsConnector.ExternalID))+ if err := azure.EnableSQLReviewCI(ctx, oauthContext, vcsConnector.Payload.Title, vcsConnector.Payload.ExternalId, vcsConnector.Payload.Branch, workspaceID); err != nil {+ slog.Error("failed to setup pipeline", log.BBError(err), slog.String("repository", vcsConnector.Payload.ExternalId))return echo.NewHTTPError(http.StatusInternalServerError, "Failed to setup SQL review pipeline").SetInternal(err)}return c.String(http.StatusOK, "OK")@@ -459,7 +459,7 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {// Backfill web url for commits.if pushEvent.Resource.PushID != 0 {- commitsInPush, err := azure.GetPushCommitsByPushID(ctx, oauthContext, vcsConnector.ExternalID, pushEvent.Resource.PushID)+ commitsInPush, err := azure.GetPushCommitsByPushID(ctx, oauthContext, vcsConnector.Payload.ExternalId, pushEvent.Resource.PushID)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get push commits by push id %d", pushEvent.Resource.PushID)).SetInternal(err)}@@ -480,9 +480,9 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {Ref: pushEvent.Resource.RefUpdates[0].Name,Before: pushEvent.Resource.RefUpdates[0].OldObjectID,After: pushEvent.Resource.RefUpdates[0].NewObjectID,- RepositoryID: vcsConnector.ExternalID,- RepositoryURL: vcsConnector.WebURL,- RepositoryFullPath: vcsConnector.ExternalID,+ RepositoryID: vcsConnector.Payload.ExternalId,+ RepositoryURL: vcsConnector.Payload.WebUrl,+ RepositoryFullPath: vcsConnector.Payload.ExternalId,AuthorName: pushEvent.Resource.PushedBy.DisplayName,CommitList: backfillCommits,})@@ -598,7 +598,7 @@ func (s *Service) processPushEvent(ctx context.Context, oauthContext *common.OauactivityCreateList = append(activityCreateList, activityCreateListForFile...)migrationDetailList = append(migrationDetailList, migrationDetailListForFile...)if len(migrationDetailListForFile) != 0 {- fileNameList = append(fileNameList, strings.TrimPrefix(fileInfo.item.FileName, repo.repository.BaseDirectory+"/"))+ fileNameList = append(fileNameList, strings.TrimPrefix(fileInfo.item.FileName, repo.repository.Payload.BaseDirectory+"/"))}}if len(migrationDetailList) == 0 {@@ -644,12 +644,12 @@ func filterFilesByCommitsDiff(ctx,oauthContext,repoInfo.vcs.InstanceURL,- repoInfo.repository.ExternalID,+ repoInfo.repository.Payload.ExternalId,beforeCommit,afterCommit,)if err != nil {- return nil, errors.WithMessagef(err, "failed to get file diff list for repository %s", repoInfo.repository.ExternalID)+ return nil, errors.WithMessagef(err, "failed to get file diff list for repository %s", repoInfo.repository.Payload.ExternalId)}var filteredDistinctFileList []vcs.DistinctFileItemfor _, file := range distinctFileList {@@ -673,7 +673,7 @@ func getFileInfoList(distinctFileList []vcs.DistinctFileItem, repo *repoInfo) []for _, item := range distinctFileList {slog.Debug("Processing file", slog.String("file", item.FileName), slog.String("commit", item.Commit.ID))var migrationInfo *db.MigrationInfo- if filepath.Dir(item.FileName) != repo.repository.BaseDirectory {+ if filepath.Dir(item.FileName) != repo.repository.Payload.BaseDirectory {continue}filename := filepath.Base(item.FileName)@@ -923,7 +923,7 @@ func readFileContent(ctx context.Context, oauthContext *common.OauthContext, pusctx,oauthContext,repo.vcs.InstanceURL,- repo.repository.ExternalID,+ repo.repository.Payload.ExternalId,file,vcs.RefInfo{RefType: vcs.RefTypeCommit,diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.goindex 37259847bb..466fca93b7 100644--- a/backend/api/v1/project_service.go+++ b/backend/api/v1/project_service.go@@ -488,7 +488,7 @@ func (s *ProjectService) UpdateProjectGitOpsInfo(ctx context.Context, request *v}}- if v := patch.Branch; v != nil && vcsConnector.Branch != *v {+ if v := patch.Branch; v != nil && vcsConnector.Payload.Branch != *v {if *v == "" {return nil, status.Errorf(codes.InvalidArgument, "branch must be specified")}@@ -496,14 +496,14 @@ func (s *ProjectService) UpdateProjectGitOpsInfo(ctx context.Context, request *vctx,vcs,vcs.AccessToken,- vcsConnector.ExternalID,+ vcsConnector.Payload.ExternalId,*v,)if err != nil {return nil, status.Errorf(codes.Internal, "failed to check branch: %v", err.Error())}if notFound {- return nil, status.Errorf(codes.NotFound, "branch %s not found in repository %s", *v, vcsConnector.FullPath)+ return nil, status.Errorf(codes.NotFound, "branch %s not found in repository %s", *v, vcsConnector.Payload.FullPath)}}@@ -555,8 +555,8 @@ func (s *ProjectService) UnsetProjectGitOpsInfo(ctx context.Context, request *v1AccessToken: vcs.AccessToken,},vcs.InstanceURL,- vcsConnector.ExternalID,- vcsConnector.ExternalWebhookID,+ vcsConnector.Payload.ExternalId,+ vcsConnector.Payload.ExternalWebhookId,); err != nil {// Despite the error here, we have deleted the repository in the database, we still return success.slog.Error("failed to delete webhook for project", slog.String("project", projectID), slog.Int("repo", vcsConnector.UID), log.BBError(err))@@ -952,18 +952,19 @@ func (s *ProjectService) createProjectGitOpsInfo(ctx context.Context, request *v// TODO(d): pass in the resource ID from API.vcsConnectorID := "default"vcsConnectorCreate := &store.VCSConnectorMessage{- CreatorID: principalID,- VCSUID: vcs.ID,- VCSResourceID: vcs.ResourceID,- ProjectID: project.ResourceID,- ResourceID: vcsConnectorID,- WebhookURLHost: setting.ExternalUrl,- Title: request.ProjectGitopsInfo.Title,- FullPath: request.ProjectGitopsInfo.FullPath,- WebURL: request.ProjectGitopsInfo.WebUrl,- Branch: request.ProjectGitopsInfo.Branch,- BaseDirectory: baseDir,- ExternalID: request.ProjectGitopsInfo.ExternalId,+ CreatorID: principalID,+ VCSUID: vcs.ID,+ VCSResourceID: vcs.ResourceID,+ ProjectID: project.ResourceID,+ ResourceID: vcsConnectorID,+ Payload: &storepb.VCSConnector{+ Title: request.ProjectGitopsInfo.Title,+ FullPath: request.ProjectGitopsInfo.FullPath,+ WebUrl: request.ProjectGitopsInfo.WebUrl,+ Branch: request.ProjectGitopsInfo.Branch,+ BaseDirectory: baseDir,+ ExternalId: request.ProjectGitopsInfo.ExternalId,+ },}// When the branch names doesn't contain wildcards, we should make sure the branch exists in the repo.@@ -971,14 +972,14 @@ func (s *ProjectService) createProjectGitOpsInfo(ctx context.Context, request *vctx,vcs,vcs.AccessToken,- vcsConnectorCreate.ExternalID,- vcsConnectorCreate.Branch,+ vcsConnectorCreate.Payload.ExternalId,+ vcsConnectorCreate.Payload.Branch,)if err != nil {- return nil, status.Errorf(codes.Internal, "failed to check branch %s with error: %v", vcsConnectorCreate.Branch, err.Error())+ return nil, status.Errorf(codes.Internal, "failed to check branch %s with error: %v", vcsConnectorCreate.Payload.Branch, err.Error())}if notFound {- return nil, status.Errorf(codes.NotFound, "branch %s not found in repository %s", vcsConnectorCreate.Branch, vcsConnectorCreate.FullPath)+ return nil, status.Errorf(codes.NotFound, "branch %s not found in repository %s", vcsConnectorCreate.Payload.Branch, vcsConnectorCreate.Payload.FullPath)}// Create the webhook.@@ -986,21 +987,21 @@ func (s *ProjectService) createProjectGitOpsInfo(ctx context.Context, request *vif err != nil {return nil, status.Errorf(codes.Internal, "failed to find workspace id with error: %v", err.Error())}- vcsConnectorCreate.WebhookEndpointID = fmt.Sprintf("workspaces/%s/projects/%s/vcsConnectors/%s", workspaceID, project.ResourceID, vcsConnectorID)+ webhookEndpointID := fmt.Sprintf("workspaces/%s/projects/%s/vcsConnectors/%s", workspaceID, project.ResourceID, vcsConnectorID)secretToken, err := common.RandomString(gitlab.SecretTokenLength)if err != nil {return nil, status.Errorf(codes.Internal, "failed to generate random secret token for vcs with error: %v", err.Error())}- vcsConnectorCreate.WebhookSecretToken = secretToken+ vcsConnectorCreate.Payload.WebhookSecretToken = secretTokenbytebaseEndpointURL := setting.GitopsWebhookUrlif bytebaseEndpointURL == "" {bytebaseEndpointURL = setting.ExternalUrl}- webhookID, err := createVCSWebhook(ctx, vcs.Type, vcsConnectorCreate.WebhookEndpointID, secretToken, vcs.AccessToken, vcs.InstanceURL, vcsConnectorCreate.ExternalID, bytebaseEndpointURL)+ webhookID, err := createVCSWebhook(ctx, vcs.Type, webhookEndpointID, secretToken, vcs.AccessToken, vcs.InstanceURL, vcsConnectorCreate.Payload.ExternalId, bytebaseEndpointURL)if err != nil {return nil, status.Errorf(codes.Internal, "failed to create webhook for project %s with error: %v", vcsConnectorCreate.ProjectID, err.Error())}- vcsConnectorCreate.ExternalWebhookID = webhookID+ vcsConnectorCreate.Payload.ExternalWebhookId = webhookIDvcsConnector, err := s.store.CreateVCSConnector(ctx, vcsConnectorCreate)if err != nil {return nil, status.Errorf(codes.Internal, "failed to link project repository with error: %v", err.Error())@@ -2381,15 +2382,13 @@ func validateMember(member string) error {func convertToProjectGitOpsInfo(vcsConnector *store.VCSConnectorMessage) *v1pb.ProjectGitOpsInfo {return &v1pb.ProjectGitOpsInfo{- Name: fmt.Sprintf("%s%s/gitOpsInfo", common.ProjectNamePrefix, vcsConnector.ProjectID),- Vcs: fmt.Sprintf("%s%s", common.VCSProviderPrefix, vcsConnector.VCSResourceID),- Title: vcsConnector.Title,- FullPath: vcsConnector.FullPath,- WebUrl: vcsConnector.WebURL,- Branch: vcsConnector.Branch,- BaseDirectory: vcsConnector.BaseDirectory,- WebhookEndpointId: vcsConnector.WebhookEndpointID,- ExternalId: vcsConnector.ExternalID,+ Name: fmt.Sprintf("%s%s/gitOpsInfo", common.ProjectNamePrefix, vcsConnector.ProjectID),+ Vcs: fmt.Sprintf("%s%s", common.VCSProviderPrefix, vcsConnector.VCSResourceID),+ Title: vcsConnector.Payload.Title,+ FullPath: vcsConnector.Payload.FullPath,+ Branch: vcsConnector.Payload.Branch,+ BaseDirectory: vcsConnector.Payload.BaseDirectory,+ ExternalId: vcsConnector.Payload.ExternalId,}}diff --git a/backend/api/v1/vcs_connector_service.go b/backend/api/v1/vcs_connector_service.goindex 575d7e0530..f42c6d8080 100644--- a/backend/api/v1/vcs_connector_service.go+++ b/backend/api/v1/vcs_connector_service.go@@ -16,6 +16,7 @@ import (vcsplugin "github.com/bytebase/bytebase/backend/plugin/vcs""github.com/bytebase/bytebase/backend/plugin/vcs/gitlab""github.com/bytebase/bytebase/backend/store"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")@@ -110,17 +111,17 @@ func (s *VCSConnectorService) CreateVCSConnector(ctx context.Context, request *vResourceID: request.VcsConnectorId,CreatorID: principalID,- VCSUID: vcs.ID,- VCSResourceID: vcs.ResourceID,- WebhookURLHost: "setting.ExternalUrl",- Title: request.GetVcsConnector().Title,- FullPath: request.GetVcsConnector().FullPath,- WebURL: request.GetVcsConnector().WebUrl,- Branch: request.GetVcsConnector().Branch,- BaseDirectory: baseDir,- ExternalID: request.GetVcsConnector().ExternalId,- WebhookEndpointID: fmt.Sprintf("workspaces/%s/projects/%s/vcsConnectors/%s", workspaceID, project.ResourceID, request.VcsConnectorId),- WebhookSecretToken: secretToken,+ VCSUID: vcs.ID,+ VCSResourceID: vcs.ResourceID,+ Payload: &storepb.VCSConnector{+ Title: request.GetVcsConnector().Title,+ FullPath: request.GetVcsConnector().FullPath,+ WebUrl: request.GetVcsConnector().WebUrl,+ Branch: request.GetVcsConnector().Branch,+ BaseDirectory: baseDir,+ ExternalId: request.GetVcsConnector().ExternalId,+ WebhookSecretToken: secretToken,+ },}// Create the webhook.@@ -128,11 +129,12 @@ func (s *VCSConnectorService) CreateVCSConnector(ctx context.Context, request *vif bytebaseEndpointURL == "" {bytebaseEndpointURL = setting.ExternalUrl}- webhookID, err := createVCSWebhook(ctx, vcs.Type, vcsConnectorCreate.WebhookEndpointID, secretToken, vcs.AccessToken, vcs.InstanceURL, vcsConnectorCreate.ExternalID, bytebaseEndpointURL)+ webhookEndpointID := fmt.Sprintf("workspaces/%s/projects/%s/vcsConnectors/%s", workspaceID, project.ResourceID, request.VcsConnectorId)+ webhookID, err := createVCSWebhook(ctx, vcs.Type, webhookEndpointID, secretToken, vcs.AccessToken, vcs.InstanceURL, vcsConnectorCreate.Payload.ExternalId, bytebaseEndpointURL)if err != nil {return nil, status.Errorf(codes.Internal, "failed to create webhook for project %s with error: %v", vcsConnectorCreate.ProjectID, err.Error())}- vcsConnectorCreate.ExternalWebhookID = webhookID+ vcsConnectorCreate.Payload.ExternalWebhookId = webhookIDvcsConnector, err = s.store.CreateVCSConnector(ctx, vcsConnectorCreate)if err != nil {@@ -331,8 +333,8 @@ func (s *VCSConnectorService) DeleteVCSConnector(ctx context.Context, request *vAccessToken: vcs.AccessToken,},vcs.InstanceURL,- vcsConnector.ExternalID,- vcsConnector.ExternalWebhookID,+ vcsConnector.Payload.ExternalId,+ vcsConnector.Payload.ExternalWebhookId,); err != nil {slog.Error("failed to delete webhook for VCS connector", slog.String("project", projectID), slog.String("VCS connector", vcsConnector.ResourceID), log.BBError(err))}@@ -357,19 +359,17 @@ func (s *VCSConnectorService) convertStoreVCSConnector(ctx context.Context, vcsC}v1VCSConnector := &v1pb.VCSConnector{- Name: fmt.Sprintf("%s%s/%s%s", common.ProjectNamePrefix, vcsConnector.ProjectID, common.VCSConnectorPrefix, vcsConnector.ResourceID),- CreateTime: timestamppb.New(vcsConnector.CreatedTime),- UpdateTime: timestamppb.New(vcsConnector.UpdatedTime),- Creator: fmt.Sprintf("users/%s", creator.Email),- Updater: fmt.Sprintf("users/%s", updater.Email),- Title: vcsConnector.Title,- VcsProvider: fmt.Sprintf("%s%s", common.VCSProviderPrefix, vcsConnector.VCSResourceID),- ExternalId: vcsConnector.ExternalID,- BaseDirectory: vcsConnector.BaseDirectory,- Branch: vcsConnector.Branch,- WebhookEndpointId: vcsConnector.WebhookEndpointID,- FullPath: vcsConnector.FullPath,- WebUrl: vcsConnector.WebURL,+ Name: fmt.Sprintf("%s%s/%s%s", common.ProjectNamePrefix, vcsConnector.ProjectID, common.VCSConnectorPrefix, vcsConnector.ResourceID),+ CreateTime: timestamppb.New(vcsConnector.CreatedTime),+ UpdateTime: timestamppb.New(vcsConnector.UpdatedTime),+ Creator: fmt.Sprintf("users/%s", creator.Email),+ Updater: fmt.Sprintf("users/%s", updater.Email),+ Title: vcsConnector.Payload.Title,+ VcsProvider: fmt.Sprintf("%s%s", common.VCSProviderPrefix, vcsConnector.VCSResourceID),+ ExternalId: vcsConnector.Payload.ExternalId,+ BaseDirectory: vcsConnector.Payload.BaseDirectory,+ Branch: vcsConnector.Payload.Branch,+ FullPath: vcsConnector.Payload.FullPath,}return v1VCSConnector, nil}diff --git a/backend/migrator/migration/prod/2.15/0013##vcs_connector.sql b/backend/migrator/migration/prod/2.15/0013##vcs_connector.sqlnew file mode 100644index 0000000000..05a5e8b828--- /dev/null+++ b/backend/migrator/migration/prod/2.15/0013##vcs_connector.sql@@ -0,0 +1,15 @@+ALTER TABLE repository ADD COLUMN payload JSONB NOT NULL DEFAULT '{}';+UPDATE repository SET payload = json_build_object('title', name, 'fullPath', full_path, 'webUrl', web_url, 'branch', branch, 'baseDirectory', base_directory, 'externalId', external_id, 'externalWebhookId', external_webhook_id, 'webhookSecretToken', webhook_secret_token);+ALTER TABLE repository DROP COLUMN name, DROP COLUMN full_path, DROP COLUMN web_url, DROP COLUMN branch, DROP COLUMN base_directory, DROP COLUMN external_id, DROP COLUMN external_webhook_id, DROP COLUMN webhook_url_host, DROP COLUMN webhook_endpoint_id, DROP COLUMN webhook_secret_token;++ALTER TABLE repository RENAME TO vcs_connector;++ALTER INDEX idx_repository_unique_project_id_resource_id RENAME TO idx_vcs_connector_unique_project_id_resource_id;+ALTER INDEX repository_pkey RENAME TO vcs_connector_pkey;++ALTER TABLE vcs_connector RENAME CONSTRAINT repository_creator_id_fkey TO vcs_connector_creator_id_fkey;+ALTER TABLE vcs_connector RENAME CONSTRAINT repository_project_id_fkey TO vcs_connector_project_id_fkey;+ALTER TABLE vcs_connector RENAME CONSTRAINT repository_updater_id_fkey TO vcs_connector_updater_id_fkey;+ALTER TABLE vcs_connector RENAME CONSTRAINT repository_vcs_id_fkey TO vcs_connector_vcs_id_fkey;++ALTER TRIGGER update_repository_updated_ts ON vcs_connector RENAME TO update_vcs_connector_updated_ts;diff --git a/backend/migrator/migration/prod/LATEST.sql b/backend/migrator/migration/prod/LATEST.sqlindex a1ad840b40..aa5e5aa84a 100644--- a/backend/migrator/migration/prod/LATEST.sql+++ b/backend/migrator/migration/prod/LATEST.sql@@ -880,10 +880,8 @@ UPDATEON vcs FOR EACH ROWEXECUTE FUNCTION trigger_update_updated_ts();--- repository table stores the repository setting for a project--- A vcs is associated with many repositories.--- A project can only link one repository (at least for now).-CREATE TABLE repository (+-- vcs_connector table stores vcs connectors for a project+CREATE TABLE vcs_connector (id SERIAL PRIMARY KEY,row_status row_status NOT NULL DEFAULT 'NORMAL',creator_id INTEGER NOT NULL REFERENCES principal (id),@@ -893,41 +891,17 @@ CREATE TABLE repository (vcs_id INTEGER NOT NULL REFERENCES vcs (id),project_id INTEGER NOT NULL REFERENCES project (id),resource_id TEXT NOT NULL,- -- Name from the corresponding VCS provider.- -- For GitLab, this is the project name. e.g. project 1- name TEXT NOT NULL,- -- Full path from the corresponding VCS provider.- -- For GitLab, this is the project full path. e.g. group1/project-1- full_path TEXT NOT NULL,- -- Web url from the corresponding VCS provider.- -- For GitLab, this is the project web url. e.g. https://gitlab.example.com/group1/project-1- web_url TEXT NOT NULL,- -- Branch to listen to.- branch TEXT NOT NULL DEFAULT '',- -- Base working directory we are interested.- base_directory TEXT NOT NULL DEFAULT '',- -- Repository id from the corresponding VCS provider.- -- For GitLab, this is the project id. e.g. 123- external_id TEXT NOT NULL,- -- Push webhook id from the corresponding VCS provider.- -- For GitLab, this is the project webhook id. e.g. 123- external_webhook_id TEXT NOT NULL,- -- Identify the host of the webhook url where the webhook event sends. We store this to identify stale webhook url whose url doesn't match the current bytebase --external-url.- webhook_url_host TEXT NOT NULL,- -- Identify the target repository receiving the webhook event. This is a random string.- webhook_endpoint_id TEXT NOT NULL,- -- For GitLab, webhook request contains this in the 'X-Gitlab-Token" header and we compare it with the one stored in db to validate it sends to the expected endpoint.- webhook_secret_token TEXT NOT NULL+ payload JSONB NOT NULL DEFAULT '{}');-CREATE UNIQUE INDEX idx_repository_unique_project_id_resource_id ON repository(project_id, resource_id);+CREATE UNIQUE INDEX idx_vcs_connector_unique_project_id_resource_id ON vcs_connector(project_id, resource_id);-ALTER SEQUENCE repository_id_seq RESTART WITH 101;+ALTER SEQUENCE vcs_connector_id_seq RESTART WITH 101;-CREATE TRIGGER update_repository_updated_ts+CREATE TRIGGER update_vcs_connector_updated_tsBEFOREUPDATE- ON repository FOR EACH ROW+ ON vcs_connector FOR EACH ROWEXECUTE FUNCTION trigger_update_updated_ts();-- Anomalydiff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.goindex 8e05dca95e..9fe28326db 100644--- a/backend/migrator/migrator_test.go+++ b/backend/migrator/migrator_test.go@@ -230,5 +230,5 @@ func TestMigrationCompatibility(t *testing.T) {func TestGetCutoffVersion(t *testing.T) {releaseVersion, err := getProdCutoffVersion()require.NoError(t, err)- require.Equal(t, semver.MustParse("2.15.12"), releaseVersion)+ require.Equal(t, semver.MustParse("2.15.13"), releaseVersion)}diff --git a/backend/store/project.go b/backend/store/project.goindex ab88b526d1..024d0a1f9c 100644--- a/backend/store/project.go+++ b/backend/store/project.go@@ -284,7 +284,7 @@ func (s *Store) listProjectImplV2(ctx context.Context, tx *Tx, find *FindProjectkey,tenant_mode,data_classification_config_id,- (SELECT COUNT(1) FROM repository WHERE project.id = repository.project_id) AS connectors,+ (SELECT COUNT(1) FROM vcs_connector WHERE project.id = vcs_connector.project_id) AS connectors,setting,row_statusFROM projectdiff --git a/backend/store/vcs_connector.go b/backend/store/vcs_connector.goindex ee54607035..f50fb4acbf 100644--- a/backend/store/vcs_connector.go+++ b/backend/store/vcs_connector.go@@ -8,6 +8,9 @@ import ("time""github.com/pkg/errors"+ "google.golang.org/protobuf/encoding/protojson"++ storepb "github.com/bytebase/bytebase/proto/generated-go/store")// VCSConnectorMessage is the message for a VCS connector.@@ -18,17 +21,7 @@ type VCSConnectorMessage struct {ProjectID stringResourceID string- // Domain specific fields- Title string- FullPath string- WebURL string- Branch string- BaseDirectory string- ExternalID string- ExternalWebhookID string- WebhookURLHost string- WebhookEndpointID string- WebhookSecretToken string+ Payload *storepb.VCSConnector// Output only fieldsUID int@@ -76,10 +69,10 @@ func (s *Store) ListVCSConnectors(ctx context.Context, find *FindVCSConnectorMeswhere, args := []string{"TRUE"}, []any{}if v := find.VCSUID; v != nil {- where, args = append(where, fmt.Sprintf("repository.vcs_id = $%d", len(args)+1)), append(args, *v)+ where, args = append(where, fmt.Sprintf("vcs_connector.vcs_id = $%d", len(args)+1)), append(args, *v)}if v := find.ResourceID; v != nil {- where, args = append(where, fmt.Sprintf("repository.resource_id = $%d", len(args)+1)), append(args, *v)+ where, args = append(where, fmt.Sprintf("vcs_connector.resource_id = $%d", len(args)+1)), append(args, *v)}if v := find.ProjectID; v != nil {where, args = append(where, fmt.Sprintf("project.resource_id = $%d", len(args)+1)), append(args, *v)@@ -93,26 +86,17 @@ func (s *Store) ListVCSConnectors(ctx context.Context, find *FindVCSConnectorMesrows, err := tx.QueryContext(ctx, `SELECT- repository.id AS id,+ vcs_connector.id AS id,vcs_id,vcs.resource_id,project.resource_id AS project_resource_id,- repository.resource_id,- repository.name AS name,- repository.creator_id,- repository.updater_id,- full_path,- web_url,- branch,- base_directory,- external_id,- external_webhook_id,- webhook_url_host,- webhook_endpoint_id,- webhook_secret_token- FROM repository- LEFT JOIN project ON project.id = repository.project_id- LEFT JOIN vcs ON vcs.id = repository.vcs_id+ vcs_connector.resource_id,+ vcs_connector.creator_id,+ vcs_connector.updater_id,+ vcs_connector.payload+ FROM vcs_connector+ LEFT JOIN project ON project.id = vcs_connector.project_id+ LEFT JOIN vcs ON vcs.id = vcs_connector.vcs_idWHERE `+strings.Join(where, " AND "),args...,)@@ -124,27 +108,24 @@ func (s *Store) ListVCSConnectors(ctx context.Context, find *FindVCSConnectorMesvar vcsConnectors []*VCSConnectorMessagefor rows.Next() {var vcsConnector VCSConnectorMessage+ var payloadStr stringif err := rows.Scan(&vcsConnector.UID,&vcsConnector.VCSUID,&vcsConnector.VCSResourceID,&vcsConnector.ProjectID,&vcsConnector.ResourceID,- &vcsConnector.Title,&vcsConnector.CreatorID,&vcsConnector.UpdaterID,- &vcsConnector.FullPath,- &vcsConnector.WebURL,- &vcsConnector.Branch,- &vcsConnector.BaseDirectory,- &vcsConnector.ExternalID,- &vcsConnector.ExternalWebhookID,- &vcsConnector.WebhookURLHost,- &vcsConnector.WebhookEndpointID,- &vcsConnector.WebhookSecretToken,+ &payloadStr,); err != nil {return nil, err}+ var payload storepb.VCSConnector+ if err := protojson.Unmarshal([]byte(payloadStr), &payload); err != nil {+ return nil, err+ }+ vcsConnector.Payload = &payloadvcsConnectors = append(vcsConnectors, &vcsConnector)}if err := rows.Err(); err != nil {@@ -165,6 +146,11 @@ func (s *Store) CreateVCSConnector(ctx context.Context, create *VCSConnectorMess}create.UpdaterID = create.CreatorID+ payload, err := protojson.Marshal(create.Payload)+ if err != nil {+ return nil, err+ }+tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, err@@ -172,24 +158,15 @@ func (s *Store) CreateVCSConnector(ctx context.Context, create *VCSConnectorMessdefer tx.Rollback()query := `- INSERT INTO repository (+ INSERT INTO vcs_connector (creator_id,updater_id,vcs_id,project_id,resource_id,- name,- full_path,- web_url,- branch,- base_directory,- external_id,- external_webhook_id,- webhook_url_host,- webhook_endpoint_id,- webhook_secret_token+ payload)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)+ VALUES ($1, $2, $3, $4, $5, $6)RETURNING id`if err := tx.QueryRowContext(ctx, query,@@ -198,16 +175,7 @@ func (s *Store) CreateVCSConnector(ctx context.Context, create *VCSConnectorMesscreate.VCSUID,project.UID,create.ResourceID,- create.Title,- create.FullPath,- create.WebURL,- create.Branch,- create.BaseDirectory,- create.ExternalID,- create.ExternalWebhookID,- create.WebhookURLHost,- create.WebhookEndpointID,- create.WebhookSecretToken,+ payload,).Scan(&create.UID,); err != nil {@@ -225,14 +193,20 @@ func (s *Store) CreateVCSConnector(ctx context.Context, create *VCSConnectorMess// UpdateVCSConnector updates a VCS connector.func (s *Store) UpdateVCSConnector(ctx context.Context, update *UpdateVCSConnectorMessage) error {set, args := []string{"updater_id = $1"}, []any{update.UpdaterID}++ var payloadSet []stringif v := update.Branch; v != nil {- set, args = append(set, fmt.Sprintf("branch = $%d", len(args)+1)), append(args, *v)+ payloadSet, args = append(payloadSet, fmt.Sprintf("jsonb_build_object('branch', to_jsonb($%d::TEXT))", len(args)+1)), append(args, *v)}if v := update.BaseDirectory; v != nil {- set, args = append(set, fmt.Sprintf("base_directory = $%d", len(args)+1)), append(args, *v)+ payloadSet, args = append(payloadSet, fmt.Sprintf("jsonb_build_object('baseDirectory', to_jsonb($%d::TEXT))", len(args)+1)), append(args, *v)}+ if len(payloadSet) != 0 {+ set = append(set, fmt.Sprintf(`payload = payload || %s`, strings.Join(payloadSet, "||")))+ }+where := []string{}- where, args = append(where, fmt.Sprintf("repository.id = $%d", len(args)+1)), append(args, update.UID)+ where, args = append(where, fmt.Sprintf("vcs_connector.id = $%d", len(args)+1)), append(args, update.UID)tx, err := s.db.BeginTx(ctx, nil)if err != nil {@@ -240,10 +214,10 @@ func (s *Store) UpdateVCSConnector(ctx context.Context, update *UpdateVCSConnect}query := `- UPDATE repository+ UPDATE vcs_connectorSET ` + strings.Join(set, ", ") + `FROM project, vcs- WHERE project.id = repository.project_id AND vcs.id = repository.vcs_id AND ` + strings.Join(where, " AND ")+ WHERE project.id = vcs_connector.project_id AND vcs.id = vcs_connector.vcs_id AND ` + strings.Join(where, " AND ")if _, err := tx.ExecContext(ctx, query, args...); err != nil {return err@@ -261,9 +235,9 @@ func (s *Store) DeleteVCSConnector(ctx context.Context, projectID, resourceID stdefer tx.Rollback()if _, err := tx.ExecContext(ctx, `- DELETE FROM repository+ DELETE FROM vcs_connectorUSING project- WHERE repository.project_id = project.id AND project.resource_id = $1 AND repository.resource_id = $2;`,+ WHERE vcs_connector.project_id = project.id AND project.resource_id = $1 AND vcs_connector.resource_id = $2;`,projectID, resourceID); err != nil {return err}diff --git a/frontend/src/store/modules/v1/repository.ts b/frontend/src/store/modules/v1/repository.tsindex 6b705a6340..9f0c981862 100644--- a/frontend/src/store/modules/v1/repository.ts+++ b/frontend/src/store/modules/v1/repository.ts@@ -128,7 +128,7 @@ const getUpdateMaskForRepository = (updateMask.push("title");}if (!isUndefined(update.branch) && !isEqual(origin.branch, update.branch)) {- updateMask.push("branch_filter");+ updateMask.push("branch");}if (!isUndefined(update.baseDirectory) &&