Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix: improve feishu approval card info (#3654)
p0ny482a1b5cc1f4
diff --git a/common/util.go b/common/util.goindex 005e5c8e2c..ae24d0d267 100644--- a/common/util.go+++ b/common/util.go@@ -2,6 +2,7 @@ package commonimport ("crypto/rand"+ "fmt""math/big""os""path"@@ -115,3 +116,25 @@ func GetBinlogRelativeDir(binlogDir string) string {instanceID := filepath.Base(binlogDir)return filepath.Join("backup", "instance", instanceID)}++// truncateString truncates the string to have a maximum length of `limit` characters.+func truncateString(str string, limit int) (string, bool) {+ chars := 0+ // The string may contain unicode characters, so we iterate here.+ for i := range str {+ if chars >= limit {+ return str[:i], true+ }+ chars+++ }+ return str, false+}++// TruncateStringWithDescription tries to truncate the string and append "... (view details in Bytebase)" if truncated.+func TruncateStringWithDescription(str string) string {+ const limit = 450+ if truncatedStr, truncated := truncateString(str, limit); truncated {+ return fmt.Sprintf("%s... (view details in Bytebase)", truncatedStr)+ }+ return str+}diff --git a/common/util_test.go b/common/util_test.goindex af60857f83..2b3eed979b 100644--- a/common/util_test.go+++ b/common/util_test.go@@ -33,10 +33,87 @@ func TestHasPrefixes(t *testing.T) {want: false,},}- for _, tt := range tests {+ for i := range tests {+ tt := tests[i]t.Run(tt.name, func(t *testing.T) {got := HasPrefixes(tt.args.src, tt.args.prefixes...)assert.Equal(t, got, tt.want)})}}++func TestTruncateString(t *testing.T) {+ tests := []struct {+ name string+ str string+ limit int+ want string+ truncated bool+ }{+ {+ name: "simple truncate 0",+ str: "0123",+ limit: 0,+ want: "",+ truncated: true,+ },+ {+ name: "simple truncate 2",+ str: "0123",+ limit: 2,+ want: "01",+ truncated: true,+ },+ {+ name: "simple truncate 3",+ str: "0123",+ limit: 3,+ want: "012",+ truncated: true,+ },+ {+ name: "simple truncate 4",+ str: "0123",+ limit: 4,+ want: "0123",+ truncated: false,+ },+ {+ name: "simple truncate 20",+ str: "0123",+ limit: 20,+ want: "0123",+ truncated: false,+ },+ {+ name: "unicode truncate 5",+ str: "H㐀〾▓朗퐭텟şüöžåйкл¤",+ limit: 5,+ want: "H㐀〾▓朗",+ truncated: true,+ },+ {+ name: "unicode truncate 10",+ str: "H㐀〾▓朗퐭텟şüöžåйкл¤",+ limit: 10,+ want: "H㐀〾▓朗퐭텟şüö",+ truncated: true,+ },+ {+ name: "unicode fit",+ str: "H㐀〾▓朗퐭텟şüöžåйкл¤",+ limit: 16,+ want: "H㐀〾▓朗퐭텟şüöžåйкл¤",+ truncated: false,+ },+ }+ a := assert.New(t)+ for i := range tests {+ test := tests[i]+ t.Run(test.name, func(t *testing.T) {+ got, truncated := truncateString(test.str, test.limit)+ a.Equal(test.want, got)+ a.Equal(test.truncated, truncated)+ })+ }+}diff --git a/plugin/app/feishu/feishu.go b/plugin/app/feishu/feishu.goindex edc36a9f1f..5ccb9303a8 100644--- a/plugin/app/feishu/feishu.go+++ b/plugin/app/feishu/feishu.go@@ -4,6 +4,7 @@ package feishuimport ("bytes""context"+ "crypto/sha1""encoding/json""fmt""io"@@ -13,6 +14,8 @@ import ("time""github.com/pkg/errors"++ "github.com/bytebase/bytebase/common")// Response code definition in feishu response body.@@ -178,17 +181,18 @@ type GetIDByEmailRequest struct {// Content is the content of the approval.type Content struct {- Issue string- Stage string- Link string- TaskList []Task- Description string+ Issue string+ Stage string+ Link string+ TaskList []Task+ SQL string}// Task is the content of a task.type Task struct {- Name string- Status string+ Name string+ Status string+ Statement string}const (@@ -233,7 +237,7 @@ const (},{"key": "@i18n@widget5",- "value": "描述"+ "value": "SQL"}]},@@ -267,7 +271,7 @@ const (},{"key": "@i18n@widget5",- "value": "Description"+ "value": "SQL"}]}@@ -565,7 +569,7 @@ func (p *Provider) CancelExternalApproval(ctx context.Context, tokenCtx TokenCtx}if response.Code != 0 {- return errors.Errorf("failed to create external approval, code %d, msg %s", response.Code, response.Msg)+ return errors.Errorf("failed to cancel external approval, code %d, msg %s", response.Code, response.Msg)}return nil@@ -627,7 +631,7 @@ func (p *Provider) GetBotID(ctx context.Context, tokenCtx TokenCtx) (string, errreturn "", err}if response.Code != 0 {- return "", errors.Errorf("failed to create external approval, code %d, msg %s", response.Code, response.Msg)+ return "", errors.Errorf("failed to get bot id, code %d, msg %s", response.Code, response.Msg)}return response.Bot.OpenID, nil@@ -648,6 +652,12 @@ func formatForm(content Content) (string, error) {return "", err}}++ sql, err := formatFormSQL(content.TaskList)+ if err != nil {+ return "", err+ }+forms := []form{{ID: "1",@@ -672,7 +682,7 @@ func formatForm(content Content) (string, error) {{ID: "5",Type: "textarea",- Value: content.Description,+ Value: sql,},}b, err := json.Marshal(forms)@@ -681,3 +691,69 @@ func formatForm(content Content) (string, error) {}return string(b), nil}++func formatFormSQL(contentTaskList []Task) (string, error) {+ const taskSQLDisplayLimit = 5+ delimiter := strings.Repeat("=", 25)+ var sql strings.Builder++ sqlHashToTaskGroup := make(map[string]int)+ var taskGroup [][]int++ // divide tasks with the same SQLs to groups.+ for i, task := range contentTaskList {+ if task.Statement == "" {+ continue+ }+ hash := fmt.Sprintf("%x", sha1.Sum([]byte(task.Statement)))+ group, ok := sqlHashToTaskGroup[hash]+ if ok {+ taskGroup[group] = append(taskGroup[group], i)+ } else {+ taskGroup = append(taskGroup, []int{i})+ sqlHashToTaskGroup[hash] = len(taskGroup) - 1+ }+ }++ // Check if every task has the same SQL.+ // For tenant mode, it's very likely for tasks to have identical SQLs.+ // If there is one unique sql, and every task has the sql.+ if len(taskGroup) == 1 && len(taskGroup[0]) == len(contentTaskList) {+ if _, err := sql.WriteString(fmt.Sprintf("%s\nThe SQL statement of every task\n%s\n", delimiter, delimiter)); err != nil {+ return "", err+ }+ truncated := common.TruncateStringWithDescription(contentTaskList[taskGroup[0][0]].Statement)+ if _, err := sql.WriteString(fmt.Sprintf("%s\n\n", truncated)); err != nil {+ return "", err+ }+ return sql.String(), nil+ }++ count := 0+ for _, taskList := range taskGroup {+ if count >= taskSQLDisplayLimit {+ if _, err := sql.WriteString(fmt.Sprintf("%s\nDisplaying %d SQL statements, view more in Bytebase\n", delimiter, count)); err != nil {+ return "", err+ }+ break+ }++ if len(taskList) == 0 {+ continue+ }+ var tasks []string+ for _, taskIndex := range taskList {+ tasks = append(tasks, fmt.Sprintf("%d", taskIndex+1))+ }++ if _, err := sql.WriteString(fmt.Sprintf("%s\nThe SQL statement of task %s\n%s\n", delimiter, strings.Join(tasks, ","), delimiter)); err != nil {+ return "", err+ }+ truncated := common.TruncateStringWithDescription(contentTaskList[taskList[0]].Statement)+ if _, err := sql.WriteString(fmt.Sprintf("%s\n\n", truncated)); err != nil {+ return "", err+ }+ count+++ }+ return sql.String(), nil+}diff --git a/plugin/app/feishu/feishu_test.go b/plugin/app/feishu/feishu_test.goindex ece3b09abe..ac1fd8a4e7 100644--- a/plugin/app/feishu/feishu_test.go+++ b/plugin/app/feishu/feishu_test.go@@ -286,3 +286,167 @@ func TestProvider_GetBotID(t *testing.T) {want := "ou_e6e14f667cfe239d7b129b521dce0569"a.Equal(want, botID)}++func TestFormatSQL(t *testing.T) {+ a := require.New(t)+ tests := []struct {+ name string+ contentTaskList []Task+ want string+ }{+ {+ name: "one group",+ contentTaskList: []Task{+ {+ Statement: "-- 1",+ },+ {+ Statement: "-- 1",+ },+ {+ Statement: "-- 1",+ },+ },+ want: `=========================+The SQL statement of every task+=========================+-- 1++`,+ },+ {+ name: "two groups",+ contentTaskList: []Task{+ {+ Statement: "-- 1",+ },+ {+ Statement: "-- 1",+ },+ {+ Statement: "-- 2",+ },+ },+ want: `=========================+The SQL statement of task 1,2+=========================+-- 1++=========================+The SQL statement of task 3+=========================+-- 2++`,+ },+ {+ name: "five groups",+ contentTaskList: []Task{+ {+ Statement: "-- 1",+ },+ {+ Statement: "-- 2",+ },+ {+ Statement: "-- 3",+ },+ {+ Statement: "-- 3",+ },+ {+ Statement: "-- 4",+ },+ {+ Statement: "-- 5",+ },+ },+ want: `=========================+The SQL statement of task 1+=========================+-- 1++=========================+The SQL statement of task 2+=========================+-- 2++=========================+The SQL statement of task 3,4+=========================+-- 3++=========================+The SQL statement of task 5+=========================+-- 4++=========================+The SQL statement of task 6+=========================+-- 5++`,+ },+ {+ name: "six groups",+ contentTaskList: []Task{+ {+ Statement: "-- 1",+ },+ {+ Statement: "-- 2",+ },+ {+ Statement: "-- 3",+ },+ {+ Statement: "-- 7",+ },+ {+ Statement: "-- 4",+ },+ {+ Statement: "-- 5",+ },+ },+ want: `=========================+The SQL statement of task 1+=========================+-- 1++=========================+The SQL statement of task 2+=========================+-- 2++=========================+The SQL statement of task 3+=========================+-- 3++=========================+The SQL statement of task 4+=========================+-- 7++=========================+The SQL statement of task 5+=========================+-- 4++=========================+Displaying 5 SQL statements, view more in Bytebase+`,+ },+ }++ for i := range tests {+ test := tests[i]+ t.Run(test.name, func(t *testing.T) {+ sql, err := formatFormSQL(test.contentTaskList)+ a.NoError(err)+ a.Equal(test.want, sql)+ })+ }+}diff --git a/plugin/webhook/webhook.go b/plugin/webhook/webhook.goindex a388bd1111..c46b7172d6 100644--- a/plugin/webhook/webhook.go+++ b/plugin/webhook/webhook.go@@ -6,6 +6,8 @@ import ("time""github.com/pkg/errors"++ "github.com/bytebase/bytebase/common")var (@@ -99,15 +101,9 @@ func (c *Context) getMetaList() []meta {// So the description could be long, which is hard to display if merged into the issue name.// We also trim it to 200 bytes to limit the message size in the webhook body, so that users can// view it easily in the corresponding webhook client.- // The issue description may contain unicode characters, so we use rune here.- descriptionRune := []rune(c.Issue.Description)- if len(descriptionRune) > 200 {- descriptionRune = descriptionRune[:200]- descriptionRune = append(descriptionRune, []rune("... (view details in Bytebase)")...)- }m = append(m, meta{Name: "Issue Description",- Value: string(descriptionRune),+ Value: common.TruncateStringWithDescription(c.Issue.Description),})}@@ -121,14 +117,9 @@ func (c *Context) getMetaList() []meta {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),+ Value: common.TruncateStringWithDescription(c.TaskResult.Detail),})}}diff --git a/plugin/webhook/webhook_test.go b/plugin/webhook/webhook_test.goindex b4350935b7..04cc3ee0c6 100644--- a/plugin/webhook/webhook_test.go+++ b/plugin/webhook/webhook_test.go@@ -5,6 +5,8 @@ import ("testing""github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/common")func TestContext_getMetaList(t *testing.T) {@@ -63,11 +65,38 @@ func TestContext_getMetaList(t *testing.T) {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: 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{@@ -87,7 +116,7 @@ func TestContext_getMetaList(t *testing.T) {},{Name: "Result Detail",- Value: string(resultDetailRune),+ Value: common.TruncateStringWithDescription(detail),},}a.Equal(want, context.getMetaList())diff --git a/server/application_runner.go b/server/application_runner.goindex beaa118b02..a3cf13cafe 100644--- a/server/application_runner.go+++ b/server/application_runner.go@@ -448,6 +448,17 @@ func (r *ApplicationRunner) createExternalApproval(ctx context.Context, issue *a})}+ for i, task := range stage.TaskList {+ statement, err := getTaskStatement(task)+ if err != nil {+ return err+ }+ if statement == "" {+ continue+ }+ taskList[i].Statement = statement+ }+instanceCode, err := r.p.CreateExternalApproval(ctx,feishu.TokenCtx{AppID: settingValue.AppID,diff --git a/server/task.go b/server/task.goindex c50244444a..c5380d54d5 100644--- a/server/task.go+++ b/server/task.go@@ -939,3 +939,13 @@ func (s *Server) cancelDependingTasks(ctx context.Context, task *api.Task) error}return nil}++func getTaskStatement(task *api.Task) (string, error) {+ var taskStatement struct {+ Statement string `json:"statement"`+ }+ if err := json.Unmarshal([]byte(task.Payload), &taskStatement); err != nil {+ return "", err+ }+ return taskStatement.Statement, nil+}