Skip to content

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

Create update schema issue on observing new sql file from the connected repository

天舟a51565b5ba4c
diff --git a/backend/api/repository.go b/backend/api/repository.go
index c4b64f9c0f..cdd7a830cd 100644
--- a/backend/api/repository.go
+++ b/backend/api/repository.go
@@ -61,6 +61,9 @@ type RepositoryFind struct {
// Related fields
VCSId *int
ProjectId *int
+
+ // Domain specific fields
+ WebhookEndpointId *string
}
func (find *RepositoryFind) String() string {
diff --git a/backend/external/gitlab/gitlab.go b/backend/external/gitlab/gitlab.go
index 73bd2bb60e..a99c44e519 100644
--- a/backend/external/gitlab/gitlab.go
+++ b/backend/external/gitlab/gitlab.go
@@ -10,13 +10,72 @@ const (
ApiPath = "api/v4"
)
+type GitLabWebhookType string
+
+const (
+ WebhookPush GitLabWebhookType = "push"
+)
+
+func (e GitLabWebhookType) String() string {
+ switch e {
+ case WebhookPush:
+ return "push"
+ }
+ return "UNKNOWN"
+}
+
type WebhookPut struct {
URL string `json:"url"`
PushEventsBranchFilter string `json:"push_events_branch_filter"`
}
+type WebhookProject struct {
+ ID int `json:"id"`
+ WebURL string `json:"web_url"`
+ FullPath string `json:"path_with_namespace"`
+}
+
+type WebhookCommitAuthor struct {
+ Name string `json:"name"`
+}
+
+type WebhookCommit struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Message string `json:"message"`
+ Timestamp string `json:"timestamp"`
+ URL string `json:"url"`
+ Author WebhookCommitAuthor `json:"author"`
+ AddedList []string `json:"added"`
+ ModifiedList []string `json:"modified"`
+ RemovedList []string `json:"removed"`
+}
+
type WebhookPushEvent struct {
- Ref string `json:"ref"`
+ ObjectKind GitLabWebhookType `json:"object_kind"`
+ Ref string `json:"ref"`
+ Username string `json:"user_name"`
+ Project WebhookProject `json:"project"`
+ CommitList []WebhookCommit `json:"commits"`
+}
+
+func GET(instanceURL string, resourcePath string, token string) (*http.Response, error) {
+ url := fmt.Sprintf("%s/%s/%s", instanceURL, ApiPath, resourcePath)
+ req, err := http.NewRequest("GET",
+ url, nil)
+ if err != nil {
+ return nil, fmt.Errorf("failed to construct GET %v (%w)", url, err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Add("Authorization", "Bearer "+token)
+ client := &http.Client{}
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("failed GET %v (%w)", url, err)
+ }
+
+ return resp, nil
}
func PUT(instanceURL string, resourcePath string, token string, body io.Reader) (*http.Response, error) {
diff --git a/backend/server/database.go b/backend/server/database.go
index e6f443c763..2b67839d12 100644
--- a/backend/server/database.go
+++ b/backend/server/database.go
@@ -97,7 +97,10 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
}
- database, err := s.ComposeDatabaseById(context.Background(), id, c.Get(getIncludeKey()).([]string))
+ databaseFind := &api.DatabaseFind{
+ ID: &id,
+ }
+ database, err := s.ComposeDatabaseByFind(context.Background(), databaseFind, c.Get(getIncludeKey()).([]string))
if err != nil {
if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database ID not found: %d", id))
@@ -182,11 +185,8 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
})
}
-func (s *Server) ComposeDatabaseById(ctx context.Context, id int, includeList []string) (*api.Database, error) {
- databaseFind := &api.DatabaseFind{
- ID: &id,
- }
- database, err := s.DatabaseService.FindDatabase(context.Background(), databaseFind)
+func (s *Server) ComposeDatabaseByFind(ctx context.Context, find *api.DatabaseFind, includeList []string) (*api.Database, error) {
+ database, err := s.DatabaseService.FindDatabase(context.Background(), find)
if err != nil {
return nil, err
}
diff --git a/backend/server/task.go b/backend/server/task.go
index 6ff44c4bc8..b125091b41 100644
--- a/backend/server/task.go
+++ b/backend/server/task.go
@@ -135,7 +135,10 @@ func (s *Server) ComposeTaskRelationship(ctx context.Context, task *api.Task, in
return err
}
- task.Database, err = s.ComposeDatabaseById(context.Background(), task.DatabaseId, includeList)
+ databaseFind := &api.DatabaseFind{
+ ID: &task.DatabaseId,
+ }
+ task.Database, err = s.ComposeDatabaseByFind(context.Background(), databaseFind, includeList)
if err != nil {
return err
}
diff --git a/backend/server/webhook.go b/backend/server/webhook.go
index 096d6db241..1def2b3d60 100644
--- a/backend/server/webhook.go
+++ b/backend/server/webhook.go
@@ -1,11 +1,21 @@
package server
import (
+ "context"
+ "encoding/json"
"fmt"
+ "io"
"net/http"
- "time"
+ "net/url"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "github.com/bytebase/bytebase"
+ "github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/external/gitlab"
"github.com/labstack/echo/v4"
+ "go.uber.org/zap"
)
var (
@@ -13,7 +23,139 @@ var (
)
func (s *Server) registerWebhookRoutes(g *echo.Group) {
- g.POST("/gitlab/:uuid", func(c echo.Context) error {
- return c.String(http.StatusOK, fmt.Sprintf("[%v] Pong from backend", time.Now().Format("2006-01-02 15:04:05")))
+ g.POST("/gitlab/:id", func(c echo.Context) error {
+ var b []byte
+ // TODO: We may save the raw event in the furture for async processing.
+ b, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Failed to read webhook request").SetInternal(err)
+ }
+
+ pushEvent := &gitlab.WebhookPushEvent{}
+ if err := json.Unmarshal(b, pushEvent); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted push event").SetInternal(err)
+ }
+ s.l.Info((fmt.Sprintf("Push event: %+v", *pushEvent)))
+
+ webhookEndpointId := c.Param("id")
+ repositoryFind := &api.RepositoryFind{
+ WebhookEndpointId: &webhookEndpointId,
+ }
+ repository, err := s.RepositoryService.FindRepository(context.Background(), repositoryFind)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Endpoint not found: %v", webhookEndpointId))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to respond webhook event for endpoint: %v", webhookEndpointId)).SetInternal(err)
+ }
+
+ if err := s.ComposeRepositoryRelationship(context.Background(), repository, []string{}); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repository.Name)).SetInternal(err)
+ }
+
+ if c.Request().Header.Get("X-Gitlab-Token") != repository.SecretToken {
+ return echo.NewHTTPError(http.StatusBadRequest, "Secret token mismatch")
+ }
+
+ if strconv.Itoa(pushEvent.Project.ID) != repository.ExternalId {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project mismatch. Expect %s, got %d", repository.ExternalId, pushEvent.Project.ID))
+ }
+
+ createdMessageList := []string{}
+ for _, commit := range pushEvent.CommitList {
+ for _, added := range commit.AddedList {
+ if strings.HasPrefix(added, repository.BaseDirectory) && filepath.Ext(added) == ".sql" {
+ filename := filepath.Base(added)
+
+ // We expect filename in the {{version}}_{{dbname}}[_{{description}}]
+ // The description part is optional
+ parts := strings.Split(strings.TrimSuffix(filename, filepath.Ext(added)), "_")
+ if len(parts) < 2 {
+ s.l.Warn("Added SQL file name does not conform to the expected format. Ignored", zap.String("filename", filename))
+ continue
+ }
+ //version := parts[0]
+ dbName := parts[1]
+ description := ""
+ if len(parts) > 2 {
+ description = strings.Join(parts[2:], " ")
+ }
+
+ // Retrieve sql by reading the file content
+ resp, err := gitlab.GET(
+ repository.VCS.InstanceURL,
+ fmt.Sprintf("projects/%s/repository/files/%s/raw?ref=%s", repository.ExternalId, url.QueryEscape(added), commit.ID),
+ repository.VCS.AccessToken,
+ )
+ if err != nil {
+ s.l.Warn("Failed to read file. Ignored", zap.String("filename", filename), zap.Error(err))
+ continue
+ }
+
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ s.l.Warn("Failed to read file response. Ignored", zap.String("filename", filename), zap.Error(err))
+ continue
+ }
+
+ // Find matching database
+ databaseFind := &api.DatabaseFind{
+ ProjectId: &repository.ProjectId,
+ Name: &dbName,
+ }
+ database, err := s.ComposeDatabaseByFind(context.Background(), databaseFind, []string{})
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ s.l.Warn(fmt.Sprintf("Project ID %d does not contain database %s. Ignored", repository.ProjectId, dbName),
+ zap.Int("project_id", repository.ProjectId),
+ zap.String("filename", filename),
+ )
+
+ } else {
+ s.l.Warn("Failed to find database. Ignored", zap.String("filename", filename), zap.Error(err))
+ }
+ continue
+ }
+
+ // Compose the new issue
+ task := &api.TaskCreate{
+ InstanceId: database.InstanceId,
+ DatabaseId: database.ID,
+ Name: description,
+ Status: "PENDING",
+ Type: api.TaskDatabaseSchemaUpdate,
+ Statement: string(b),
+ }
+ stage := &api.StageCreate{
+ EnvironmentId: database.Instance.EnvironmentId,
+ TaskList: []api.TaskCreate{*task},
+ Name: fmt.Sprintf("Update %s schema", database.Name),
+ Type: api.StageDatabaseSchemaUpdate,
+ }
+ pipeline := &api.PipelineCreate{
+ StageList: []api.StageCreate{*stage},
+ Name: commit.Title,
+ }
+ issueCreate := &api.IssueCreate{
+ ProjectId: database.ProjectId,
+ Pipeline: *pipeline,
+ Name: commit.Title,
+ Type: api.IssueDatabaseSchemaUpdate,
+ Description: commit.Message,
+ AssigneeId: api.SYSTEM_BOT_ID,
+ }
+
+ issue, err := s.CreateIssue(context.Background(), issueCreate, api.SYSTEM_BOT_ID)
+ if err != nil {
+ s.l.Warn(fmt.Sprintf("Failed to create update schema task after adding %s", filename), zap.Error(err),
+ zap.String("filename", filename))
+ continue
+ }
+ createdMessageList = append(createdMessageList, fmt.Sprintf("Created issue '%s' on adding %s", issue.Name, filename))
+ }
+ }
+ }
+
+ return c.String(http.StatusOK, strings.Join(createdMessageList, "\n"))
})
}
diff --git a/backend/store/repository.go b/backend/store/repository.go
index f847334a25..7c3c8fd452 100644
--- a/backend/store/repository.go
+++ b/backend/store/repository.go
@@ -217,6 +217,9 @@ func findRepositoryList(ctx context.Context, tx *Tx, find *api.RepositoryFind) (
if v := find.ProjectId; v != nil {
where, args = append(where, "project_id = ?"), append(args, *v)
}
+ if v := find.WebhookEndpointId; v != nil {
+ where, args = append(where, "webhook_endpoint_id = ?"), append(args, *v)
+ }
rows, err := tx.QueryContext(ctx, `
SELECT