Skip to content

Commit

Permalink
fix: 🐛 [frontend-gray] 修改header -> head, cookie设置默认时间为2天
Browse files Browse the repository at this point in the history
  • Loading branch information
heimanba committed Sep 10, 2024
1 parent 122834e commit 2d0ddab
Show file tree
Hide file tree
Showing 6 changed files with 34 additions and 27 deletions.
10 changes: 5 additions & 5 deletions plugins/wasm-go/extensions/frontend-gray/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
| `baseDeployment` | object | 非必填 | - | 配置Base基线规则的配置 |
| `grayDeployments` | array of object | 非必填 | - | 配置Gray灰度的生效规则,以及生效版本 |
| `backendGrayTag` | string | 非必填 | `x-mse-tag` | 后端灰度版本Tag,如果配置了,cookie中将携带值为`${backendGrayTag}:${grayDeployments[].backendVersion}` |
| `debugGrayWeight` | boolean | 非必填 | - | 开启安比例灰度的Debug模式,用于观测按比例灰度效果 |
| `debugGrayWeight` | boolean | 非必填 | - | 开启按照比例灰度的Debug模式,用于观测按比例灰度效果 |
| `injection` | object | 非必填 | - | 往首页HTML中注入全局信息,比如`<script>window.global = {...}</script>` |


Expand Down Expand Up @@ -58,8 +58,8 @@

| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
|--------|--------|------|-----|-------------------------------------------------|
| `header` | array of string | 非必填 | - | 注入header信息,比如`<link rel="stylesheet" href="https://cdn.example.com/styles.css">` |
| `body` | map of string to string | 非必填 | - | 注入Body |
| `head` | array of string | 非必填 | - | 注入head信息,比如`<link rel="stylesheet" href="https://cdn.example.com/styles.css">` |
| `body` | object | 非必填 | - | 注入Body |

