Skip to content

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

feat(test): implement test for vcs schema update, and fixed a few VCS flow bugs (#536)

Danny Xu4920fb741303
diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.go
index adfc514034..7451fd3fe5 100644
--- a/plugin/vcs/gitlab/gitlab.go
+++ b/plugin/vcs/gitlab/gitlab.go
@@ -106,16 +106,16 @@ type WebhookPushEvent struct {
CommitList []WebhookCommit `json:"commits"`
}
-// fileCommit is the API message for file commit.
-type fileCommit struct {
+// FileCommit is the API message for file commit.
+type FileCommit struct {
Branch string `json:"branch"`
Content string `json:"content"`
CommitMessage string `json:"commit_message"`
LastCommitID string `json:"last_commit_id,omitempty"`
}
-// fileMeta is the API message for file metadata.
-type fileMeta struct {
+// FileMeta is the API message for file metadata.
+type FileMeta struct {
LastCommitID string `json:"last_commit_id"`
}
@@ -139,7 +139,7 @@ func (provider *Provider) APIURL(instanceURL string) string {
}
func (provider *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) (*vcs.UserInfo, error) {
- resp, err := httpGet(
+ code, body, err := httpGet(
instanceURL,
"user",
&oauthCtx.AccessToken,
@@ -154,22 +154,17 @@ func (provider *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthCon
return nil, err
}
- if resp.StatusCode == 404 {
+ if code == 404 {
return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch user info from GitLab instance %s", instanceURL))
- } else if resp.StatusCode >= 300 {
+ } else if code >= 300 {
return nil, fmt.Errorf("failed to read user info from GitLab instance %s, status code: %d",
instanceURL,
- resp.StatusCode,
+ code,
)
}
- b, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
-
UserInfo := &vcs.UserInfo{}
- if err := json.Unmarshal(b, UserInfo); err != nil {
+ if err := json.Unmarshal([]byte(body), UserInfo); err != nil {
return nil, err
}
@@ -177,7 +172,7 @@ func (provider *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthCon
}
func (provider *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
- body, err := json.Marshal(fileCommit{
+ body, err := json.Marshal(FileCommit{
Branch: fileCommitCreate.Branch,
CommitMessage: fileCommitCreate.CommitMessage,
Content: fileCommitCreate.Content,
@@ -186,7 +181,7 @@ func (provider *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthC
return fmt.Errorf("failed to marshal file commit: %w", err)
}
- resp, err := httpPost(
+ code, _, err := httpPost(
instanceURL,
fmt.Sprintf("projects/%s/repository/files/%s", repositoryID, url.QueryEscape(filePath)),
&oauthCtx.AccessToken,
@@ -202,18 +197,18 @@ func (provider *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthC
return fmt.Errorf("failed to create file %s on GitLab instance %s, err: %w", filePath, instanceURL, err)
}
- if resp.StatusCode >= 300 {
+ if code >= 300 {
return fmt.Errorf("failed to create file %s on GitLab instance %s, status code: %d",
filePath,
instanceURL,
- resp.StatusCode,
+ code,
)
}
return nil
}
func (provider *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
- body, err := json.Marshal(fileCommit{
+ body, err := json.Marshal(FileCommit{
Branch: fileCommitCreate.Branch,
CommitMessage: fileCommitCreate.CommitMessage,
Content: fileCommitCreate.Content,
@@ -223,7 +218,7 @@ func (provider *Provider) OverwriteFile(ctx context.Context, oauthCtx common.Oau
return fmt.Errorf("failed to marshal file commit: %w", err)
}
- resp, err := httpPut(
+ code, _, err := httpPut(
instanceURL,
fmt.Sprintf("projects/%s/repository/files/%s", repositoryID, url.QueryEscape(filePath)),
&oauthCtx.AccessToken,
@@ -239,18 +234,18 @@ func (provider *Provider) OverwriteFile(ctx context.Context, oauthCtx common.Oau
return fmt.Errorf("failed to create file %s on GitLab instance %s, error: %w", filePath, instanceURL, err)
}
- if resp.StatusCode >= 300 {
+ if code >= 300 {
return fmt.Errorf("failed to create file %s on GitLab instance %s, status code: %d",
filePath,
instanceURL,
- resp.StatusCode,
+ code,
)
}
return nil
}
-func (provider *Provider) ReadFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, commitID string) (io.ReadCloser, error) {
- resp, err := httpGet(
+func (provider *Provider) ReadFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, commitID string) (string, error) {
+ code, body, err := httpGet(
instanceURL,
fmt.Sprintf("projects/%s/repository/files/%s/raw?ref=%s", repositoryID, url.QueryEscape(filePath), commitID),
&oauthCtx.AccessToken,
@@ -263,24 +258,24 @@ func (provider *Provider) ReadFile(ctx context.Context, oauthCtx common.OauthCon
)
if err != nil {
- return nil, fmt.Errorf("failed to read file %s from GitLab instance %s: %w", filePath, instanceURL, err)
+ return "", fmt.Errorf("failed to read file %s from GitLab instance %s: %w", filePath, instanceURL, err)
}
- if resp.StatusCode == 404 {
- return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to read file %s from GitLab instance %s, file not found", filePath, instanceURL))
- } else if resp.StatusCode >= 300 {
- return nil, fmt.Errorf("failed to read file %s from GitLab instance %s, status code: %d",
+ if code == 404 {
+ return "", common.Errorf(common.NotFound, fmt.Errorf("failed to read file %s from GitLab instance %s, file not found", filePath, instanceURL))
+ } else if code >= 300 {
+ return "", fmt.Errorf("failed to read file %s from GitLab instance %s, status code: %d",
filePath,
instanceURL,
- resp.StatusCode,
+ code,
)
}
- return resp.Body, nil
+ return body, nil
}
func (provider *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, branch string) (*vcs.FileMeta, error) {
- resp, err := httpGet(
+ code, body, err := httpGet(
instanceURL,
fmt.Sprintf("projects/%s/repository/files/%s?ref=%s", repositoryID, url.QueryEscape(filePath), url.QueryEscape(branch)),
&oauthCtx.AccessToken,
@@ -296,19 +291,18 @@ func (provider *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.Oaut
return nil, fmt.Errorf("failed to read file meta %s from GitLab instance %s: %w", filePath, instanceURL, err)
}
- if resp.StatusCode == 404 {
+ if code == 404 {
return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to read file meta %s from GitLab instance %s, file not found", filePath, instanceURL))
- } else if resp.StatusCode >= 300 {
+ } else if code >= 300 {
return nil, fmt.Errorf("failed to read file meta %s from GitLab instance %s, status code: %d",
filePath,
instanceURL,
- resp.StatusCode,
+ code,
)
}
- defer resp.Body.Close()
- file := &fileMeta{}
- if err := json.NewDecoder(resp.Body).Decode(file); err != nil {
+ file := &FileMeta{}
+ if err := json.Unmarshal([]byte(body), file); err != nil {
return nil, fmt.Errorf("failed to unmarshal file meta from GitLab instance %s: %w", instanceURL, err)
}
@@ -319,7 +313,7 @@ func (provider *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.Oaut
func (provider *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, payload []byte) (string, error) {
resourcePath := fmt.Sprintf("projects/%s/hooks", repositoryID)
- resp, err := httpPost(
+ code, body, err := httpPost(
instanceURL,
resourcePath,
&oauthCtx.AccessToken,
@@ -334,17 +328,16 @@ func (provider *Provider) CreateWebhook(ctx context.Context, oauthCtx common.Oau
if err != nil {
return "", fmt.Errorf("failed to create webhook for repository %s from GitLab instance %s: %w", repositoryID, instanceURL, err)
}
- defer resp.Body.Close()
- if resp.StatusCode >= 300 {
+ if code >= 300 {
reason := fmt.Sprintf(
"failed to create webhook for repository %s from GitLab instance %s, status code: %d",
repositoryID,
instanceURL,
- resp.StatusCode,
+ code,
)
// Add helper tips if the status code is 422, refer to bytebase#101 for more context.
- if resp.StatusCode == http.StatusUnprocessableEntity {
+ if code == http.StatusUnprocessableEntity {
reason += ".\n\nIf GitLab and Bytebase are in the same private network, " +
"please follow the instructions in https://docs.gitlab.com/ee/security/webhooks.html"
}
@@ -352,7 +345,7 @@ func (provider *Provider) CreateWebhook(ctx context.Context, oauthCtx common.Oau
}
webhookInfo := &WebhookInfo{}
- if err := json.NewDecoder(resp.Body).Decode(webhookInfo); err != nil {
+ if err := json.Unmarshal([]byte(body), webhookInfo); err != nil {
return "", fmt.Errorf("failed to unmarshal create webhook response for repository %s from GitLab instance %s: %w", repositoryID, instanceURL, err)
}
return strconv.Itoa(webhookInfo.ID), nil
@@ -360,7 +353,7 @@ func (provider *Provider) CreateWebhook(ctx context.Context, oauthCtx common.Oau
func (provider *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, webhookId string, payload []byte) error {
resourcePath := fmt.Sprintf("projects/%s/hooks/%s", repositoryID, webhookId)
- resp, err := httpPut(
+ code, _, err := httpPut(
instanceURL,
resourcePath,
&oauthCtx.AccessToken,
@@ -376,15 +369,15 @@ func (provider *Provider) PatchWebhook(ctx context.Context, oauthCtx common.Oaut
return fmt.Errorf("failed to patch webhook ID %s for repository %s from GitLab instance %s: %w", webhookId, repositoryID, instanceURL, err)
}
- if resp.StatusCode >= 300 {
- return fmt.Errorf("failed to patch webhook ID %s for repository %s from GitLab instance %s, status code: %d", webhookId, repositoryID, instanceURL, resp.StatusCode)
+ if code >= 300 {
+ return fmt.Errorf("failed to patch webhook ID %s for repository %s from GitLab instance %s, status code: %d", webhookId, repositoryID, instanceURL, code)
}
return nil
}
func (provider *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, webhookId string) error {
resourcePath := fmt.Sprintf("projects/%s/hooks/%s", repositoryID, webhookId)
- resp, err := httpDelete(
+ code, _, err := httpDelete(
instanceURL,
resourcePath,
&oauthCtx.AccessToken,
@@ -399,14 +392,14 @@ func (provider *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.Oau
return fmt.Errorf("failed to delete webhook ID %s for repository %s from GitLab instance %s: %w", webhookId, repositoryID, instanceURL, err)
}
- if resp.StatusCode >= 300 {
- return fmt.Errorf("failed to delete webhook ID %s for repository %s from GitLab instance %s, status code: %d", webhookId, repositoryID, instanceURL, resp.StatusCode)
+ if code >= 300 {
+ return fmt.Errorf("failed to delete webhook ID %s for repository %s from GitLab instance %s, status code: %d", webhookId, repositoryID, instanceURL, code)
}
return nil
}
// httpPost sends a POST request.
-func httpPost(instanceURL string, resourcePath string, token *string, body io.Reader, oauthContext oauthContext, refresher common.TokenRefresher) (*http.Response, error) {
+func httpPost(instanceURL string, resourcePath string, token *string, body io.Reader, oauthContext oauthContext, refresher common.TokenRefresher) (code int, respBody string, err error) {
return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {
url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)
req, err := http.NewRequest("POST",
@@ -427,7 +420,7 @@ func httpPost(instanceURL string, resourcePath string, token *string, body io.Re
}
// httpGet sends a GET request.
-func httpGet(instanceURL string, resourcePath string, token *string, oauthContext oauthContext, refresher common.TokenRefresher) (*http.Response, error) {
+func httpGet(instanceURL string, resourcePath string, token *string, oauthContext oauthContext, refresher common.TokenRefresher) (code int, respBody string, err error) {
return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {
url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)
req, err := http.NewRequest("GET",
@@ -448,7 +441,7 @@ func httpGet(instanceURL string, resourcePath string, token *string, oauthContex
}
// httpPut sends a PUT request.
-func httpPut(instanceURL string, resourcePath string, token *string, body io.Reader, oauthContext oauthContext, refresher common.TokenRefresher) (*http.Response, error) {
+func httpPut(instanceURL string, resourcePath string, token *string, body io.Reader, oauthContext oauthContext, refresher common.TokenRefresher) (code int, respBody string, err error) {
return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {
url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)
req, err := http.NewRequest("PUT",
@@ -469,7 +462,7 @@ func httpPut(instanceURL string, resourcePath string, token *string, body io.Rea
}
// httpDelete sends a DELETE request.
-func httpDelete(instanceURL string, resourcePath string, token *string, oauthContext oauthContext, refresher common.TokenRefresher) (*http.Response, error) {
+func httpDelete(instanceURL string, resourcePath string, token *string, oauthContext oauthContext, refresher common.TokenRefresher) (code int, respBody string, err error) {
return retry(instanceURL, token, oauthContext, refresher, func() (*http.Response, error) {
url := fmt.Sprintf("%s/%s/%s", instanceURL, apiPath, resourcePath)
req, err := http.NewRequest("DELETE",
@@ -489,28 +482,34 @@ func httpDelete(instanceURL string, resourcePath string, token *string, oauthCon
})
}
-func retry(instanceURL string, token *string, oauthContext oauthContext, refresher common.TokenRefresher, f func() (*http.Response, error)) (*http.Response, error) {
+func retry(instanceURL string, token *string, oauthContext oauthContext, refresher common.TokenRefresher, f func() (*http.Response, error)) (code int, respBody string, err error) {
retries := 0
RETRY:
retries++
resp, err := f()
if err != nil {
- return nil, err
+ return 0, "", err
}
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return 0, "", fmt.Errorf("failed to read gitlab response body, code %v, error: %v", resp.StatusCode, err)
+ }
+
+ if err := getOAuthErrorDetails(resp.StatusCode, string(body)); err != nil {
+ if _, ok := err.(oauthError); ok && retries < maxRetries {
+ // Refresh and store the token.
+ if err := refreshToken(instanceURL, token, oauthContext, refresher); err != nil {
+ return 0, "", err
+ }
+ goto RETRY
- if err := getOAuthErrorDetails(resp); err != nil && retries < maxRetries {
- // Refresh and store the token.
- if err := refreshToken(instanceURL, token, oauthContext, refresher); err != nil {
- return nil, err
}
- goto RETRY
- }
- if err != nil {
- return nil, err
+ // err must be oauthError. So this happens only when the number of retries has exceeded.
+ return 0, "", fmt.Errorf("retries exceeded for oauth refresher; original code %v body %s; oauth error: %v", resp.StatusCode, string(body), err)
}
- return resp, nil
+ return resp.StatusCode, string(body), nil
}
type oauthError struct {
@@ -518,7 +517,7 @@ type oauthError struct {
ErrorDescription string `json:"error_description"`
}
-func (e *oauthError) Error() string {
+func (e oauthError) Error() string {
return fmt.Sprintf("gitlab oauth response error %q description %q", e.Err, e.ErrorDescription)
}
@@ -526,17 +525,15 @@ func (e *oauthError) Error() string {
// We do this because this method is only intended to be used by oauth to refresh access token
// on expiration. When it's error like 404, GitLab api doesn't return it as error so we keep the
// similar behavior and let caller check the response status code.
-func getOAuthErrorDetails(resp *http.Response) error {
- if 200 <= resp.StatusCode && resp.StatusCode < 300 {
+func getOAuthErrorDetails(code int, body string) error {
+ if 200 <= code && code < 300 {
return nil
}
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return err
- }
+
var oe oauthError
- if err = json.Unmarshal([]byte(body), &oe); err != nil {
- return err
+ if err := json.Unmarshal([]byte(body), &oe); err != nil {
+ // If we failed to unmarshal body with oauth error, it's not oauthError and we should return nil.
+ return nil
}
// https://www.oauth.com/oauth2-servers/access-tokens/access-token-response/
// {"error":"invalid_token","error_description":"Token is expired. You can either do re-authorization or token refresh."}
@@ -580,15 +577,19 @@ func refreshToken(instanceURL string, oldToken *string, oauthContext oauthContex
if err != nil {
return fmt.Errorf("failed to send refresh token POST %v (%w)", url, err)
}
- if err := getOAuthErrorDetails(resp); err != nil {
- return err
- }
-
body, err = io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read body from refresh token POST %v (%w)", url, err)
}
+ // We should not call getOAuthErrorDetails.
+ // In the sequence of 1) get file content with oauth error, 2) refresh token.
+ // If step 2) failed still with oauth error, we should stop retries because we should always expect refreshing token request to succeed unless we're holding any invalid refresh token already.
+
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("failed to fetch refresh token, response code %v body %s", resp.StatusCode, body)
+ }
+
var r refreshOauthResponse
if err := json.Unmarshal([]byte(body), &r); err != nil {
return fmt.Errorf("failed to unmarshal body from refresh token POST %v (%w)", url, err)
diff --git a/plugin/vcs/vcs.go b/plugin/vcs/vcs.go
index 2969a8c81a..da8f425d00 100644
--- a/plugin/vcs/vcs.go
+++ b/plugin/vcs/vcs.go
@@ -2,7 +2,6 @@ package vcs
import (
"context"
- "io"
"sync"
"github.com/bytebase/bytebase/common"
@@ -108,7 +107,7 @@ type Provider interface {
// repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
// filePath: file path to be read
// commitID: the specific version to be read
- ReadFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, commitID string) (io.ReadCloser, error)
+ ReadFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, commitID string) (string, error)
// Reads the file metadata. Returns the file meta on success.
//
// Similar to ReadFile except it specifies a branch instead of a commitID.
diff --git a/server/webhook.go b/server/webhook.go
index 36cec208d3..ce811287b4 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -141,7 +141,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
}
// Retrieve sql by reading the file content
- reader, err := vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: s.l}).ReadFile(
+ content, err := vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: s.l}).ReadFile(
ctx,
common.OauthContext{
ClientID: repository.VCS.ApplicationID,
@@ -159,13 +159,6 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
createIgnoredFileActivity(err)
continue
}
- defer reader.Close()
-
- b, err := io.ReadAll(reader)
- if err != nil {
- createIgnoredFileActivity(fmt.Errorf("failed to read file response: %w", err))
- continue
- }
// Create schema update issue.
var createContext string
@@ -173,9 +166,9 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
if !s.feature(api.FeatureMultiTenancy) {
return echo.NewHTTPError(http.StatusForbidden, api.FeatureMultiTenancy.AccessErrorMessage())
}
- createContext, err = s.createTenantSchemaUpdateIssue(ctx, repository, mi, vcsPushEvent, commit, added, string(b))
+ createContext, err = s.createTenantSchemaUpdateIssue(ctx, repository, mi, vcsPushEvent, commit, added, content)
} else {
- createContext, err = s.createSchemaUpdateIssue(ctx, repository, mi, vcsPushEvent, commit, added, string(b))
+ createContext, err = s.createSchemaUpdateIssue(ctx, repository, mi, vcsPushEvent, commit, added, content)
}
if err != nil {
createIgnoredFileActivity(err)
diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.go
index 8df331cfaa..b8499e48ca 100644
--- a/tests/fake/gitlab.go
+++ b/tests/fake/gitlab.go
@@ -5,6 +5,7 @@ import (
"fmt"
"io"
"net/http"
+ "net/url"
"strings"
"github.com/bytebase/bytebase/plugin/vcs/gitlab"
@@ -20,7 +21,12 @@ type GitLab struct {
client *http.Client
nextWebhookID int
- projectHooks map[string][]*gitlab.WebhookPost
+ projects map[string]*projectData
+}
+
+type projectData struct {
+ webhooks []*gitlab.WebhookPost
+ files map[string]string
}
// NewGitLab creates a fake GitLab.
@@ -35,12 +41,15 @@ func NewGitLab(port int) *GitLab {
Echo: e,
client: &http.Client{},
nextWebhookID: 20210113,
- projectHooks: map[string][]*gitlab.WebhookPost{},
+ projects: map[string]*projectData{},
}
// Routes
projectGroup := e.Group("/api/v4")
projectGroup.POST("/projects/:id/hooks", gl.createProjectHook)
+ projectGroup.GET("/projects/:id/repository/files/:file/raw", gl.readProjectFile)
+ projectGroup.GET("/projects/:id/repository/files/:file", gl.readProjectFileMetadata)
+ projectGroup.POST("/projects/:id/repository/files/:file", gl.createProjectFile)
return gl
}
@@ -57,7 +66,9 @@ func (gl *GitLab) Close() error {
// CreateProject creates a GitLab project.
func (gl *GitLab) CreateProject(id string) {
- gl.projectHooks[id] = nil
+ gl.projects[id] = &projectData{
+ files: map[string]string{},
+ }
}
// createProjectHook creates a project webhook.
@@ -72,10 +83,11 @@ func (gl *GitLab) createProjectHook(c echo.Context) error {
if err := json.Unmarshal(b, webhookPost); err != nil {
return fmt.Errorf("failed to unmarshal create project hook request body, error %w", err)
}
- if _, ok := gl.projectHooks[gitlabProjectID]; !ok {
+ pd, ok := gl.projects[gitlabProjectID]
+ if !ok {
return fmt.Errorf("gitlab project %q doesn't exist", gitlabProjectID)
}
- gl.projectHooks[gitlabProjectID] = append(gl.projectHooks[gitlabProjectID], webhookPost)
+ pd.webhooks = append(pd.webhooks, webhookPost)
if err := json.NewEncoder(c.Response().Writer).Encode(&gitlab.WebhookInfo{
ID: gl.nextWebhookID,
@@ -87,27 +99,104 @@ func (gl *GitLab) createProjectHook(c echo.Context) error {
return nil
}
+// createProjectHook creates a project webhook.
+func (gl *GitLab) readProjectFile(c echo.Context) error {
+ gitlabProjectID := c.Param("id")
+ fileNameEscaped := c.Param("file")
+ fileName, err := url.QueryUnescape(fileNameEscaped)
+ if err != nil {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("failed to query unescape %q, error: %v", fileNameEscaped, err))
+ }
+
+ pd, ok := gl.projects[gitlabProjectID]
+ if !ok {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", gitlabProjectID))
+ }
+
+ content, ok := pd.files[fileName]
+ if !ok {
+ return c.String(http.StatusNotFound, fmt.Sprintf("file %q not found", fileName))
+ }
+
+ return c.String(http.StatusOK, content)
+}
+
+// createProjectHook creates a project webhook.
+func (gl *GitLab) readProjectFileMetadata(c echo.Context) error {
+ gitlabProjectID := c.Param("id")
+ fileNameEscaped := c.Param("file")
+ fileName, err := url.QueryUnescape(fileNameEscaped)
+ if err != nil {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("failed to query unescape %q, error: %v", fileNameEscaped, err))
+ }
+
+ pd, ok := gl.projects[gitlabProjectID]
+ if !ok {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", gitlabProjectID))
+ }
+
+ if _, ok := pd.files[fileName]; !ok {
+ return c.String(http.StatusNotFound, fmt.Sprintf("file %q not found", fileName))
+ }
+
+ buf, err := json.Marshal(&gitlab.FileMeta{})
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal FileMeta, error %v", err))
+ }
+
+ return c.String(http.StatusOK, string(buf))
+}
+
+// createProjectHook creates a project file.
+func (gl *GitLab) createProjectFile(c echo.Context) error {
+ gitlabProjectID := c.Param("id")
+ fileNameEscaped := c.Param("file")
+ fileName, err := url.QueryUnescape(fileNameEscaped)
+ if err != nil {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("failed to query unescape %q, error: %v", fileNameEscaped, err))
+ }
+ b, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read create project file request body, error %v", err))
+ }
+ fileCommit := &gitlab.FileCommit{}
+ if err := json.Unmarshal(b, fileCommit); err != nil {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("failed to unmarshal create project file request body, error %v", err))
+ }
+
+ pd, ok := gl.projects[gitlabProjectID]
+ if !ok {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", gitlabProjectID))
+ }
+
+ // Save file.
+ pd.files[fileName] = fileCommit.Content
+
+ return c.String(http.StatusOK, "")
+}
+
// SendCommits sends comments to webhooks.
func (gl *GitLab) SendCommits(gitlabProjectID string, webhookPushEvent *gitlab.WebhookPushEvent) error {
- webhookPosts, ok := gl.projectHooks[gitlabProjectID]
+ pd, ok := gl.projects[gitlabProjectID]
if !ok {
return fmt.Errorf("gitlab project %q doesn't exist", gitlabProjectID)
}
- for _, webhookPost := range webhookPosts {
+ // Trigger webhooks.
+ for _, webhook := range pd.webhooks {
// Send post request.
buf, err := json.Marshal(webhookPushEvent)
if err != nil {
return fmt.Errorf("failed to marshal webhookPushEvent, error %w", err)
}
- req, err := http.NewRequest("POST", webhookPost.URL, strings.NewReader(string(buf)))
+ req, err := http.NewRequest("POST", webhook.URL, strings.NewReader(string(buf)))
if err != nil {
- return fmt.Errorf("fail to create a new POST request(%q), error: %w", webhookPost.URL, err)
+ return fmt.Errorf("fail to create a new POST request(%q), error: %w", webhook.URL, err)
}
- req.Header.Set("X-Gitlab-Token", webhookPost.SecretToken)
+ req.Header.Set("X-Gitlab-Token", webhook.SecretToken)
resp, err := gl.client.Do(req)
if err != nil {
- return fmt.Errorf("fail to send a POST request(%q), error: %w", webhookPost.URL, err)
+ return fmt.Errorf("fail to send a POST request(%q), error: %w", webhook.URL, err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
@@ -122,3 +211,17 @@ func (gl *GitLab) SendCommits(gitlabProjectID string, webhookPushEvent *gitlab.W
return nil
}
+
+// AddFiles add files to repository.
+func (gl *GitLab) AddFiles(gitlabProjectID string, files map[string]string) error {
+ pd, ok := gl.projects[gitlabProjectID]
+ if !ok {
+ return fmt.Errorf("gitlab project %q doesn't exist", gitlabProjectID)
+ }
+
+ // Save files
+ for name, content := range files {
+ pd.files[name] = content
+ }
+ return nil
+}
diff --git a/tests/schema_update_test.go b/tests/schema_update_test.go
index 2d73cc3149..dfeb2d7cc2 100644
--- a/tests/schema_update_test.go
+++ b/tests/schema_update_test.go
@@ -19,6 +19,14 @@ import (
//go:embed fake
var fakeFS embed.FS
+var (
+ migrationStatement = `
+ CREATE TABLE book (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL
+ );`
+)
+
func TestSchemaUpdate(t *testing.T) {
ctx := context.Background()
ctl := &controller{}
@@ -32,6 +40,7 @@ func TestSchemaUpdate(t *testing.T) {
t.Fatal(err)
}
+ // Switch plan to increase instance limit.
license, err := fs.ReadFile(fakeFS, "fake/license")
if err != nil {
t.Fatal(err)
@@ -94,7 +103,7 @@ func TestSchemaUpdate(t *testing.T) {
t.Fatalf("failed to get databases, error: %v", err)
}
if len(databases) != 0 {
- t.Fatalf("invalid number of databases %v in project %v, expecting no database", project.ID, len(databases))
+ t.Fatalf("invalid number of databases %v in project %v, expecting no database", len(databases), project.ID)
}
// Expecting instance to have no database.
databases, err = ctl.getDatabases(api.DatabaseFind{
@@ -104,7 +113,7 @@ func TestSchemaUpdate(t *testing.T) {
t.Fatalf("failed to get databases, error: %v", err)
}
if len(databases) != 0 {
- t.Fatalf("invalid number of databases %v in instance %v, expecting no database", instance1.ID, len(databases))
+ t.Fatalf("invalid number of databases %v in instance %v, expecting no database", len(databases), instance1.ID)
}
// Create an issue that creates a database.
@@ -128,11 +137,9 @@ func TestSchemaUpdate(t *testing.T) {
if err != nil {
t.Fatalf("failed to create database creation issue, error: %v", err)
}
-
if status, _ := getAggregatedTaskStatus(issue); status != api.TaskPendingApproval {
t.Fatalf("issue %v pipeline %v is supposed to be pending manual approval.", issue.ID, issue.Pipeline.ID)
}
-
status, err := ctl.waitIssuePipeline(issue.ID)
if err != nil {
t.Fatalf("failed to wait for issue %v pipeline %v, error: %v", issue.ID, issue.Pipeline.ID, err)
@@ -156,11 +163,6 @@ func TestSchemaUpdate(t *testing.T) {
t.Fatalf("expect database %v name %q to be in instance %v, got %v", database.ID, database.Name, instance1.ID, database.Instance.ID)
}
- migrationStatement := `
- CREATE TABLE book (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- name TEXT NOT NULL
- );`
// Create an issue that updates database schema.
createContext, err = json.Marshal(&api.UpdateSchemaContext{
MigrationType: db.Migrate,
@@ -226,6 +228,18 @@ func TestVCSSchemaUpdate(t *testing.T) {
t.Fatal(err)
}
+ // Switch plan to increase instance limit.
+ license, err := fs.ReadFile(fakeFS, "fake/license")
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = ctl.switchPlan(&enterpriseAPI.SubscriptionPatch{
+ License: string(license),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
// Create a VCS.
applicationID := "testApplicationID"
applicationSecret := "testApplicationSecret"
@@ -264,7 +278,7 @@ func TestVCSSchemaUpdate(t *testing.T) {
Name: "Test Repository",
FullPath: repositoryPath,
WebURL: fmt.Sprintf("%s/%s", gitURL, repositoryPath),
- BranchFilter: "master",
+ BranchFilter: "feature/foo",
BaseDirectory: "bbtest",
FilePathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",
SchemaPathTemplate: "{{ENV_NAME}}/.{{DB_NAME}}__LATEST.sql",
@@ -277,14 +291,132 @@ func TestVCSSchemaUpdate(t *testing.T) {
t.Fatalf("failed to create repository, error: %v", err)
}
+ // Provision an instance.
+ instanceDir := t.TempDir()
+ instance1Name := "testInstance1"
+ instance1Dir, err := ctl.provisionSQLiteInstance(instanceDir, instance1Name)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ environments, err := ctl.getEnvironments()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var prodEnvironment *api.Environment
+ for _, environment := range environments {
+ if environment.Name == "Prod" {
+ prodEnvironment = environment
+ break
+ }
+ }
+ if prodEnvironment == nil {
+ t.Fatal("unable to find prod environment")
+ }
+
+ // Add an instance.
+ instance1, err := ctl.addInstance(api.InstanceCreate{
+ EnvironmentID: prodEnvironment.ID,
+ Name: instance1Name,
+ Engine: db.SQLite,
+ Host: instance1Dir,
+ })
+ if err != nil {
+ t.Fatalf("failed to add instance, error: %v", err)
+ }
+ // Create an issue that creates a database.
+ databaseName := "testVCSSchemaUpdate"
+ createContext, err := json.Marshal(&api.CreateDatabaseContext{
+ InstanceID: instance1.ID,
+ DatabaseName: databaseName,
+ })
+ if err != nil {
+ t.Fatal(fmt.Errorf("failed to construct database creation issue CreateContext payload, error: %w", err))
+ }
+ issue, err := ctl.createIssue(api.IssueCreate{
+ ProjectID: project.ID,
+ Name: fmt.Sprintf("create database %q", databaseName),
+ Type: api.IssueDatabaseCreate,
+ Description: fmt.Sprintf("This creates a database %q.", databaseName),
+ // Assign to self.
+ AssigneeID: project.Creator.ID,
+ CreateContext: string(createContext),
+ })
+ if err != nil {
+ t.Fatalf("failed to create database creation issue, error: %v", err)
+ }
+ status, err := ctl.waitIssuePipeline(issue.ID)
+ if err != nil {
+ t.Fatalf("failed to wait for issue %v pipeline %v, error: %v", issue.ID, issue.Pipeline.ID, err)
+ }
+ if status != api.TaskDone {
+ t.Fatalf("issue %v pipeline %v is expected to finish with status done, got %v", issue.ID, issue.Pipeline.ID, status)
+ }
+ issue, err = ctl.patchIssueStatus(api.IssueStatusPatch{
+ ID: issue.ID,
+ Status: api.IssueDone,
+ })
+ if err != nil {
+ t.Fatalf("failed to patch issue status %v to done, error: %v", issue.ID, err)
+ }
+
// Simulate Git commits.
+ file1 := "bbtest/Prod/testVCSSchemaUpdate__ver1__migrate__create_a_test_table.sql"
pushEvent := &gitlab.WebhookPushEvent{
ObjectKind: gitlab.WebhookPush,
+ Ref: "refs/heads/feature/foo",
Project: gitlab.WebhookProject{
ID: gitlabProjectID,
},
+ CommitList: []gitlab.WebhookCommit{
+ {
+ Timestamp: "2021-01-13T13:14:00Z",
+ AddedList: []string{
+ file1,
+ },
+ },
+ },
+ }
+ if err := ctl.gitlab.AddFiles(gitlabProjectIDStr, map[string]string{file1: migrationStatement}); err != nil {
+ t.Fatalf("failed to add files to gitlab project %q, error %v", gitlabProjectID, err)
}
if err := ctl.gitlab.SendCommits(gitlabProjectIDStr, pushEvent); err != nil {
t.Fatalf("failed to send commits to gitlab project %q, error %v", gitlabProjectID, err)
}
+
+ // Get schema update issue.
+ openStatus := []api.IssueStatus{api.IssueOpen}
+ issues, err := ctl.getIssues(api.IssueFind{ProjectID: &project.ID, StatusList: &openStatus})
+ if err != nil {
+ t.Fatalf("failed to get open issues for project %v, error: %v", project.ID, err)
+ }
+ if len(issues) != 1 {
+ t.Fatalf("invalid number of open issues %v in project %v, expecting one issue", len(issues), project.ID)
+ }
+ issue = issues[0]
+ status, err = ctl.waitIssuePipeline(issue.ID)
+ if err != nil {
+ t.Fatalf("failed to wait for issue %v pipeline %v, error: %v", issue.ID, issue.Pipeline.ID, err)
+ }
+ if status != api.TaskDone {
+ t.Fatalf("issue %v pipeline %v is expected to finish with status done got %v", issue.ID, issue.Pipeline.ID, status)
+ }
+
+ // Query schema.
+ sqlResultSet, err := ctl.executeSQL(api.SQLExecute{
+ InstanceID: instance1.ID,
+ DatabaseName: databaseName,
+ Statement: "SELECT * FROM sqlite_schema WHERE type = 'table' AND tbl_name = 'book';",
+ Readonly: true,
+ })
+ if err != nil {
+ t.Fatalf("failed to execute SQL, error: %v", err)
+ }
+ if sqlResultSet.Error != "" {
+ t.Fatalf("expect SQL result has no error, got %q", sqlResultSet.Error)
+ }
+ wantResult := `[{"name":"book","rootpage":"2","sql":"CREATE TABLE book (\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\tname TEXT NOT NULL\n\t)","tbl_name":"book","type":"table"}]`
+ if sqlResultSet.Data != wantResult {
+ t.Fatalf("want SQL result %q, got %q, diff %q", wantResult, sqlResultSet.Data, pretty.Diff(wantResult, sqlResultSet.Data))
+ }
}
diff --git a/tests/tests.go b/tests/tests.go
index 2810da8e00..d7cdebd4ea 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -401,6 +401,58 @@ func (ctl *controller) getIssue(id int) (*api.Issue, error) {
return issue, nil
}
+// getIssue gets the issue with given ID.
+func (ctl *controller) getIssues(issueFind api.IssueFind) ([]*api.Issue, error) {
+ params := make(map[string]string)
+ if issueFind.ProjectID != nil {
+ params["project"] = fmt.Sprintf("%d", *issueFind.ProjectID)
+ }
+ if issueFind.StatusList != nil && len(*issueFind.StatusList) > 0 {
+ var sl []string
+ for _, status := range *issueFind.StatusList {
+ sl = append(sl, string(status))
+ }
+ params["status"] = strings.Join(sl, ",")
+ }
+ body, err := ctl.get("/issue", params)
+ if err != nil {
+ return nil, err
+ }
+
+ var issues []*api.Issue
+ ps, err := jsonapi.UnmarshalManyPayload(body, reflect.TypeOf(new(api.Issue)))
+ if err != nil {
+ return nil, fmt.Errorf("fail to unmarshal get issue response, error %w", err)
+ }
+ for _, p := range ps {
+ issue, ok := p.(*api.Issue)
+ if !ok {
+ return nil, fmt.Errorf("fail to convert issue")
+ }
+ issues = append(issues, issue)
+ }
+ return issues, nil
+}
+
+// patchIssue patches the issue with given ID.
+func (ctl *controller) patchIssueStatus(issueStatusPatch api.IssueStatusPatch) (*api.Issue, error) {
+ buf := new(bytes.Buffer)
+ if err := jsonapi.MarshalPayload(buf, &issueStatusPatch); err != nil {
+ return nil, fmt.Errorf("failed to marshal issue status patch, error: %w", err)
+ }
+
+ body, err := ctl.patch(fmt.Sprintf("/issue/%d/status", issueStatusPatch.ID), buf)
+ if err != nil {
+ return nil, err
+ }
+
+ issue := new(api.Issue)
+ if err = jsonapi.UnmarshalPayload(body, issue); err != nil {
+ return nil, fmt.Errorf("fail to unmarshal patch issue status patch response, error: %w", err)
+ }
+ return issue, nil
+}
+
// patchTaskStatus patches the status of a task in the pipeline stage.
func (ctl *controller) patchTaskStatus(taskStatusPatch api.TaskStatusPatch, pipelineID int) (*api.Task, error) {
buf := new(bytes.Buffer)
@@ -450,7 +502,11 @@ func getAggregatedTaskStatus(issue *api.Issue) (api.TaskStatus, error) {
case api.TaskPendingApproval:
return api.TaskPendingApproval, nil
case api.TaskFailed:
- return api.TaskFailed, fmt.Errorf("pipeline task %v failed payload %q", task.ID, task.Payload)
+ var runs []string
+ for _, run := range task.TaskRunList {
+ runs = append(runs, fmt.Sprintf("%+v", run))
+ }
+ return api.TaskFailed, fmt.Errorf("pipeline task %v failed runs: %v", task.ID, strings.Join(runs, ", "))
case api.TaskCanceled:
return api.TaskCanceled, nil
case api.TaskRunning: