Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: simplify webhook code structure (#18699)
Danny Xuf71713faf8b4
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.goindex e80250914a..b4ba272eac 100644--- a/backend/api/v1/issue_service.go+++ b/backend/api/v1/issue_service.go@@ -430,13 +430,14 @@ func (s *IssueService) createIssueDatabaseChange(ctx context.Context, project *s// Trigger ISSUE_CREATED webhooks.webhookManager.CreateEvent(ctx, &webhook.Event{- Actor: user,Type: storepb.Activity_ISSUE_CREATED,Project: webhook.NewProject(project),- Issue: webhook.NewIssue(issue),IssueCreated: &webhook.EventIssueCreated{- CreatorName: user.Name,- CreatorEmail: user.Email,+ Creator: &webhook.User{+ Name: user.Name,+ Email: user.Email,+ },+ Issue: webhook.NewIssue(issue),},})@@ -509,13 +510,14 @@ func (s *IssueService) createIssueGrantRequest(ctx context.Context, project *sto// Trigger ISSUE_CREATED webhooks.webhookManager.CreateEvent(ctx, &webhook.Event{- Actor: user,Type: storepb.Activity_ISSUE_CREATED,Project: webhook.NewProject(project),- Issue: webhook.NewIssue(issue),IssueCreated: &webhook.EventIssueCreated{- CreatorName: user.Name,- CreatorEmail: user.Email,+ Creator: &webhook.User{+ Name: user.Name,+ Email: user.Email,+ },+ Issue: webhook.NewIssue(issue),},})@@ -577,13 +579,14 @@ func (s *IssueService) createIssueDatabaseDataExport(ctx context.Context, projec// Trigger ISSUE_CREATED webhooks.webhookManager.CreateEvent(ctx, &webhook.Event{- Actor: user,Type: storepb.Activity_ISSUE_CREATED,Project: webhook.NewProject(project),- Issue: webhook.NewIssue(issue),IssueCreated: &webhook.EventIssueCreated{- CreatorName: user.Name,- CreatorEmail: user.Email,+ Creator: &webhook.User{+ Name: user.Name,+ Email: user.Email,+ },+ Issue: webhook.NewIssue(issue),},})@@ -699,16 +702,24 @@ func (s *IssueService) ApproveIssue(ctx context.Context, req *connect.Request[v1return}+ // Get issue creator for webhook event+ creator, err := s.store.GetUserByEmail(ctx, issue.CreatorEmail)+ if err != nil {+ slog.Warn("failed to get issue creator, using system bot", log.BBError(err))+ creator = store.SystemBotUser+ }+// Send ISSUE_APPROVAL_REQUESTED webhooks.webhookManager.CreateEvent(ctx, &webhook.Event{- Actor: user,Type: storepb.Activity_ISSUE_APPROVAL_REQUESTED,- Comment: "",- Issue: webhook.NewIssue(issue),Project: webhook.NewProject(project),ApprovalRequested: &webhook.EventIssueApprovalRequested{- ApprovalRole: role,- Approvers: approvers,+ Creator: &webhook.User{+ Name: creator.Name,+ Email: creator.Email,+ },+ Issue: webhook.NewIssue(issue),+ Approvers: approvers,},})}()@@ -846,17 +857,19 @@ func (s *IssueService) RejectIssue(ctx context.Context, req *connect.Request[v1p// Trigger ISSUE_SENT_BACK webhooks.webhookManager.CreateEvent(ctx, &webhook.Event{- Actor: user,Type: storepb.Activity_ISSUE_SENT_BACK,- Comment: req.Msg.Comment,- Issue: webhook.NewIssue(issue),Project: webhook.NewProject(project),SentBack: &webhook.EventIssueSentBack{- ApproverName: user.Name,- ApproverEmail: user.Email,- CreatorName: creator.Name,- CreatorEmail: creator.Email,- Reason: req.Msg.Comment,+ Approver: &webhook.User{+ Name: user.Name,+ Email: user.Email,+ },+ Creator: &webhook.User{+ Name: creator.Name,+ Email: creator.Email,+ },+ Issue: webhook.NewIssue(issue),+ Reason: req.Msg.Comment,},})@@ -942,16 +955,24 @@ func (s *IssueService) RequestIssue(ctx context.Context, req *connect.Request[v1return}+ // Get issue creator for webhook event+ creator, err := s.store.GetUserByEmail(ctx, issue.CreatorEmail)+ if err != nil {+ slog.Warn("failed to get issue creator, using system bot", log.BBError(err))+ creator = store.SystemBotUser+ }+// Send ISSUE_APPROVAL_REQUESTED webhooks.webhookManager.CreateEvent(ctx, &webhook.Event{- Actor: user,Type: storepb.Activity_ISSUE_APPROVAL_REQUESTED,- Comment: "",- Issue: webhook.NewIssue(issue),Project: webhook.NewProject(project),ApprovalRequested: &webhook.EventIssueApprovalRequested{- ApprovalRole: role,- Approvers: approvers,+ Creator: &webhook.User{+ Name: creator.Name,+ Email: creator.Email,+ },+ Issue: webhook.NewIssue(issue),+ Approvers: approvers,},})}()diff --git a/backend/component/webhook/event.go b/backend/component/webhook/event.goindex bb21cacc88..2967a31c2a 100644--- a/backend/component/webhook/event.go+++ b/backend/component/webhook/event.go@@ -8,20 +8,15 @@ import ()type Event struct {- Actor *store.UserMessage- Type storepb.Activity_Type- Comment string- // nullable- Issue *IssueProject *Project- Rollout *Rollout+ Type storepb.Activity_Type- // Focused event types+ // Focused event types (only one is set)IssueCreated *EventIssueCreatedApprovalRequested *EventIssueApprovalRequestedSentBack *EventIssueSentBack- PipelineFailed *EventPipelineFailed- PipelineCompleted *EventPipelineCompleted+ RolloutFailed *EventRolloutFailed+ RolloutCompleted *EventRolloutCompleted}func NewIssue(i *store.IssueMessage) *Issue {@@ -48,7 +43,8 @@ func NewProject(p *store.ProjectMessage) *Project {func NewRollout(r *store.PlanMessage) *Rollout {return &Rollout{- UID: int(r.UID),+ UID: int(r.UID),+ Title: r.Name,}}@@ -68,30 +64,31 @@ type Project struct {}type Rollout struct {- UID int+ UID int+ Title string}type EventIssueCreated struct {- CreatorName string- CreatorEmail string+ Creator *User+ Issue *Issue}type EventIssueApprovalRequested struct {- ApprovalRole string- Approvers []User+ Creator *User+ Issue *Issue+ Approvers []User}type EventIssueSentBack struct {- ApproverName string- ApproverEmail string- CreatorName string- CreatorEmail string- Reason string+ Approver *User+ Creator *User+ Issue *Issue+ Reason string}-type EventPipelineFailed struct {- FailedTasks []FailedTask- FirstFailureTime time.Time+type EventRolloutFailed struct {+ Rollout *Rollout+ FailedTasks []FailedTask}type FailedTask struct {@@ -103,10 +100,8 @@ type FailedTask struct {FailedAt time.Time}-type EventPipelineCompleted struct {- TotalTasks int- StartedAt time.Time- CompletedAt time.Time+type EventRolloutCompleted struct {+ Rollout *Rollout}type User struct {diff --git a/backend/component/webhook/manager.go b/backend/component/webhook/manager.goindex af389dcf71..e206f2f438 100644--- a/backend/component/webhook/manager.go+++ b/backend/component/webhook/manager.go@@ -38,7 +38,10 @@ func (m *Manager) CreateEvent(ctx context.Context, e *Event) {EventType: &e.Type,})if err != nil {- slog.Warn("failed to find project webhook", "issue_name", e.Issue.Title, log.BBError(err))+ slog.Warn("failed to find project webhook",+ slog.String("project", e.Project.ResourceID),+ slog.String("event_type", e.Type.String()),+ log.BBError(err))return}@@ -49,7 +52,8 @@ func (m *Manager) CreateEvent(ctx context.Context, e *Event) {webhookCtx, err := m.getWebhookContextFromEvent(ctx, e, e.Type)if err != nil {slog.Warn("failed to get webhook context",- slog.String("issue_name", e.Issue.Title),+ slog.String("project", e.Project.ResourceID),+ slog.String("event_type", e.Type.String()),log.BBError(err))return}@@ -73,18 +77,19 @@ func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, eventitle := ""titleZh := ""link := ""- if e.Issue != nil {- // TODO(steven): Remove the slug dependency when the legacy issue page is removed.- link = fmt.Sprintf("%s/projects/%s/issues/%s-%d", externalURL, e.Project.ResourceID, slug.Make(e.Issue.Title), e.Issue.UID)- } else if e.Rollout != nil {- link = fmt.Sprintf("%s/projects/%s/plans/%d/rollout", externalURL, e.Project.ResourceID, e.Rollout.UID)- }+ var actor *User+ var issue *Issue+ var rollout *Rollout+switch e.Type {case storepb.Activity_ISSUE_CREATED:title = "Issue created"titleZh = "创建工单"if e.IssueCreated != nil {- webhookCtx.Description = fmt.Sprintf("%s created issue %s", e.IssueCreated.CreatorName, e.Issue.Title)+ actor = e.IssueCreated.Creator+ issue = e.IssueCreated.Issue+ link = fmt.Sprintf("%s/projects/%s/issues/%s-%d", externalURL, e.Project.ResourceID, slug.Make(issue.Title), issue.UID)+ webhookCtx.Description = fmt.Sprintf("%s created issue %s", actor.Name, issue.Title)}case storepb.Activity_ISSUE_APPROVAL_REQUESTED:@@ -92,7 +97,9 @@ func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, eventitle = "Approval required"titleZh = "需要审批"if e.ApprovalRequested != nil {- webhookCtx.ApprovalRole = e.ApprovalRequested.ApprovalRole+ actor = e.ApprovalRequested.Creator+ issue = e.ApprovalRequested.Issue+ link = fmt.Sprintf("%s/projects/%s/issues/%s-%d", externalURL, e.Project.ResourceID, slug.Make(issue.Title), issue.UID)mentionUsers = make([]*store.UserMessage, 0, len(e.ApprovalRequested.Approvers))for _, user := range e.ApprovalRequested.Approvers {mentionUsers = append(mentionUsers, &store.UserMessage{@@ -107,22 +114,27 @@ func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, eventitle = "Issue sent back"titleZh = "工单被退回"if e.SentBack != nil {- webhookCtx.Description = fmt.Sprintf("%s sent back the issue: %s", e.SentBack.ApproverName, e.SentBack.Reason)+ actor = e.SentBack.Approver+ issue = e.SentBack.Issue+ link = fmt.Sprintf("%s/projects/%s/issues/%s-%d", externalURL, e.Project.ResourceID, slug.Make(issue.Title), issue.UID)+ webhookCtx.Description = fmt.Sprintf("%s sent back the issue: %s", e.SentBack.Approver.Name, e.SentBack.Reason)mentionUsers = []*store.UserMessage{{- Name: e.SentBack.CreatorName,- Email: e.SentBack.CreatorEmail,+ Name: e.SentBack.Creator.Name,+ Email: e.SentBack.Creator.Email,},}}case storepb.Activity_PIPELINE_FAILED:level = webhook.WebhookError- title = "Pipeline failed"- titleZh = "流水线失败"- if e.PipelineFailed != nil {- failedTasks := make([]webhook.FailedTaskInfo, 0, len(e.PipelineFailed.FailedTasks))- for _, task := range e.PipelineFailed.FailedTasks {+ title = "Rollout failed"+ titleZh = "发布失败"+ if e.RolloutFailed != nil {+ rollout = e.RolloutFailed.Rollout+ link = fmt.Sprintf("%s/projects/%s/plans/%d/rollout", externalURL, e.Project.ResourceID, rollout.UID)+ failedTasks := make([]webhook.FailedTaskInfo, 0, len(e.RolloutFailed.FailedTasks))+ for _, task := range e.RolloutFailed.FailedTasks {failedTasks = append(failedTasks, webhook.FailedTaskInfo{Name: task.TaskName,Instance: task.InstanceName,@@ -137,17 +149,12 @@ func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, evencase storepb.Activity_PIPELINE_COMPLETED:level = webhook.WebhookSuccess- title = "Pipeline completed"- titleZh = "流水线完成"- if e.PipelineCompleted != nil {- duration := e.PipelineCompleted.CompletedAt.Sub(e.PipelineCompleted.StartedAt)- webhookCtx.PipelineMetrics = &webhook.PipelineMetrics{- TotalTasks: e.PipelineCompleted.TotalTasks,- StartedAt: e.PipelineCompleted.StartedAt.Format(time.RFC3339),- CompletedAt: e.PipelineCompleted.CompletedAt.Format(time.RFC3339),- DurationSecs: int64(duration.Seconds()),- }- webhookCtx.Description = fmt.Sprintf("Completed %d task(s) in %s", e.PipelineCompleted.TotalTasks, duration.String())+ title = "Rollout completed"+ titleZh = "发布完成"+ if e.RolloutCompleted != nil {+ rollout = e.RolloutCompleted.Rollout+ link = fmt.Sprintf("%s/projects/%s/plans/%d/rollout", externalURL, e.Project.ResourceID, rollout.UID)+ webhookCtx.Description = "Rollout completed successfully"}default:@@ -163,48 +170,54 @@ func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, even}webhookCtx = webhook.Context{- Level: level,- EventType: string(eventType),- Title: title,- TitleZh: titleZh,- Issue: nil,- Rollout: nil,+ Level: level,+ EventType: string(eventType),+ Title: title,+ TitleZh: titleZh,+ Link: link,+ MentionEndUsers: mentionEndUsers,Project: &webhook.Project{Name: common.FormatProject(e.Project.ResourceID),Title: e.Project.Title,},- Description: e.Comment,- Link: link,- ActorID: e.Actor.ID,- ActorName: e.Actor.Name,- ActorEmail: e.Actor.Email,- MentionEndUsers: mentionEndUsers,}- if e.Issue != nil {- creatorName := e.Issue.CreatorEmail- creatorUser, err := m.store.GetUserByEmail(ctx, e.Issue.CreatorEmail)++ // Set actor information if available+ if actor != nil {+ webhookCtx.ActorID = 0 // We don't have ID in User struct+ webhookCtx.ActorName = actor.Name+ webhookCtx.ActorEmail = actor.Email+ }++ // Set issue information if available+ if issue != nil {+ creatorName := issue.Title // Fallback+ creatorUser, err := m.store.GetUserByEmail(ctx, actor.Email)if err != nil {slog.Warn("failed to get creator user for webhook context",- slog.String("issue_name", e.Issue.Title),+ slog.String("issue_title", issue.Title),log.BBError(err))} else {creatorName = creatorUser.Name}webhookCtx.Issue = &webhook.Issue{- ID: e.Issue.UID,- Name: e.Issue.Title,- Status: e.Issue.Status,- Type: e.Issue.Type,- Description: e.Issue.Description,+ ID: issue.UID,+ Name: issue.Title,+ Status: issue.Status,+ Type: issue.Type,+ Description: issue.Description,Creator: webhook.Creator{Name: creatorName,- Email: e.Issue.CreatorEmail,+ Email: actor.Email,},}}- if e.Rollout != nil {++ // Set rollout information if available+ if rollout != nil {webhookCtx.Rollout = &webhook.Rollout{- UID: e.Rollout.UID,+ UID: rollout.UID,+ Title: rollout.Title,}}diff --git a/backend/plugin/webhook/dingtalk/dingtalk.go b/backend/plugin/webhook/dingtalk/dingtalk.goindex bb7e1ba440..e132357a85 100644--- a/backend/plugin/webhook/dingtalk/dingtalk.go+++ b/backend/plugin/webhook/dingtalk/dingtalk.go@@ -231,7 +231,9 @@ func getMarkdownText(context webhook.Context) string {for _, meta := range context.GetMetaListZh() {metaStrList = append(metaStrList, fmt.Sprintf("##### **%s:** %s", meta.Name, meta.Value))}- metaStrList = append(metaStrList, fmt.Sprintf("##### **由:** %s (%s)", context.ActorName, context.ActorEmail))+ if context.ActorName != "" {+ metaStrList = append(metaStrList, fmt.Sprintf("##### **由:** %s (%s)", context.ActorName, context.ActorEmail))+ }text := fmt.Sprintf("# %s\n%s\n##### [在 Bytebase 中显示](%s)", context.TitleZh, strings.Join(metaStrList, "\n"), context.Link)if context.Description != "" {diff --git a/backend/plugin/webhook/discord.go b/backend/plugin/webhook/discord/discord.gosimilarity index 54%rename from backend/plugin/webhook/discord.gorename to backend/plugin/webhook/discord/discord.goindex 33bf93ee0f..e651220b90 100644--- a/backend/plugin/webhook/discord.go+++ b/backend/plugin/webhook/discord/discord.go@@ -1,4 +1,4 @@-package webhook+package discordimport ("bytes"@@ -10,81 +10,85 @@ import ("github.com/pkg/errors"storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/webhook")-// DiscordWebhookResponse is the API message for Discord webhook response.-type DiscordWebhookResponse struct {+// WebhookResponse is the API message for Discord webhook response.+type WebhookResponse struct {Code int `json:"code"`Message string `json:"message"`}-// DiscordWebhookEmbedField is the API message for Discord webhook embed field.-type DiscordWebhookEmbedField struct {+// WebhookEmbedField is the API message for Discord webhook embed field.+type WebhookEmbedField struct {Name string `json:"name"`Value string `json:"value"`}-// DiscordWebhookEmbedAuthor is the API message for Discord webhook embed Author.-type DiscordWebhookEmbedAuthor struct {+// WebhookEmbedAuthor is the API message for Discord webhook embed Author.+type WebhookEmbedAuthor struct {Name string `json:"name"`}-// DiscordWebhookEmbed is the API message for Discord webhook embed.-type DiscordWebhookEmbed struct {- Title string `json:"title"`- Type string `json:"type"`- Description string `json:"description,omitempty"`- URL string `json:"url,omitempty"`- Timestamp string `json:"timestamp"`- Author DiscordWebhookEmbedAuthor `json:"author"`- FieldList []DiscordWebhookEmbedField `json:"fields,omitempty"`+// WebhookEmbed is the API message for Discord webhook embed.+type WebhookEmbed struct {+ Title string `json:"title"`+ Type string `json:"type"`+ Description string `json:"description,omitempty"`+ URL string `json:"url,omitempty"`+ Timestamp string `json:"timestamp"`+ Author *WebhookEmbedAuthor `json:"author,omitempty"`+ FieldList []WebhookEmbedField `json:"fields,omitempty"`}-// DiscordWebhook is the API message for Discord webhook.-type DiscordWebhook struct {- EmbedList []DiscordWebhookEmbed `json:"embeds"`+// Webhook is the API message for Discord webhook.+type Webhook struct {+ EmbedList []WebhookEmbed `json:"embeds"`}func init() {- Register(storepb.WebhookType_DISCORD, &DiscordReceiver{})+ webhook.Register(storepb.WebhookType_DISCORD, &Receiver{})}-// DiscordReceiver is the receiver for Discord.-type DiscordReceiver struct {+// Receiver is the receiver for Discord.+type Receiver struct {}-func (*DiscordReceiver) Post(context Context) error {- embedList := []DiscordWebhookEmbed{}+func (*Receiver) Post(context webhook.Context) error {+ embedList := []WebhookEmbed{}- fieldList := []DiscordWebhookEmbedField{}+ fieldList := []WebhookEmbedField{}for _, meta := range context.GetMetaList() {- fieldList = append(fieldList, DiscordWebhookEmbedField(meta))+ fieldList = append(fieldList, WebhookEmbedField(meta))}status := ""switch context.Level {- case WebhookSuccess:+ case webhook.WebhookSuccess:status = ":white_check_mark: "- case WebhookWarn:+ case webhook.WebhookWarn:status = ":warning: "- case WebhookError:+ case webhook.WebhookError:status = ":exclamation: "default:// No status icon for other levelsstatus = ""}- embedList = append(embedList, DiscordWebhookEmbed{+ embed := WebhookEmbed{Title: fmt.Sprintf("%s%s", status, context.Title),Type: "rich",Description: context.Description,URL: context.Link,- Author: DiscordWebhookEmbedAuthor{+ FieldList: fieldList,+ }+ if context.ActorName != "" {+ embed.Author = &WebhookEmbedAuthor{Name: fmt.Sprintf("%s (%s)", context.ActorName, context.ActorEmail),- },- FieldList: fieldList,- })+ }+ }+ embedList = append(embedList, embed)- post := DiscordWebhook{+ post := Webhook{EmbedList: embedList,}body, err := json.Marshal(post)@@ -99,7 +103,7 @@ func (*DiscordReceiver) Post(context Context) error {req.Header.Set("Content-Type", "application/json")client := &http.Client{- Timeout: Timeout,+ Timeout: webhook.Timeout,}resp, err := client.Do(req)if err != nil {@@ -116,7 +120,7 @@ func (*DiscordReceiver) Post(context Context) error {return errors.Errorf("failed to POST webhook %s, status code: %d, response body: %s", context.URL, resp.StatusCode, b)}- webhookResponse := &DiscordWebhookResponse{}+ webhookResponse := &WebhookResponse{}if err := json.Unmarshal(b, webhookResponse); err != nil {return errors.Wrapf(err, "malformed webhook response from %s", context.URL)}diff --git a/backend/plugin/webhook/feishu/feishu.go b/backend/plugin/webhook/feishu/feishu.goindex 7ade0345c8..44c1bd52b1 100644--- a/backend/plugin/webhook/feishu/feishu.go+++ b/backend/plugin/webhook/feishu/feishu.go@@ -233,7 +233,10 @@ func getMessageCard(context webhook.Context) *WebhookCard {_, _ = markdownBuf.WriteString(fmt.Sprintf("**%s**: %s\n", meta.Name, meta.Value))}- _, _ = markdownBuf.WriteString(fmt.Sprintf("**Actor**: %s (%s)\n[View in Bytebase](%s)", context.ActorName, context.ActorEmail, context.Link))+ if context.ActorName != "" {+ _, _ = markdownBuf.WriteString(fmt.Sprintf("**Actor**: %s (%s)\n", context.ActorName, context.ActorEmail))+ }+ _, _ = markdownBuf.WriteString(fmt.Sprintf("[View in Bytebase](%s)", context.Link))return &WebhookCard{Config: WebhookCardConfig{diff --git a/backend/plugin/webhook/lark/lark.go b/backend/plugin/webhook/lark/lark.goindex da76a64e18..e2b5b760ff 100644--- a/backend/plugin/webhook/lark/lark.go+++ b/backend/plugin/webhook/lark/lark.go@@ -233,7 +233,10 @@ func getMessageCard(context webhook.Context) *WebhookCard {_, _ = markdownBuf.WriteString(fmt.Sprintf("**%s**: %s\n", meta.Name, meta.Value))}- _, _ = markdownBuf.WriteString(fmt.Sprintf("**Actor**: %s (%s)\n[View in Bytebase](%s)", context.ActorName, context.ActorEmail, context.Link))+ if context.ActorName != "" {+ _, _ = markdownBuf.WriteString(fmt.Sprintf("**Actor**: %s (%s)\n", context.ActorName, context.ActorEmail))+ }+ _, _ = markdownBuf.WriteString(fmt.Sprintf("[View in Bytebase](%s)", context.Link))return &WebhookCard{Config: WebhookCardConfig{diff --git a/backend/plugin/webhook/slack/slack.go b/backend/plugin/webhook/slack/slack.goindex dea2bba42b..a82091539c 100644--- a/backend/plugin/webhook/slack/slack.go+++ b/backend/plugin/webhook/slack/slack.go@@ -115,13 +115,15 @@ func GetBlocks(context webhook.Context) []Block {})}- blockList = append(blockList, Block{- Type: "section",- Text: &BlockMarkdown{- Type: "mrkdwn",- Text: fmt.Sprintf("Actor: %s (%s)", context.ActorName, context.ActorEmail),- },- })+ if context.ActorName != "" {+ blockList = append(blockList, Block{+ Type: "section",+ Text: &BlockMarkdown{+ Type: "mrkdwn",+ Text: fmt.Sprintf("Actor: %s (%s)", context.ActorName, context.ActorEmail),+ },+ })+ }blockList = append(blockList, Block{Type: "actions",diff --git a/backend/plugin/webhook/teams/teams.go b/backend/plugin/webhook/teams/teams.goindex 403755865c..91184d983f 100644--- a/backend/plugin/webhook/teams/teams.go+++ b/backend/plugin/webhook/teams/teams.go@@ -159,6 +159,14 @@ func postMessage(context webhook.Context) error {factList = append(factList, WebhookSectionFact(meta))}+ section := WebhookSection{+ FactList: factList,+ Text: context.Description,+ }+ if context.ActorName != "" {+ section.ActivityTitle = fmt.Sprintf("%s (%s)", context.ActorName, context.ActorEmail)+ }+post := Webhook{Type: "MessageCard",Context: "https://schema.org/extensions",@@ -166,11 +174,7 @@ func postMessage(context webhook.Context) error {ThemeColor: themeColor,Title: context.Title,SectionList: []WebhookSection{- {- ActivityTitle: fmt.Sprintf("%s (%s)", context.ActorName, context.ActorEmail),- FactList: factList,- Text: context.Description,- },+ section,},ActionList: []WebhookAction{{@@ -251,10 +255,12 @@ func getAdaptiveCard(context webhook.Context) *AdaptiveCard {Value: meta.Value,})}- facts = append(facts, fact{- Title: "Actor",- Value: fmt.Sprintf("%s (%s)", context.ActorName, context.ActorEmail),- })+ if context.ActorName != "" {+ facts = append(facts, fact{+ Title: "Actor",+ Value: fmt.Sprintf("%s (%s)", context.ActorName, context.ActorEmail),+ })+ }if len(facts) > 0 {body = append(body, factSet{diff --git a/backend/plugin/webhook/webhook.go b/backend/plugin/webhook/webhook.goindex 9e867a6015..1e3f44463a 100644--- a/backend/plugin/webhook/webhook.go+++ b/backend/plugin/webhook/webhook.go@@ -61,20 +61,6 @@ type Rollout struct {Title string}-type Stage struct {- Name string-}--// TaskResult is the latest result of a task.-// The `detail` field is only present if the status is TaskFailed.-// The `SkippedReason` field is only present if the task is skipped.-type TaskResult struct {- Name string- Status string- Detail string- SkippedReason string-}-// Project object of project.type Project struct {Name string@@ -96,19 +82,15 @@ type Context struct {CreatedTS int64Issue *IssueRollout *Rollout- Stage *StageProject *Project- TaskResult *TaskResult// End users that should be mentioned.MentionEndUsers []*store.UserMessageDirectMessage boolIMSetting *storepb.AppIMSetting- // New event data- ApprovalRole string- FailedTasks []FailedTaskInfo- PipelineMetrics *PipelineMetrics+ // Event-specific data+ FailedTasks []FailedTaskInfo}// FailedTaskInfo contains information about a failed task.@@ -120,14 +102,6 @@ type FailedTaskInfo struct {FailedAt string}-// PipelineMetrics contains metrics about a pipeline execution.-type PipelineMetrics struct {- TotalTasks int- StartedAt string- CompletedAt string- DurationSecs int64-}-// Receiver is the webhook receiver.type Receiver interface {Post(context Context) error@@ -168,38 +142,6 @@ func (c *Context) GetMetaList() []Meta {}}- if c.Stage != nil {- m = append(m, Meta{- Name: "Stage",- Value: c.Stage.Name,- })- }-- if c.TaskResult != nil {- if c.TaskResult.Name != "" {- m = append(m, Meta{- Name: "Task",- Value: c.TaskResult.Name,- })- }- m = append(m, Meta{- Name: "Status",- Value: c.TaskResult.Status,- })- if c.TaskResult.Detail != "" {- m = append(m, Meta{- Name: "Result Detail",- Value: common.TruncateStringWithDescription(c.TaskResult.Detail),- })- }- if c.TaskResult.SkippedReason != "" {- m = append(m, Meta{- Name: "Skipped Reason",- Value: c.TaskResult.SkippedReason,- })- }- }-return m}@@ -238,38 +180,6 @@ func (c *Context) GetMetaListZh() []Meta {}}- if c.Stage != nil {- m = append(m, Meta{- Name: "阶段",- Value: c.Stage.Name,- })- }-- if c.TaskResult != nil {- if c.TaskResult.Name != "" {- m = append(m, Meta{- Name: "任务",- Value: c.TaskResult.Name,- })- }- m = append(m, Meta{- Name: "状态",- Value: c.TaskResult.Status,- })- if c.TaskResult.Detail != "" {- m = append(m, Meta{- Name: "结果详情",- Value: common.TruncateStringWithDescription(c.TaskResult.Detail),- })- }- if c.TaskResult.SkippedReason != "" {- m = append(m, Meta{- Name: "跳过原因",- Value: c.TaskResult.SkippedReason,- })- }- }-return m}diff --git a/backend/plugin/webhook/webhook_test.go b/backend/plugin/webhook/webhook_test.goindex b212f995d0..40fbf86d16 100644--- a/backend/plugin/webhook/webhook_test.go+++ b/backend/plugin/webhook/webhook_test.go@@ -1,126 +1,12 @@package webhookimport (- "crypto/rand""testing""github.com/stretchr/testify/require"-- "github.com/bytebase/bytebase/backend/common")func TestContext_getMetaList(t *testing.T) {- t.Run("task1", func(t *testing.T) {- a := require.New(t)- context := Context{- TaskResult: &TaskResult{- Name: "task name",- Status: "PENDING_APPROVAL",- },- }- want := []Meta{- {- Name: "Task",- Value: "task name",- },- {- Name: "Status",- Value: "PENDING_APPROVAL",- },- }- a.Equal(want, context.GetMetaList())- })- t.Run("task2", func(t *testing.T) {- a := require.New(t)- context := Context{- TaskResult: &TaskResult{- Name: "task name",- Status: "FAILED",- Detail: "SQL STATE",- },- }- want := []Meta{- {- Name: "Task",- Value: "task name",- },- {- Name: "Status",- Value: "FAILED",- },- {- Name: "Result Detail",- Value: "SQL STATE",- },- }- a.Equal(want, context.GetMetaList())- })- t.Run("task3", func(t *testing.T) {- a := require.New(t)-- // generate random string- b := make([]byte, 300)- _, err := rand.Read(b)- a.NoError(err)- detail := string(b)- a.Equal(300, len(detail))-- context := Context{- TaskResult: &TaskResult{- Name: "task name",- Status: "FAILED",- Detail: detail,- },- }- want := []Meta{- {- Name: "Task",- Value: "task name",- },- {- Name: "Status",- Value: "FAILED",- },- {- Name: "Result Detail",- Value: common.TruncateStringWithDescription(detail),- },- }- a.Equal(want, context.GetMetaList())- })- t.Run("task4", func(t *testing.T) {- a := require.New(t)-- // generate random string- b := make([]byte, 600)- _, err := rand.Read(b)- a.NoError(err)- detail := string(b)- a.Equal(600, len(detail))-- context := Context{- TaskResult: &TaskResult{- Name: "task name",- Status: "FAILED",- Detail: detail,- },- }- want := []Meta{- {- Name: "Task",- Value: "task name",- },- {- Name: "Status",- Value: "FAILED",- },- {- Name: "Result Detail",- Value: common.TruncateStringWithDescription(detail),- },- }- a.Equal(want, context.GetMetaList())- })t.Run("Issue with Creator", func(t *testing.T) {a := require.New(t)context := Context{diff --git a/backend/plugin/webhook/wecom/wecom.go b/backend/plugin/webhook/wecom/wecom.goindex 0ae2a7a854..e93f067f2b 100644--- a/backend/plugin/webhook/wecom/wecom.go+++ b/backend/plugin/webhook/wecom/wecom.go@@ -63,7 +63,9 @@ func getMessageCard(context webhook.Context) *WebhookMarkdown {for _, meta := range context.GetMetaList() {metaStrList = append(metaStrList, fmt.Sprintf("**%s**: %s", meta.Name, meta.Value))}- metaStrList = append(metaStrList, fmt.Sprintf("**Actor**: %s (%s)", context.ActorName, context.ActorEmail))+ if context.ActorName != "" {+ metaStrList = append(metaStrList, fmt.Sprintf("**Actor**: %s (%s)", context.ActorName, context.ActorEmail))+ }status := ""switch context.Level {diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.goindex acc7edc723..b6542772d6 100644--- a/backend/runner/approval/runner.go+++ b/backend/runner/approval/runner.go@@ -258,14 +258,15 @@ func (r *Runner) findApprovalTemplateForIssue(ctx context.Context, issue *store.// Trigger ISSUE_APPROVAL_REQUESTED webhookr.webhookManager.CreateEvent(ctx, &webhook.Event{- Actor: creator,Type: storepb.Activity_ISSUE_APPROVAL_REQUESTED,- Comment: "",- Issue: webhook.NewIssue(issue),Project: webhook.NewProject(project),ApprovalRequested: &webhook.EventIssueApprovalRequested{- ApprovalRole: role,- Approvers: approvers,+ Creator: &webhook.User{+ Name: creator.Name,+ Email: creator.Email,+ },+ Issue: webhook.NewIssue(issue),+ Approvers: approvers,},})}()diff --git a/backend/runner/taskrun/running_scheduler.go b/backend/runner/taskrun/running_scheduler.goindex 26a759a892..43ebd5799a 100644--- a/backend/runner/taskrun/running_scheduler.go+++ b/backend/runner/taskrun/running_scheduler.go@@ -390,11 +390,6 @@ func (s *Scheduler) recordPipelineFailure(ctx context.Context, task *store.TaskMreturn errors.Errorf("project %v not found", plan.ProjectID)}- issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{PlanUID: &task.PlanID})- if err != nil {- return errors.Wrap(err, "failed to get issue")- }-instance, err := s.store.GetInstance(ctx, &store.FindInstanceMessage{ResourceID: &task.InstanceID})if err != nil {return errors.Wrapf(err, "failed to get instance")@@ -413,24 +408,16 @@ func (s *Scheduler) recordPipelineFailure(ctx context.Context, task *store.TaskMplan.UID,failedTask,func(failedTasks []webhook.FailedTask) {- firstFailureTime := time.Now().Add(-5 * time.Minute)- if len(failedTasks) > 0 {- firstFailureTime = failedTasks[0].FailedAt- }-// Use background context to avoid cancellation issueswebhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()s.webhookManager.CreateEvent(webhookCtx, &webhook.Event{- Actor: store.SystemBotUser,Type: storepb.Activity_PIPELINE_FAILED,Project: webhook.NewProject(project),- Issue: webhook.NewIssue(issue),- Rollout: webhook.NewRollout(plan),- PipelineFailed: &webhook.EventPipelineFailed{- FailedTasks: failedTasks,- FirstFailureTime: firstFailureTime,+ RolloutFailed: &webhook.EventRolloutFailed{+ Rollout: webhook.NewRollout(plan),+ FailedTasks: failedTasks,},})},diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.goindex eb288cf155..1cf6fef4fc 100644--- a/backend/runner/taskrun/scheduler.go+++ b/backend/runner/taskrun/scheduler.go@@ -204,26 +204,11 @@ func (s *Scheduler) checkPlanCompletion(ctx context.Context, planID int64) {}// Send PIPELINE_COMPLETED webhook- startedAt := time.Now()- completedAt := time.Now()- if earliestStart != nil {- startedAt = *earliestStart- }- if latestEnd != nil {- completedAt = *latestEnd- }-s.webhookManager.CreateEvent(ctx, &webhook.Event{- Actor: store.SystemBotUser,Type: storepb.Activity_PIPELINE_COMPLETED,- Comment: "",- Issue: webhook.NewIssue(issueN),- Rollout: webhook.NewRollout(plan),Project: webhook.NewProject(project),- PipelineCompleted: &webhook.EventPipelineCompleted{- TotalTasks: len(tasks),- StartedAt: startedAt,- CompletedAt: completedAt,+ RolloutCompleted: &webhook.EventRolloutCompleted{+ Rollout: webhook.NewRollout(plan),},})}diff --git a/backend/server/ultimate.go b/backend/server/ultimate.goindex 6a667158c6..35e2c5a9ff 100644--- a/backend/server/ultimate.go+++ b/backend/server/ultimate.go@@ -67,7 +67,10 @@ import (// IM webhooks._ "github.com/bytebase/bytebase/backend/plugin/webhook/dingtalk"+ _ "github.com/bytebase/bytebase/backend/plugin/webhook/discord"_ "github.com/bytebase/bytebase/backend/plugin/webhook/feishu"+ _ "github.com/bytebase/bytebase/backend/plugin/webhook/lark"_ "github.com/bytebase/bytebase/backend/plugin/webhook/slack"+ _ "github.com/bytebase/bytebase/backend/plugin/webhook/teams"_ "github.com/bytebase/bytebase/backend/plugin/webhook/wecom")diff --git a/backend/server/ultimate_linux.go b/backend/server/ultimate_linux.godeleted file mode 100644index 7edee30b8b..0000000000--- a/backend/server/ultimate_linux.go+++ /dev/null@@ -1,6 +0,0 @@-//go:build !minidemo--package server--// Drivers under linux.-// _ "github.com/bytebase/bytebase/backend/plugin/db/obo"