`injection.body`字段配置说明:
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
Expand Down Expand Up @@ -218,7 +218,7 @@ grayDeployments:
enabled: true
weight: 80
injection:
header:
head:
- <script>console.log('Header')</script>
body:
first:
Expand All @@ -228,4 +228,4 @@ injection:
- <script>console.log('hello world after')</script>
- <script>console.log('hello world after2')</script>
```
通过 `injection`往HTML首页注入代码,可以在`header`标签注入代码,也可以在`body`标签的`first`和`last`位置注入代码。
通过 `injection`往HTML首页注入代码,可以在`head`标签注入代码,也可以在`body`标签的`first`和`last`位置注入代码。
10 changes: 6 additions & 4 deletions plugins/wasm-go/extensions/frontend-gray/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ const (
XForwardedFor = "x-forwarded-for"
XPreHigressTag = "x-pre-higress-tag"
IsIndex = "is-index"
NotFound = "not-found"
IsNotFound = "is-not-found"
// 2 days
MaxAgeCookie = "172800"
)

type LogInfo func(format string, args ...interface{})
Expand Down Expand Up @@ -39,8 +41,8 @@ type Rewrite struct {
}

type Injection struct {
Header []string
Body *BodyInjection
Head []string
Body *BodyInjection
}

type BodyInjection struct {
Expand Down Expand Up @@ -131,7 +133,7 @@ func JsonToGrayConfig(json gjson.Result, grayConfig *GrayConfig) {
}

grayConfig.Injection = &Injection{
Header: convertToStringList(json.Get("injection.header").Array()),
Head: convertToStringList(json.Get("injection.head").Array()),
Body: &BodyInjection{
First: convertToStringList(json.Get("injection.body.first").Array()),
Last: convertToStringList(json.Get("injection.body.last").Array()),
Expand Down
7 changes: 3 additions & 4 deletions plugins/wasm-go/extensions/frontend-gray/envoy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ static_resources:
],
"rewrite": {
"host": "frontend-gray-cn-shanghai.oss-cn-shanghai-internal.aliyuncs.com",
"notFoundUri": "/mfe/app1/dev/333.html",
"notFoundUri": "/mfe/app1/{version}/333.html",
"indexRouting": {
"/app1": "/mfe/app1/{version}/index.html",
"/": "/mfe/app1/{version}/index.html"
Expand All @@ -89,13 +89,12 @@ static_resources:
{
"name": "beta-user",
"version": "0.0.1",
"enabled": true,
"weight": 50
"enabled": true
}
],
"debugGrayWeight": true,
"injection": {
"header": [
"head": [
"<script>console.log('Header')</script>"
],
"body": {
Expand Down
25 changes: 13 additions & 12 deletions plugins/wasm-go/extensions/frontend-gray/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ func onHttpResponseHeader(ctx wrapper.HttpContext, grayConfig config.GrayConfig,
status, err := proxywasm.GetHttpResponseHeader(":status")
contentType, _ := proxywasm.GetHttpResponseHeader("Content-Type")

// 只有200状态码才进行重写
if grayConfig.Rewrite != nil && grayConfig.Rewrite.Host != "" {
// 删除Content-Disposition,避免自动下载文件
proxywasm.RemoveHttpResponseHeader("Content-Disposition")
Expand All @@ -119,7 +118,7 @@ func onHttpResponseHeader(ctx wrapper.HttpContext, grayConfig config.GrayConfig,
if err != nil || status != "200" {
if status == "404" {
if grayConfig.Rewrite.NotFound != "" && isIndex {
ctx.SetContext(config.NotFound, true)
ctx.SetContext(config.IsNotFound, true)
responseHeaders, _ := proxywasm.GetHttpResponseHeaders()
headersMap := util.ConvertHeaders(responseHeaders)
if _, ok := headersMap[":status"]; !ok {
Expand Down Expand Up @@ -157,12 +156,12 @@ func onHttpResponseHeader(ctx wrapper.HttpContext, grayConfig config.GrayConfig,
frontendVersion := ctx.GetContext(config.XPreHigressTag).(string)
xForwardedFor := ctx.GetContext(config.XForwardedFor).(string)

// 设置当前的前端版本
proxywasm.AddHttpResponseHeader("Set-Cookie", fmt.Sprintf("%s=%s,%s; Path=/;", config.XPreHigressTag, frontendVersion, util.GetRealIpFromXff(xForwardedFor)))
// 设置后端的前端版本
// 设置前端的版本
proxywasm.AddHttpResponseHeader("Set-Cookie", fmt.Sprintf("%s=%s,%s; Max-Age=%s; Path=/;", config.XPreHigressTag, frontendVersion, util.GetRealIpFromXff(xForwardedFor), config.MaxAgeCookie))
// 设置后端的版本
if util.IsBackendGrayEnabled(grayConfig) {
backendVersion := ctx.GetContext(grayConfig.BackendGrayTag).(string)
proxywasm.AddHttpResponseHeader("Set-Cookie", fmt.Sprintf("%s=%s; Path=/;", grayConfig.BackendGrayTag, backendVersion))
proxywasm.AddHttpResponseHeader("Set-Cookie", fmt.Sprintf("%s=%s; Max-Age=%s; Path=/;", grayConfig.BackendGrayTag, backendVersion, config.MaxAgeCookie))
}
}
return types.ActionContinue
Expand All @@ -173,11 +172,13 @@ func onHttpResponseBody(ctx wrapper.HttpContext, grayConfig config.GrayConfig, b
return types.ActionContinue
}
isIndex := ctx.GetContext(config.IsIndex).(bool)
frontendVersion := ctx.GetContext(config.XPreHigressTag).(string)

notFoundUri := ctx.GetContext(config.NotFound)
if isIndex && notFoundUri != nil && notFoundUri.(bool) && grayConfig.Rewrite.Host != "" && grayConfig.Rewrite.NotFound != "" {
isNotFound := ctx.GetContext(config.IsNotFound)
if isIndex && isNotFound != nil && isNotFound.(bool) && grayConfig.Rewrite.Host != "" && grayConfig.Rewrite.NotFound != "" {
client := wrapper.NewClusterClient(wrapper.RouteCluster{Host: grayConfig.Rewrite.Host})
client.Get(grayConfig.Rewrite.NotFound, nil, func(statusCode int, responseHeaders http.Header, responseBody []byte) {

client.Get(strings.Replace(grayConfig.Rewrite.NotFound, "{version}", frontendVersion, -1), nil, func(statusCode int, responseHeaders http.Header, responseBody []byte) {
proxywasm.ReplaceHttpResponseBody(responseBody)
proxywasm.ResumeHttpResponse()
}, 1500)
Expand All @@ -189,19 +190,19 @@ func onHttpResponseBody(ctx wrapper.HttpContext, grayConfig config.GrayConfig, b
newBody := string(body)

// 收集需要插入的内容
headerInjection := strings.Join(grayConfig.Injection.Header, "\n")
headInjection := strings.Join(grayConfig.Injection.Head, "\n")
bodyFirstInjection := strings.Join(grayConfig.Injection.Body.First, "\n")
bodyLastInjection := strings.Join(grayConfig.Injection.Body.Last, "\n")

// 使用 strings.Builder 来提高性能
var sb strings.Builder
// 预分配内存,避免多次内存分配
sb.Grow(len(newBody) + len(headerInjection) + len(bodyFirstInjection) + len(bodyLastInjection))
sb.Grow(len(newBody) + len(headInjection) + len(bodyFirstInjection) + len(bodyLastInjection))
sb.WriteString(newBody)

// 进行替换
content := sb.String()
content = strings.ReplaceAll(content, "</head>", fmt.Sprintf("%s\n</head>", headerInjection))
content = strings.ReplaceAll(content, "</head>", fmt.Sprintf("%s\n</head>", headInjection))
content = strings.ReplaceAll(content, "<body>", fmt.Sprintf("<body>\n%s", bodyFirstInjection))
content = strings.ReplaceAll(content, "</body>", fmt.Sprintf("%s\n</body>", bodyLastInjection))

Expand Down
5 changes: 4 additions & 1 deletion plugins/wasm-go/extensions/frontend-gray/util/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"math/rand"
"net/url"
"os"
"path"
"path/filepath"
"sort"
Expand All @@ -19,7 +20,9 @@ import (

func LogInfof(format string, args ...interface{}) {
format = fmt.Sprintf("[%s] %s", "frontend-gray", format)
proxywasm.LogInfof(format, args...)
if os.Getenv("TEST_MODE") != "" {
proxywasm.LogInfof(format, args...)
}
}

// 从xff中获取真实的IP
Expand Down
4 changes: 3 additions & 1 deletion plugins/wasm-go/extensions/frontend-gray/util/utils_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package util

import (
"os"
"testing"

"github.com/alibaba/higress/plugins/wasm-go/extensions/frontend-gray/config"
Expand Down Expand Up @@ -116,8 +117,9 @@ func TestFilterGrayWeight(t *testing.T) {
testName := test.name
t.Run(testName, func(t *testing.T) {
grayConfig := &config.GrayConfig{}
os.Setenv("TEST_MODE", "true")
config.JsonToGrayConfig(gjson.Parse(test.input), grayConfig)
reslut := FilterGrayWeight(grayConfig)
reslut := FilterGrayWeight(grayConfig, []string{"base", "1.0.1"}, "192.168.1.1")
t.Logf("reslut-----: %v", reslut)
})
}
Expand Down

0 comments on commit 2d0ddab

Please sign in to comment.