Skip to content

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

Webhook backend support

天舟a93368fb9a5d
diff --git a/.air.toml b/.air.toml
index 95c757c007..0599018aba 100644
--- a/.air.toml
+++ b/.air.toml
@@ -2,7 +2,7 @@ root = "."
tmp_dir = ".air"
[build]
- bin = "./.air/bytebase --port 8080 --data ."
+ bin = "./.air/bytebase --port 8080 --frontend-port 3000 --data ."
cmd = "go build -o ./.air/bytebase ./bin/server/main.go"
delay = 1000
exclude_dir = [".air", "vendor", "frontend"]
diff --git a/.air_debug.toml b/.air_debug.toml
index 68274d4e4e..cd7df2b720 100644
--- a/.air_debug.toml
+++ b/.air_debug.toml
@@ -2,7 +2,7 @@ root = "."
tmp_dir = ".air"
[build]
- bin = "./.air/bytebase --port 8080 --debug --data ."
+ bin = "./.air/bytebase --port 8080 --frontend-port 3000 --debug --data ."
cmd = "go build --tags \"sqlite_trace\" -o ./.air/bytebase ./bin/server/main.go"
delay = 1000
exclude_dir = [".air", "vendor", "frontend"]
diff --git a/.air_demo.toml b/.air_demo.toml
index 4c9795e460..79026fbdbe 100644
--- a/.air_demo.toml
+++ b/.air_demo.toml
@@ -2,7 +2,7 @@ root = "."
tmp_dir = ".air"
[build]
- bin = "./.air/bytebase --demo --port 8080 --data ."
+ bin = "./.air/bytebase --demo --port 8080 --frontend-port 3000 --data ."
cmd = "go build -o ./.air/bytebase ./bin/server/main.go"
delay = 1000
exclude_dir = [".air", "vendor", "frontend"]
diff --git a/api/issue.go b/api/issue.go
index 2c1928ecd7..582c14171f 100644
--- a/api/issue.go
+++ b/api/issue.go
@@ -3,6 +3,9 @@ package api
import (
"context"
"encoding/json"
+ "fmt"
+
+ "github.com/gosimple/slug"
)
// Issue status
@@ -171,3 +174,7 @@ type IssueService interface {
FindIssue(ctx context.Context, find *IssueFind) (*Issue, error)
PatchIssue(ctx context.Context, patch *IssuePatch) (*Issue, error)
}
+
+func IssueSlug(issue *Issue) string {
+ return fmt.Sprintf("%s-%d", slug.Make(issue.Name), issue.ID)
+}
diff --git a/api/project_hook.go b/api/project_hook.go
new file mode 100644
index 0000000000..bd8f1d908b
--- /dev/null
+++ b/api/project_hook.go
@@ -0,0 +1,89 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+)
+
+type ProjectHook struct {
+ ID int `jsonapi:"primary,projectWebhookMember"`
+
+ // Standard fields
+ CreatorId int
+ Creator *Principal `jsonapi:"attr,creator"`
+ CreatedTs int64 `jsonapi:"attr,createdTs"`
+ UpdaterId int
+ Updater *Principal `jsonapi:"attr,updater"`
+ UpdatedTs int64 `jsonapi:"attr,updatedTs"`
+
+ // Related fields
+ // Just returns ProjectId since it always operates within the project context
+ ProjectId int `jsonapi:"attr,projecId"`
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ Description string `jsonapi:"attr,description"`
+ URL string `jsonapi:"attr,url"`
+ ActivityList []string `jsonapi:"attr,activityList"`
+}
+
+type ProjectHookCreate struct {
+ // Standard fields
+ // Value is assigned from the jwt subject field passed by the client.
+ CreatorId int
+
+ // Related fields
+ ProjectId int
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ Description string `jsonapi:"attr,description"`
+ URL string `jsonapi:"attr,url"`
+ ActivityList []string `jsonapi:"attr,activityList"`
+}
+
+type ProjectHookFind struct {
+ ID *int
+
+ // Related fields
+ ProjectId *int
+ ActivityType *ActivityType
+}
+
+func (find *ProjectHookFind) String() string {
+ str, err := json.Marshal(*find)
+ if err != nil {
+ return err.Error()
+ }
+ return string(str)
+}
+
+type ProjectHookPatch struct {
+ ID int
+
+ // Standard fields
+ // Value is assigned from the jwt subject field passed by the client.
+ UpdaterId int
+
+ // Domain specific fields
+ Name *string `jsonapi:"attr,name"`
+ Description *string `jsonapi:"attr,description"`
+ URL *string `jsonapi:"attr,url"`
+ ActivityList *[]string `jsonapi:"attr,activityList"`
+}
+
+type ProjectHookDelete struct {
+ ID int
+
+ // Standard fields
+ // Value is assigned from the jwt subject field passed by the client.
+ DeleterId int
+}
+
+type ProjectHookService interface {
+ CreateProjectHook(ctx context.Context, create *ProjectHookCreate) (*ProjectHook, error)
+ FindProjectHookList(ctx context.Context, find *ProjectHookFind) ([]*ProjectHook, error)
+ FindProjectHook(ctx context.Context, find *ProjectHookFind) (*ProjectHook, error)
+ PatchProjectHook(ctx context.Context, patch *ProjectHookPatch) (*ProjectHook, error)
+ DeleteProjectHook(ctx context.Context, delete *ProjectHookDelete) error
+}
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index eac9e4e426..b33a72c5ac 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -53,9 +53,11 @@ ________________________________________________________________________________
// -----------------------------------Command Line Config BEGIN------------------------------------
var (
// Used for flags.
- host string
- port int
- dataDir string
+ host string
+ port int
+ frontendHost string
+ frontendPort int
+ dataDir string
// When we are running in readonly mode:
// - The data file will be opened in readonly mode, no applicable migration or seeding will be applied.
// - Requests other than GET will be rejected
@@ -93,6 +95,13 @@ var (
os.Exit(1)
}
+ if frontendHost == "" {
+ frontendHost = host
+ }
+ if frontendPort == 0 {
+ frontendPort = port
+ }
+
start()
fmt.Print(BYE_BANNER)
@@ -106,8 +115,10 @@ func Execute() error {
}
func init() {
- rootCmd.PersistentFlags().StringVar(&host, "host", "http://localhost", "host where Bytebase is accessed from, must start with http:// or https://. This is used by Bytebase to create the webhook callback endpoint for VCS integration")
- rootCmd.PersistentFlags().IntVar(&port, "port", 80, "port where Bytebase is accessed from. This is also used by Bytebase to create the webhook callback endpoint for VCS integration")
+ rootCmd.PersistentFlags().StringVar(&host, "host", "http://localhost", "host where Bytebase backend is accessed from, must start with http:// or https://. This is used by Bytebase to create the webhook callback endpoint for VCS integration")
+ rootCmd.PersistentFlags().IntVar(&port, "port", 80, "port where Bytebase backend is accessed from. This is also used by Bytebase to create the webhook callback endpoint for VCS integration")
+ rootCmd.PersistentFlags().StringVar(&frontendHost, "frontend-host", "", "host where Bytebase frontend is accessed from, must start with http:// or https://. This is used by Bytebase to compose the frontend link when posting the webhook event. Default is the same as --host")
+ rootCmd.PersistentFlags().IntVar(&frontendPort, "frontend-port", 0, "port where Bytebase frontend is accessed from. This is used by Bytebase to compose the frontend link when posting the webhook event. Default is the same as --port")
rootCmd.PersistentFlags().StringVar(&dataDir, "data", ".", "directory where Bytebase stores data. If relative path is supplied, then the path is relative to the directory where bytebase is under")
rootCmd.PersistentFlags().BoolVar(&readonly, "readonly", false, "whether to run in read-only mode")
rootCmd.PersistentFlags().BoolVar(&demo, "demo", false, "whether to run using demo data")
@@ -204,8 +215,8 @@ func newMain() *main {
fmt.Println("-----Config BEGIN-----")
fmt.Printf("mode=%s\n", activeProfile.mode)
- fmt.Printf("host=%s\n", host)
- fmt.Printf("port=%d\n", port)
+ fmt.Printf("server=%s:%d\n", host, port)
+ fmt.Printf("frontend=%s:%d\n", frontendHost, frontendPort)
fmt.Printf("dsn=%s\n", activeProfile.dsn)
fmt.Printf("seedDir=%s\n", activeProfile.seedDir)
fmt.Printf("readonly=%t\n", readonly)
@@ -265,12 +276,13 @@ func (m *main) Run() error {
m.db = db
- server := server.NewServer(m.l, version, host, port, m.profile.mode, config.secret, readonly, demo, debug)
+ server := server.NewServer(m.l, version, host, port, frontendHost, frontendPort, m.profile.mode, config.secret, readonly, demo, debug)
server.SettingService = settingService
server.PrincipalService = store.NewPrincipalService(m.l, db, server.CacheService)
server.MemberService = store.NewMemberService(m.l, db, server.CacheService)
server.ProjectService = store.NewProjectService(m.l, db, server.CacheService)
server.ProjectMemberService = store.NewProjectMemberService(m.l, db)
+ server.ProjectHookService = store.NewProjectHookService(m.l, db)
server.EnvironmentService = store.NewEnvironmentService(m.l, db, server.CacheService)
server.DataSourceService = store.NewDataSourceService(m.l, db)
server.DatabaseService = store.NewDatabaseService(m.l, db, server.CacheService)
diff --git a/go.mod b/go.mod
index e4a8509fe4..3bb5929b04 100644
--- a/go.mod
+++ b/go.mod
@@ -10,6 +10,7 @@ require (
github.com/golang/snappy v0.0.4 // indirect
github.com/google/jsonapi v1.0.0
github.com/google/uuid v1.3.0
+ github.com/gosimple/slug v1.10.0 // indirect
github.com/labstack/echo/v4 v4.2.2
github.com/lib/pq v1.10.2
github.com/mattn/go-sqlite3 v1.14.7
diff --git a/go.sum b/go.sum
index feaaa5294a..db41c0da2e 100644
--- a/go.sum
+++ b/go.sum
@@ -159,6 +159,10 @@ github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
+github.com/gosimple/slug v1.10.0 h1:3XbiQua1IpCdrvuntWvGBxVm+K99wCSxJjlxkP49GGQ=
+github.com/gosimple/slug v1.10.0/go.mod h1:MICb3w495l9KNdZm+Xn5b6T2Hn831f9DMxiJ1r+bAjw=
+github.com/gosimple/unidecode v1.0.0 h1:kPdvM+qy0tnk4/BrnkrbdJ82xe88xn7c9hcaipDz4dQ=
+github.com/gosimple/unidecode v1.0.0/go.mod h1:CP0Cr1Y1kogOtx0bJblKzsVWrqYaqfNOnHzpgWw4Awc=
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q=
github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8=
diff --git a/plugin/webhook/dingtalk.go b/plugin/webhook/dingtalk.go
new file mode 100644
index 0000000000..fb26fbf8a3
--- /dev/null
+++ b/plugin/webhook/dingtalk.go
@@ -0,0 +1,65 @@
+package webhook
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+)
+
+type DingTalkWebhookMarkdown struct {
+ Title string `json:"title"`
+ Text string `json:"text"`
+}
+
+type DingTalkWebhook struct {
+ MessageType string `json:"msgtype"`
+ Markdown DingTalkWebhookMarkdown `json:"markdown"`
+}
+
+func init() {
+ register("oapi.dingtalk.com", &DingTalkReceiver{})
+}
+
+type DingTalkReceiver struct {
+}
+
+func (receiver *DingTalkReceiver) post(url string, title string, description string, metaList []WebHookMeta, link string) error {
+ metaStrList := []string{}
+ for _, meta := range metaList {
+ metaStrList = append(metaStrList, fmt.Sprintf("##### **%s:** %s", meta.Name, meta.Value))
+ }
+ text := fmt.Sprintf("# %s\n%s\n##### [View in Bytebase](%s)", title, strings.Join(metaStrList, "\n"), link)
+ if description != "" {
+ text = fmt.Sprintf("# %s\n> %s\n%s\n##### [View in Bytebase](%s)", title, description, strings.Join(metaStrList, "\n"), link)
+ }
+
+ post := DingTalkWebhook{
+ MessageType: "markdown",
+ Markdown: DingTalkWebhookMarkdown{
+ Title: title,
+ Text: text,
+ },
+ }
+ body, err := json.Marshal(post)
+ if err != nil {
+ return fmt.Errorf("failed to marshal webhook POST request: %v", url)
+ }
+ req, err := http.NewRequest("POST",
+ url, bytes.NewBuffer(body))
+ if err != nil {
+ return fmt.Errorf("failed to construct webhook POST request %v (%w)", url, err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ client := &http.Client{
+ Timeout: timeout,
+ }
+ _, err = client.Do(req)
+ if err != nil {
+ return fmt.Errorf("failed to POST webhook %v (%w)", url, err)
+ }
+
+ return nil
+}
diff --git a/plugin/webhook/discord.go b/plugin/webhook/discord.go
new file mode 100644
index 0000000000..25959530ff
--- /dev/null
+++ b/plugin/webhook/discord.go
@@ -0,0 +1,73 @@
+package webhook
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+)
+
+type DiscordWebhookEmbedField struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+}
+
+type DiscordWebhookEmbed struct {
+ Title string `json:"title"`
+ Type string `json:"type"`
+ Description string `json:"description,omitempty"`
+ URL string `json:"url,omitempty"`
+ FieldList []DiscordWebhookEmbedField `json:"fields,omitempty"`
+}
+
+type DiscordWebhook struct {
+ EmbedList []DiscordWebhookEmbed `json:"embeds"`
+}
+
+func init() {
+ register("discord.com", &DiscordReceiver{})
+}
+
+type DiscordReceiver struct {
+}
+
+func (receiver *DiscordReceiver) post(url string, title string, description string, metaList []WebHookMeta, link string) error {
+ embedList := []DiscordWebhookEmbed{}
+
+ fieldList := []DiscordWebhookEmbedField{}
+ for _, meta := range metaList {
+ fieldList = append(fieldList, DiscordWebhookEmbedField(meta))
+ }
+
+ embedList = append(embedList, DiscordWebhookEmbed{
+ Title: title,
+ Type: "rich",
+ Description: description,
+ URL: link,
+ FieldList: fieldList,
+ })
+
+ post := DiscordWebhook{
+ EmbedList: embedList,
+ }
+ body, err := json.Marshal(post)
+ if err != nil {
+ return fmt.Errorf("failed to marshal webhook POST request: %v", url)
+ }
+ req, err := http.NewRequest("POST",
+ url, bytes.NewBuffer(body))
+ if err != nil {
+ return fmt.Errorf("failed to construct webhook POST request %v (%w)", url, err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ client := &http.Client{
+ Timeout: timeout,
+ }
+ _, err = client.Do(req)
+ if err != nil {
+ return fmt.Errorf("failed to POST webhook %+v (%w)", url, err)
+ }
+
+ return nil
+}
diff --git a/plugin/webhook/feishu.go b/plugin/webhook/feishu.go
new file mode 100644
index 0000000000..66ca3fa0cf
--- /dev/null
+++ b/plugin/webhook/feishu.go
@@ -0,0 +1,111 @@
+package webhook
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+)
+
+type FeishuWebhookPostSection struct {
+ Tag string `json:"tag"`
+ Text string `json:"text"`
+ Href string `json:"href,omitempty"`
+}
+
+type FeishuWebhookPostLine struct {
+ SectionList []FeishuWebhookPostSection `json:""`
+}
+
+type FeishuWebhookPost struct {
+ Title string `json:"title"`
+ ContentList [][]FeishuWebhookPostSection `json:"content"`
+}
+
+type FeishuWebhookPostLanguage struct {
+ English FeishuWebhookPost `json:"en_us"`
+}
+
+type FeishuWebhookContent struct {
+ Post FeishuWebhookPostLanguage `json:"post"`
+}
+
+type FeishuWebhook struct {
+ MessageType string `json:"msg_type"`
+ Content FeishuWebhookContent `json:"content"`
+}
+
+func init() {
+ register("open.feishu.cn", &FeishuReceiver{})
+}
+
+type FeishuReceiver struct {
+}
+
+func (receiver *FeishuReceiver) post(url string, title string, description string, metaList []WebHookMeta, link string) error {
+ contentList := [][]FeishuWebhookPostSection{}
+ if description != "" {
+ sectionList := []FeishuWebhookPostSection{}
+ sectionList = append(sectionList, FeishuWebhookPostSection{
+ Tag: "text",
+ Text: description,
+ })
+ contentList = append(contentList, sectionList)
+
+ sectionList = []FeishuWebhookPostSection{}
+ sectionList = append(sectionList, FeishuWebhookPostSection{
+ Tag: "text",
+ Text: "",
+ })
+ contentList = append(contentList, sectionList)
+ }
+
+ for _, meta := range metaList {
+ sectionList := []FeishuWebhookPostSection{}
+ sectionList = append(sectionList, FeishuWebhookPostSection{
+ Tag: "text",
+ Text: fmt.Sprintf("%s: %s", meta.Name, meta.Value),
+ })
+ contentList = append(contentList, sectionList)
+ }
+
+ sectionList := []FeishuWebhookPostSection{}
+ sectionList = append(sectionList, FeishuWebhookPostSection{
+ Tag: "a",
+ Text: "View in Bytebase",
+ Href: link,
+ })
+ contentList = append(contentList, sectionList)
+
+ post := FeishuWebhook{
+ MessageType: "post",
+ Content: FeishuWebhookContent{
+ Post: FeishuWebhookPostLanguage{
+ English: FeishuWebhookPost{
+ Title: title,
+ ContentList: contentList,
+ },
+ },
+ },
+ }
+ body, err := json.Marshal(post)
+ if err != nil {
+ return fmt.Errorf("failed to marshal webhook POST request: %v", url)
+ }
+ req, err := http.NewRequest("POST",
+ url, bytes.NewBuffer(body))
+ if err != nil {
+ return fmt.Errorf("failed to construct webhook POST request %v (%w)", url, err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ client := &http.Client{
+ Timeout: timeout,
+ }
+ _, err = client.Do(req)
+ if err != nil {
+ return fmt.Errorf("failed to POST webhook %+v (%w)", url, err)
+ }
+
+ return nil
+}
diff --git a/plugin/webhook/slack.go b/plugin/webhook/slack.go
new file mode 100644
index 0000000000..442a89fab1
--- /dev/null
+++ b/plugin/webhook/slack.go
@@ -0,0 +1,94 @@
+package webhook
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+)
+
+type SlackWebhookBlockText struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+}
+
+type SlackWebhookBlock struct {
+ Type string `json:"type"`
+ Text SlackWebhookBlockText `json:"text"`
+}
+
+type SlackWebhook struct {
+ Text string `json:"text"`
+ BlockList []SlackWebhookBlock `json:"blocks"`
+}
+
+func init() {
+ register("hooks.slack.com", &SlackReceiver{})
+}
+
+type SlackReceiver struct {
+}
+
+func (receiver *SlackReceiver) post(url string, title string, description string, metaList []WebHookMeta, link string) error {
+ blockList := []SlackWebhookBlock{}
+ blockList = append(blockList, SlackWebhookBlock{
+ Type: "section",
+ Text: SlackWebhookBlockText{
+ Type: "mrkdwn",
+ Text: fmt.Sprintf("*%s*", title),
+ },
+ })
+
+ if description != "" {
+ blockList = append(blockList, SlackWebhookBlock{
+ Type: "section",
+ Text: SlackWebhookBlockText{
+ Type: "mrkdwn",
+ Text: fmt.Sprintf("```%s```", description),
+ },
+ })
+ }
+
+ for _, meta := range metaList {
+ blockList = append(blockList, SlackWebhookBlock{
+ Type: "section",
+ Text: SlackWebhookBlockText{
+ Type: "mrkdwn",
+ Text: fmt.Sprintf("*%s:* %s", meta.Name, meta.Value),
+ },
+ })
+ }
+
+ blockList = append(blockList, SlackWebhookBlock{
+ Type: "section",
+ Text: SlackWebhookBlockText{
+ Type: "mrkdwn",
+ Text: fmt.Sprintf("<%s|View in Bytebase>", link),
+ },
+ })
+
+ post := SlackWebhook{
+ Text: title,
+ BlockList: blockList,
+ }
+ body, err := json.Marshal(post)
+ if err != nil {
+ return fmt.Errorf("failed to marshal webhook POST request: %v", url)
+ }
+ req, err := http.NewRequest("POST",
+ url, bytes.NewBuffer(body))
+ if err != nil {
+ return fmt.Errorf("failed to construct webhook POST request %v (%w)", url, err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ client := &http.Client{
+ Timeout: timeout,
+ }
+ _, err = client.Do(req)
+ if err != nil {
+ return fmt.Errorf("failed to POST webhook %+v (%w)", url, err)
+ }
+
+ return nil
+}
diff --git a/plugin/webhook/teams.go b/plugin/webhook/teams.go
new file mode 100644
index 0000000000..7d2a8b57ab
--- /dev/null
+++ b/plugin/webhook/teams.go
@@ -0,0 +1,101 @@
+package webhook
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+)
+
+var THEME_COLOR = "4f46e5"
+
+type TeamsWebhookActionTarget struct {
+ OS string `json:"os"`
+ URI string `json:"uri"`
+}
+
+type TeamsWebhookAction struct {
+ Type string `json:"@type"`
+ Name string `json:"name"`
+ TargetList []TeamsWebhookActionTarget `json:"targets"`
+}
+
+type TeamsWebhookSectionFact struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+}
+
+type TeamsWebhookSection struct {
+ FactList []TeamsWebhookSectionFact `json:"facts"`
+ Text string `json:"text"`
+}
+
+type TeamsWebhook struct {
+ Type string `json:"@type"`
+ Context string `json:"@context"`
+ Summary string `json:"summary"`
+ ThemeColor string `json:"themeColor"`
+ Title string `json:"title"`
+ SectionList []TeamsWebhookSection `json:"sections"`
+ ActionList []TeamsWebhookAction `json:"potentialAction"`
+}
+
+func init() {
+ register("webhook.office.com", &TeamsReceiver{})
+}
+
+type TeamsReceiver struct {
+}
+
+func (receiver *TeamsReceiver) post(url string, title string, description string, metaList []WebHookMeta, link string) error {
+ factList := []TeamsWebhookSectionFact{}
+ for _, meta := range metaList {
+ factList = append(factList, TeamsWebhookSectionFact(meta))
+ }
+
+ post := TeamsWebhook{
+ Type: "MessageCard",
+ Context: "https://schema.org/extensions",
+ Summary: title,
+ ThemeColor: THEME_COLOR,
+ Title: title,
+ SectionList: []TeamsWebhookSection{
+ {
+ FactList: factList,
+ Text: description,
+ },
+ },
+ ActionList: []TeamsWebhookAction{
+ {
+ Type: "OpenUri",
+ Name: "View in Bytebase",
+ TargetList: []TeamsWebhookActionTarget{
+ {
+ OS: "default",
+ URI: link,
+ },
+ },
+ },
+ },
+ }
+ body, err := json.Marshal(post)
+ if err != nil {
+ return fmt.Errorf("failed to marshal webhook POST request: %v", url)
+ }
+ req, err := http.NewRequest("POST",
+ url, bytes.NewBuffer(body))
+ if err != nil {
+ return fmt.Errorf("failed to construct webhook POST request %v (%w)", url, err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ client := &http.Client{
+ Timeout: timeout,
+ }
+ _, err = client.Do(req)
+ if err != nil {
+ return fmt.Errorf("failed to POST webhook %+v (%w)", url, err)
+ }
+
+ return nil
+}
diff --git a/plugin/webhook/webhook.go b/plugin/webhook/webhook.go
new file mode 100644
index 0000000000..f0f823a5e4
--- /dev/null
+++ b/plugin/webhook/webhook.go
@@ -0,0 +1,63 @@
+package webhook
+
+import (
+ "fmt"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+)
+
+var (
+ receiverMu sync.RWMutex
+ receivers = make(map[string]WebhookReceiver)
+ timeout = 1 * time.Second
+)
+
+type WebHookMeta struct {
+ Name string
+ Value string
+}
+
+type WebhookReceiver interface {
+ post(url string, title string, description string, metaList []WebHookMeta, link string) error
+}
+
+// Register makes a receiver available by the url host
+// If Register is called twice with the same url host or if receiver is nil,
+// it panics.
+func register(host string, r WebhookReceiver) {
+ receiverMu.Lock()
+ defer receiverMu.Unlock()
+ if r == nil {
+ panic("webhook: Register receiver is nil")
+ }
+ if _, dup := receivers[host]; dup {
+ panic("webhook: Register called twice for host " + host)
+ }
+ receivers[host] = r
+}
+
+func Post(urlstr string, title string, description string, metaList []WebHookMeta, link string) error {
+ u, err := url.Parse(urlstr)
+ if err != nil {
+ return fmt.Errorf("webhook: invalid url: %v", urlstr)
+ }
+
+ receiverMu.RLock()
+ var r WebhookReceiver
+ for key, value := range receivers {
+ // Microsfot Teams webhook host is like https://xxx.webhook.office.com where xxx is the team.
+ // So we use contains instead of exact match
+ if strings.Contains(u.Host, key) {
+ r = value
+ break
+ }
+ }
+ receiverMu.RUnlock()
+ if r == nil {
+ return fmt.Errorf("webhook: no applicable receiver for host: %v", u.Host)
+ }
+
+ return r.post(urlstr, title, description, metaList, link)
+}
diff --git a/plugin/webhook/wecom.go b/plugin/webhook/wecom.go
new file mode 100644
index 0000000000..35dbb0a897
--- /dev/null
+++ b/plugin/webhook/wecom.go
@@ -0,0 +1,64 @@
+package webhook
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+)
+
+type WeComWebhookMarkdown struct {
+ Content string `json:"content"`
+}
+
+type WeComWebhook struct {
+ MessageType string `json:"msgtype"`
+ Markdown WeComWebhookMarkdown `json:"markdown"`
+}
+
+func init() {
+ register("qyapi.weixin.qq.com", &WeComReceiver{})
+}
+
+type WeComReceiver struct {
+}
+
+func (receiver *WeComReceiver) post(url string, title string, description string, metaList []WebHookMeta, link string) error {
+ metaStrList := []string{}
+ for _, meta := range metaList {
+ metaStrList = append(metaStrList, fmt.Sprintf("%s: <font color=\"comment\">%s</font>", meta.Name, meta.Value))
+ }
+
+ content := fmt.Sprintf("# %s\n\n%s\n[View in Bytebase](%s)", title, strings.Join(metaStrList, "\n"), link)
+ if description != "" {
+ content = fmt.Sprintf("# %s\n> %s\n\n%s\n[View in Bytebase](%s)", title, description, strings.Join(metaStrList, "\n"), link)
+ }
+
+ post := WeComWebhook{
+ MessageType: "markdown",
+ Markdown: WeComWebhookMarkdown{
+ Content: content,
+ },
+ }
+ body, err := json.Marshal(post)
+ if err != nil {
+ return fmt.Errorf("failed to marshal webhook POST request: %v", url)
+ }
+ req, err := http.NewRequest("POST",
+ url, bytes.NewBuffer(body))
+ if err != nil {
+ return fmt.Errorf("failed to construct webhook POST request %v (%w)", url, err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ client := &http.Client{
+ Timeout: timeout,
+ }
+ _, err = client.Do(req)
+ if err != nil {
+ return fmt.Errorf("failed to POST webhook %v (%w)", url, err)
+ }
+
+ return nil
+}
diff --git a/server/issue.go b/server/issue.go
index b4756942fa..badc474968 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -10,8 +10,10 @@ import (
"github.com/bytebase/bytebase"
"github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/plugin/webhook"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
+ "go.uber.org/zap"
)
func (s *Server) registerIssueRoutes(g *echo.Group) {
@@ -502,6 +504,75 @@ func (s *Server) ChangeIssueStatus(ctx context.Context, issue *api.Issue, newSta
return nil, err
}
+ hookFind := &api.ProjectHookFind{
+ ProjectId: &issue.ProjectId,
+ ActivityType: &activityCreate.Type,
+ }
+ hookList, err := s.ProjectHookService.FindProjectHookList(context.Background(), hookFind)
+ if err != nil {
+ return nil, fmt.Errorf("failed to find project webhook hook after changing the issue status: %v, error: %w", issue.Name, err)
+ }
+
+ // If we need to post webhook event, then we need to make sure the project info exists since we will include
+ // the project name in the webhook event.
+ if len(hookList) > 0 {
+ if issue.Project == nil {
+ projectFind := &api.ProjectFind{
+ ID: &issue.ProjectId,
+ }
+ issue.Project, err = s.ProjectService.FindProject(ctx, projectFind)
+ if err != nil {
+ return nil, fmt.Errorf("failed to find project for posting webhook event after changing the issue status: %v, error: %w", issue.Name, err)
+ }
+ }
+
+ principalFind := &api.PrincipalFind{
+ ID: &updatorId,
+ }
+ updater, err := s.PrincipalService.FindPrincipal(context.Background(), principalFind)
+ if err != nil {
+ return nil, fmt.Errorf("failed to find updater for posting webhook event after changing the issue status: %v, error: %w", issue.Name, err)
+ }
+
+ for _, hook := range hookList {
+ s.l.Info(fmt.Sprintf("hook name: %s, %s", hook.Name, hook.URL))
+ title := ""
+ switch newStatus {
+ case "OPEN":
+ title = fmt.Sprintf("Issue reopened - %s", issue.Name)
+ case "DONE":
+ title = fmt.Sprintf("Issue resolved - %s", issue.Name)
+ case "CANCELED":
+ title = fmt.Sprintf("Issue canceled - %s", issue.Name)
+ }
+
+ err := webhook.Post(
+ hook.URL,
+ title,
+ comment,
+ []webhook.WebHookMeta{
+ {
+ Name: "Project",
+ Value: issue.Project.Name,
+ },
+ {
+ Name: "By",
+ Value: updater.Name,
+ },
+ },
+ fmt.Sprintf("%s:%d/issue/%s", s.frontendHost, s.frontendPort, api.IssueSlug(issue)),
+ )
+ if err != nil {
+ // The external webhook endpoint might be invalid which is out of our code control, so we just emit a warning
+ s.l.Warn("Failed to post webhook event after changing the issue status",
+ zap.String("issue_name", issue.Name),
+ zap.String("old_status", string(issue.Status)),
+ zap.String("new_status", string(newStatus)),
+ zap.Error(err))
+ }
+ }
+ }
+
return updatedIssue, nil
}
diff --git a/server/server.go b/server/server.go
index ed3f195e47..5343d18477 100644
--- a/server/server.go
+++ b/server/server.go
@@ -29,6 +29,7 @@ type Server struct {
MemberService api.MemberService
ProjectService api.ProjectService
ProjectMemberService api.ProjectMemberService
+ ProjectHookService api.ProjectHookService
EnvironmentService api.EnvironmentService
InstanceService api.InstanceService
InstanceUserService api.InstanceUserService
@@ -51,16 +52,18 @@ type Server struct {
e *echo.Echo
- l *zap.Logger
- version string
- mode string
- host string
- port int
- startedTs int64
- secret string
- readonly bool
- demo bool
- plan api.PlanType
+ l *zap.Logger
+ version string
+ mode string
+ host string
+ port int
+ frontendHost string
+ frontendPort int
+ startedTs int64
+ secret string
+ readonly bool
+ demo bool
+ plan api.PlanType
}
//go:embed acl_casbin_model.conf
@@ -75,7 +78,7 @@ var casbinDBAPolicy string
//go:embed acl_casbin_policy_developer.csv
var casbinDeveloperPolicy string
-func NewServer(logger *zap.Logger, version string, host string, port int, mode string, secret string, readonly bool, demo bool, debug bool) *Server {
+func NewServer(logger *zap.Logger, version string, host string, port int, frontendHost string, frontendPort int, mode string, secret string, readonly bool, demo bool, debug bool) *Server {
e := echo.New()
e.HideBanner = true
e.HidePort = true
@@ -90,6 +93,8 @@ func NewServer(logger *zap.Logger, version string, host string, port int, mode s
mode: mode,
host: host,
port: port,
+ frontendHost: frontendHost,
+ frontendPort: frontendPort,
startedTs: time.Now().Unix(),
secret: secret,
readonly: readonly,
diff --git a/store/migration/10001__init_schema.sql b/store/migration/10001__init_schema.sql
index 8a4fffc448..2a415b8cce 100644
--- a/store/migration/10001__init_schema.sql
+++ b/store/migration/10001__init_schema.sql
@@ -256,6 +256,45 @@ WHERE
END;
+-- Project Hook
+CREATE TABLE project_hook (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ row_status TEXT NOT NULL CHECK (
+ row_status IN ('NORMAL', 'ARCHIVED', 'PENDING_DELETE')
+ ) DEFAULT 'NORMAL',
+ creator_id INTEGER NOT NULL REFERENCES principal (id),
+ created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ updater_id INTEGER NOT NULL REFERENCES principal (id),
+ updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ project_id INTEGER NOT NULL REFERENCES project (id),
+ name TEXT NOT NULL,
+ description TEXT NOT NULL DEFAULT '',
+ url TEXT NOT NULL,
+ -- Comma separated list of activity triggers.
+ activity_list TEXT NOT NULL,
+ UNIQUE(project_id, url)
+);
+
+CREATE INDEX idx_project_hook_project_id ON project_hook(project_id);
+
+INSERT INTO
+ sqlite_sequence (name, seq)
+VALUES
+ ('project_hook', 100);
+
+CREATE TRIGGER IF NOT EXISTS `trigger_update_project_hook_modification_time`
+AFTER
+UPDATE
+ ON `project_hook` FOR EACH ROW BEGIN
+UPDATE
+ `project_hook`
+SET
+ updated_ts = (strftime('%s', 'now'))
+WHERE
+ rowid = old.rowid;
+
+END;
+
-- Instance
CREATE TABLE instance (
id INTEGER PRIMARY KEY AUTOINCREMENT,
diff --git a/store/project_hook.go b/store/project_hook.go
new file mode 100644
index 0000000000..ca36b04cc3
--- /dev/null
+++ b/store/project_hook.go
@@ -0,0 +1,322 @@
+package store
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase"
+ "github.com/bytebase/bytebase/api"
+ "go.uber.org/zap"
+)
+
+var (
+ _ api.ProjectHookService = (*ProjectHookService)(nil)
+)
+
+// ProjectHookService represents a service for managing projectHook.
+type ProjectHookService struct {
+ l *zap.Logger
+ db *DB
+}
+
+// NewProjectHookService returns a new instance of ProjectHookService.
+func NewProjectHookService(logger *zap.Logger, db *DB) *ProjectHookService {
+ return &ProjectHookService{l: logger, db: db}
+}
+
+// CreateProjectHook creates a new projectHook.
+func (s *ProjectHookService) CreateProjectHook(ctx context.Context, create *api.ProjectHookCreate) (*api.ProjectHook, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ projectHook, err := createProjectHook(ctx, tx, create)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return projectHook, nil
+}
+
+// FindProjectHookList retrieves a list of projectHooks based on find.
+func (s *ProjectHookService) FindProjectHookList(ctx context.Context, find *api.ProjectHookFind) ([]*api.ProjectHook, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := findProjectHookList(ctx, tx, find)
+ if err != nil {
+ return []*api.ProjectHook{}, err
+ }
+
+ return list, nil
+}
+
+// FindProjectHook retrieves a single projectHook based on find.
+// Returns ENOTFOUND if no matching record.
+// Returns ECONFLICT if finding more than 1 matching records.
+func (s *ProjectHookService) FindProjectHook(ctx context.Context, find *api.ProjectHookFind) (*api.ProjectHook, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := findProjectHookList(ctx, tx, find)
+ if err != nil {
+ return nil, err
+ } else if len(list) == 0 {
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("project hook not found: %+v", find)}
+ } else if len(list) > 1 {
+ return nil, &bytebase.Error{Code: bytebase.ECONFLICT, Message: fmt.Sprintf("found %d project hooks with filter %+v, expect 1", len(list), find)}
+ }
+ return list[0], nil
+}
+
+// PatchProjectHook updates an existing projectHook by ID.
+// Returns ENOTFOUND if projectHook does not exist.
+func (s *ProjectHookService) PatchProjectHook(ctx context.Context, patch *api.ProjectHookPatch) (*api.ProjectHook, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ projectHook, err := patchProjectHook(ctx, tx, patch)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return projectHook, nil
+}
+
+// DeleteProjectHook deletes an existing projectHook by ID.
+// Returns ENOTFOUND if projectHook does not exist.
+func (s *ProjectHookService) DeleteProjectHook(ctx context.Context, delete *api.ProjectHookDelete) error {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return FormatError(err)
+ }
+ defer tx.Rollback()
+
+ err = deleteProjectHook(ctx, tx, delete)
+ if err != nil {
+ return FormatError(err)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return FormatError(err)
+ }
+
+ return nil
+}
+
+// createProjectHook creates a new projectHook.
+func createProjectHook(ctx context.Context, tx *Tx, create *api.ProjectHookCreate) (*api.ProjectHook, error) {
+ // Insert row into database.
+ row, err := tx.QueryContext(ctx, `
+ INSERT INTO project_hook (
+ creator_id,
+ updater_id,
+ project_id,
+ name,
+ description,
+ url,
+ activity_list
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, project_id, name, description, url, activity_list
+ `,
+ create.CreatorId,
+ create.CreatorId,
+ create.ProjectId,
+ create.Name,
+ create.Description,
+ create.URL,
+ strings.Join(create.ActivityList, ","),
+ )
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ row.Next()
+ var projectHook api.ProjectHook
+ var activityList string
+ if err := row.Scan(
+ &projectHook.ID,
+ &projectHook.CreatorId,
+ &projectHook.CreatedTs,
+ &projectHook.UpdaterId,
+ &projectHook.UpdatedTs,
+ &projectHook.ProjectId,
+ &projectHook.Name,
+ &projectHook.Description,
+ &projectHook.URL,
+ &activityList,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+ projectHook.ActivityList = strings.Split(activityList, ",")
+
+ return &projectHook, nil
+}
+
+func findProjectHookList(ctx context.Context, tx *Tx, find *api.ProjectHookFind) (_ []*api.ProjectHook, err error) {
+ // Build WHERE clause.
+ where, args := []string{"1 = 1"}, []interface{}{}
+ if v := find.ID; v != nil {
+ where, args = append(where, "id = ?"), append(args, *v)
+ }
+ if v := find.ProjectId; v != nil {
+ where, args = append(where, "project_id = ?"), append(args, *v)
+ }
+
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ id,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ project_id,
+ name,
+ description,
+ url,
+ activity_list
+ FROM project_hook
+ WHERE `+strings.Join(where, " AND "),
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer rows.Close()
+
+ // Iterate over result set and deserialize rows into list.
+ list := make([]*api.ProjectHook, 0)
+ for rows.Next() {
+ var projectHook api.ProjectHook
+ var activityList string
+ if err := rows.Scan(
+ &projectHook.ID,
+ &projectHook.CreatorId,
+ &projectHook.CreatedTs,
+ &projectHook.UpdaterId,
+ &projectHook.UpdatedTs,
+ &projectHook.ProjectId,
+ &projectHook.Name,
+ &projectHook.Description,
+ &projectHook.URL,
+ &activityList,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+ projectHook.ActivityList = strings.Split(activityList, ",")
+
+ if v := find.ActivityType; v != nil {
+ for _, activity := range projectHook.ActivityList {
+ if api.ActivityType(activity) == *v {
+ list = append(list, &projectHook)
+ break
+ }
+ }
+ } else {
+ list = append(list, &projectHook)
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return list, nil
+}
+
+// patchProjectHook updates a projectHook by ID. Returns the new state of the projectHook after update.
+func patchProjectHook(ctx context.Context, tx *Tx, patch *api.ProjectHookPatch) (*api.ProjectHook, error) {
+ // Build UPDATE clause.
+ set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}
+ if v := patch.Name; v != nil {
+ set, args = append(set, "name = ?"), append(args, *v)
+ }
+ if v := patch.Description; v != nil {
+ set, args = append(set, "description = ?"), append(args, *v)
+ }
+ if v := patch.URL; v != nil {
+ set, args = append(set, "url = ?"), append(args, *v)
+ }
+ if v := patch.ActivityList; v != nil {
+ activityList := strings.Join(*v, ",")
+ set, args = append(set, "activity_list = ?"), append(args, activityList)
+ }
+
+ args = append(args, patch.ID)
+
+ // Execute update query with RETURNING.
+ row, err := tx.QueryContext(ctx, `
+ UPDATE project_hook
+ SET `+strings.Join(set, ", ")+`
+ WHERE id = ?
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, project_id, name, description, url, activity_list
+ `,
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ if row.Next() {
+ var projectHook api.ProjectHook
+ var activityList string
+ if err := row.Scan(
+ &projectHook.ID,
+ &projectHook.CreatorId,
+ &projectHook.CreatedTs,
+ &projectHook.UpdaterId,
+ &projectHook.UpdatedTs,
+ &projectHook.ProjectId,
+ &projectHook.Name,
+ &projectHook.Description,
+ &projectHook.URL,
+ &activityList,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+ projectHook.ActivityList = strings.Split(activityList, ",")
+
+ return &projectHook, nil
+ }
+
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("project hook ID not found: %d", patch.ID)}
+}
+
+// deleteProjectHook permanently deletes a projectHook by ID.
+func deleteProjectHook(ctx context.Context, tx *Tx, delete *api.ProjectHookDelete) error {
+ // Remove row from database.
+ result, err := tx.ExecContext(ctx, `DELETE FROM project_hook WHERE id = ?`, delete.ID)
+ if err != nil {
+ return FormatError(err)
+ }
+
+ rows, _ := result.RowsAffected()
+ if rows == 0 {
+ return &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("project hook ID not found: %d", delete.ID)}
+ }
+
+ return nil
+}
diff --git a/store/seed/test/10000__reset.sql b/store/seed/test/10000__reset.sql
index 1aad83b51d..9f17b05975 100644
--- a/store/seed/test/10000__reset.sql
+++ b/store/seed/test/10000__reset.sql
@@ -68,6 +68,9 @@ DELETE FROM
DELETE FROM
environment;
+DELETE FROM
+ project_hook;
+
DELETE FROM
project_member;