Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: show failed task run result via IM webhook (#3327)
p0nyccd06ead3e68
diff --git a/plugin/webhook/custom.go b/plugin/webhook/custom.goindex 032945c645..6b6c2cff92 100644--- a/plugin/webhook/custom.go+++ b/plugin/webhook/custom.go@@ -34,10 +34,10 @@ func init() {}// CustomReceiver is the receiver for custom.-type CustomReceiver struct {-}+type CustomReceiver struct{}func (*CustomReceiver) post(context Context) error {+ // TODO(p0ny): handle context.Taskpayload := CustomWebhookRequest{Level: context.Level,ActivityType: context.ActivityType,diff --git a/plugin/webhook/webhook.go b/plugin/webhook/webhook.goindex cd612debe5..bbf4f3d6b0 100644--- a/plugin/webhook/webhook.go+++ b/plugin/webhook/webhook.go@@ -44,6 +44,14 @@ type Issue struct {Description string `json:"description"`}+// TaskResult is the latest result of a task.+// The `detail` field is only present if the status is TaskFailed.+type TaskResult struct {+ Name string `json:"name"`+ Status string `json:"status"`+ Detail string `json:"detail"`+}+// Project object of project.type Project struct {ID int `json:"id"`@@ -64,6 +72,7 @@ type Context struct {CreatedTs int64Issue *IssueProject *Project+ TaskResult *TaskResult}// Receiver is the webhook receiver.@@ -102,6 +111,28 @@ func (c *Context) getMetaList() []meta {})}+ if c.TaskResult != nil {+ m = append(m, meta{+ Name: "Task",+ Value: c.TaskResult.Name,+ })+ m = append(m, meta{+ Name: "Status",+ Value: c.TaskResult.Status,+ })+ if c.TaskResult.Detail != "" {+ resultDetailRune := []rune(c.TaskResult.Detail)+ if len(resultDetailRune) > 200 {+ resultDetailRune = resultDetailRune[:200]+ resultDetailRune = append(resultDetailRune, []rune("... (view details in Bytebase)")...)+ }+ m = append(m, meta{+ Name: "Result Detail",+ Value: string(resultDetailRune),+ })+ }+ }+return m}diff --git a/plugin/webhook/webhook_test.go b/plugin/webhook/webhook_test.gonew file mode 100644index 0000000000..b4350935b7--- /dev/null+++ b/plugin/webhook/webhook_test.go@@ -0,0 +1,95 @@+package webhook++import (+ "crypto/rand"+ "testing"++ "github.com/stretchr/testify/require"+)++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))++ resultDetailRune := []rune(detail)+ if len(resultDetailRune) > 200 {+ resultDetailRune = resultDetailRune[:200]+ resultDetailRune = append(resultDetailRune, []rune("... (view details in Bytebase)")...)+ }++ 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: string(resultDetailRune),+ },+ }+ a.Equal(want, context.getMetaList())+ })+}diff --git a/server/activity_manager.go b/server/activity_manager.goindex f81e736cc4..9052e2ebe0 100644--- a/server/activity_manager.go+++ b/server/activity_manager.go@@ -4,6 +4,7 @@ import ("context""encoding/json""fmt"+ "sort""strconv""time"@@ -148,7 +149,6 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.Activireturn nil, errors.Errorf("updater principal not found for ID %v", create.CreatorID)}- // Call external webhook endpoint in Go routine to avoid blocking web serving thread.webhookCtx, err := m.getWebhookContext(ctx, activity, meta, updater)if err != nil {log.Warn("Failed to get webhook context",@@ -156,6 +156,7 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.Activizap.Error(err))return activity, nil}+ // Call external webhook endpoint in Go routine to avoid blocking web serving thread.go postWebhookList(webhookCtx, webhookList, meta.issue)return activity, nil@@ -176,8 +177,10 @@ func postWebhookList(webhookCtx webhook.Context, webhookList []*api.ProjectWebho}}}+func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.Activity, meta *ActivityMeta, updater *api.Principal) (webhook.Context, error) {var webhookCtx webhook.Context+ var webhookTaskResult *webhook.TaskResultlevel := webhook.WebhookInfotitle := ""link := fmt.Sprintf("%s/issue/%s", m.s.profile.ExternalURL, api.IssueSlug(meta.issue))@@ -304,6 +307,11 @@ func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.Areturn webhookCtx, err}+ webhookTaskResult = &webhook.TaskResult{+ Name: task.Name,+ Status: string(task.Status),+ }+title = "Task changed - " + task.Nameswitch update.NewStatus {case api.TaskPending:@@ -321,6 +329,29 @@ func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.Acase api.TaskFailed:level = webhook.WebhookErrortitle = "Task failed - " + task.Name++ if len(task.TaskRunList) == 0 {+ err := errors.Errorf("expect at least 1 TaskRun, get 0")+ log.Warn(err.Error(),+ zap.Any("task", task),+ zap.Error(err))+ return webhookCtx, err+ }++ // sort TaskRunList to get the most recent task run result.+ sort.Slice(task.TaskRunList, func(i int, j int) bool {+ return task.TaskRunList[i].UpdatedTs > task.TaskRunList[j].UpdatedTs || (task.TaskRunList[i].UpdatedTs == task.TaskRunList[j].UpdatedTs && task.TaskRunList[i].ID > task.TaskRunList[j].ID)+ })++ var result api.TaskRunResultPayload+ if err := json.Unmarshal([]byte(task.TaskRunList[0].Result), &result); err != nil {+ err := errors.Wrapf(err, "failed to unmarshal TaskRun Result")+ log.Warn(err.Error(),+ zap.Any("TaskRun", task.TaskRunList[0]),+ zap.Error(err))+ return webhookCtx, err+ }+ webhookTaskResult.Detail = result.Detail}}@@ -339,6 +370,7 @@ func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.AID: meta.issue.ProjectID,Name: meta.issue.Project.Name,},+ TaskResult: webhookTaskResult,Description: activity.Comment,Link: link,CreatorID: updater.ID,