Skip to content

Commit

Permalink
refactor: 💡 优化代码编写以及命名问题
Browse files Browse the repository at this point in the history
  • Loading branch information
heimanba committed Aug 9, 2024
1 parent 4e5a471 commit cea1812
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 61 deletions.
22 changes: 12 additions & 10 deletions plugins/wasm-go/extensions/frontend-gray/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
| `grayKey` | string | 非必填 | - | 用户ID的唯一标识,可以来自Cookie或者Header中,比如 userid,如果没有填写则使用`rules[].grayTagKey``rules[].grayTagValue`过滤灰度规则 |
| `graySubKey` | string | 非必填 | - | 用户身份信息可能以JSON形式透出,比如:`userInfo:{ userCode:"001" }`,当前例子`graySubKey`取值为`userCode` |
| `rules` | array of object | 必填 | - | 用户定义不同的灰度规则,适配不同的灰度场景 |
| `rewrite` | object | 必填 | - | 重写配置,一般用于OSS/CDN 前端部署的重写配置 |
| `rewrite` | object | 必填 | - | 重写配置,一般用于OSS/CDN前端部署的重写配置 |
| `baseDeployment` | object | 非必填 | - | 配置Base基线规则的配置 |
| `grayDeployments` | array of object | 非必填 | - | 配置Gray灰度的生效规则,以及生效版本 |

Expand All @@ -22,15 +22,17 @@
| `grayTagValue` | array of string | 非必填 | - | 用户分类打标的标签value值,来自Cookie |

`rewrite`字段配置说明:
> `index`首页重写和`file`文件重写,本质都是前缀匹配,比如`/app1`: `/mfe/app1/{version}/index.html`代表/app1为前缀的请求,路由到`/mfe/app1/{version}/index.html`页面上,其中`{version}`代表版本号,在运行过程中会被`baseDeployment.version`或者`grayDeployments[].version`动态替换。
> `indexRouting`首页重写和`fileRouting`文件重写,本质都是前缀匹配,比如`/app1`: `/mfe/app1/{version}/index.html`代表/app1为前缀的请求,路由到`/mfe/app1/{version}/index.html`页面上,其中`{version}`代表版本号,在运行过程中会被`baseDeployment.version`或者`grayDeployments[].version`动态替换。
> `{version}` 作为保留字段,在灰度过程中进行动态替换前端版本。

| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
|------------|--------------|------|-----|------------------------------|
| `host` | string | 非必填 | - | host地址,如果是OSS则设置为 VPC 内网访问地址 |
| `notFound` | string | 非必填 | - | 404 页面配置 |
| `index` | object | 非必填 | - | 首页重写配置 |
| `file` | object | 非必填 | - | 文件重写配置 |
| `notFoundUri` | string | 非必填 | - | 404 页面配置 |
| `indexRouting` | object | 非必填 | - | 首页重写配置 |
| `fileRouting` | object | 非必填 | - | 文件重写配置 |

`baseDeployment`字段配置说明:

Expand Down Expand Up @@ -134,11 +136,11 @@ rules:
- level5
rewrite:
host: frontend-gray.oss-cn-shanghai-internal.aliyuncs.com
notFound: /mfe/app1/dev/404.html
index:
notFoundUri: /mfe/app1/dev/404.html
indexRouting:
/app1: '/mfe/app1/{version}/index.html'
/: '/mfe/app1/{version}/index.html',
file:
fileRouting:
/: '/mfe/app1/{version}'
/app1/: '/mfe/app1/{version}'
baseDeployment:
Expand All @@ -151,10 +153,10 @@ grayDeployments:

`{version}`会在运行过程中动态替换为真正的版本

#### 首页配置
#### indexRouting:首页路由配置
访问 `/app1`, `/app123`,`/app1/index.html`, `/app1/xxx`, `/xxxx` 都会路由到'/mfe/app1/{version}/index.html'

#### 文件配置
#### fileRouting:文件路由配置
下面文件映射均生效
- `/js/a.js` => `/mfe/app1/v1.0.0/js/a.js`
- `/js/template/a.js` => `/mfe/app1/v1.0.0/js/template/a.js`
Expand Down
12 changes: 6 additions & 6 deletions plugins/wasm-go/extensions/frontend-gray/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ type GrayConfig struct {
}

func convertToStringList(results []gjson.Result) []string {
interfaces := make([]string, 0)
for _, result := range results {
interfaces = append(interfaces, result.Value().(string))
interfaces := make([]string, len(results)) // 预分配切片容量
for i, result := range results {
interfaces[i] = result.String() // 使用 String() 方法直接获取字符串
}
return interfaces
}
Expand Down Expand Up @@ -85,9 +85,9 @@ func JsonToGrayConfig(json gjson.Result, grayConfig *GrayConfig) {
}
grayConfig.Rewrite = &Rewrite{
Host: json.Get("rewrite.host").String(),
NotFound: json.Get("rewrite.notFound").String(),
Index: convertToStringMap(json.Get("rewrite.index")),
File: convertToStringMap(json.Get("rewrite.file")),
NotFound: json.Get("rewrite.notFoundUri").String(),
Index: convertToStringMap(json.Get("rewrite.indexRouting")),
File: convertToStringMap(json.Get("rewrite.fileRouting")),
}

// 解析 deployment
Expand Down
6 changes: 3 additions & 3 deletions plugins/wasm-go/extensions/frontend-gray/envoy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,12 @@ static_resources:
],
"rewrite": {
"host": "frontend-gray-cn-shanghai.oss-cn-shanghai-internal.aliyuncs.com",
"notFound": "/mfe/app1/dev/404.html",
"index": {
"notFoundUri": "/mfe/app1/dev/404.html",
"indexRouting": {
"/app1": "/mfe/app1/{version}/index.html",
"/": "/mfe/app1/{version}/index.html"
},
"file": {
"fileRouting": {
"/": "/mfe/app1/{version}",
"/app1": "/mfe/app1/{version}"
}
Expand Down
26 changes: 11 additions & 15 deletions plugins/wasm-go/extensions/frontend-gray/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func parseConfig(json gjson.Result, grayConfig *config.GrayConfig, log wrapper.L
}

func onHttpRequestHeaders(ctx wrapper.HttpContext, grayConfig config.GrayConfig, log wrapper.Log) types.Action {
if !util.IsGreyEnabled(grayConfig) {
if !util.IsGrayEnabled(grayConfig) {
return types.ActionContinue
}

Expand All @@ -41,7 +41,7 @@ func onHttpRequestHeaders(ctx wrapper.HttpContext, grayConfig config.GrayConfig,
accept, _ := proxywasm.GetHttpRequestHeader("accept")
fetchMode, _ := proxywasm.GetHttpRequestHeader("sec-fetch-mode")

isIndex := util.CheckReqesutIsIndex(fetchMode, accept, path)
isIndex := util.IsIndexRequest(fetchMode, accept, path)
hasRewrite := len(grayConfig.Rewrite.File) > 0 || len(grayConfig.Rewrite.Index) > 0
grayKeyValue := util.GetGrayKey(util.ExtractCookieValueByKey(cookies, grayConfig.GrayKey), grayConfig.GraySubKey)

Expand Down Expand Up @@ -91,7 +91,7 @@ func onHttpRequestHeaders(ctx wrapper.HttpContext, grayConfig config.GrayConfig,
}

func onHttpResponseHeader(ctx wrapper.HttpContext, grayConfig config.GrayConfig, log wrapper.Log) types.Action {
if !util.IsGreyEnabled(grayConfig) {
if !util.IsGrayEnabled(grayConfig) {
return types.ActionContinue
}
status, err := proxywasm.GetHttpResponseHeader(":status")
Expand All @@ -117,20 +117,16 @@ func onHttpResponseHeader(ctx wrapper.HttpContext, grayConfig config.GrayConfig,
return types.ActionContinue
}

if grayConfig.Rewrite.Host != "" {
// 删除Content-Disposition,避免自动下载文件
proxywasm.RemoveHttpResponseHeader("Content-Disposition")
}
// 删除content-length,可能要修改Response返回值
proxywasm.RemoveHttpResponseHeader("Content-Length")

// 删除Content-Disposition,避免自动下载文件
proxywasm.RemoveHttpResponseHeader("Content-Disposition")

if strings.HasPrefix(contentType, "text/html") {
ctx.SetContext(config.IsHTML, true)
// 不会进去Streaming 的Body处理
ctx.BufferResponseBody()
// 删除content-length,可能要修改Response返回值
proxywasm.RemoveHttpResponseHeader("Content-Length")

// 删除Content-Disposition,避免自动下载文件
proxywasm.RemoveHttpResponseHeader("Content-Disposition")

// 添加Cache-Control 头部,禁止缓存
proxywasm.ReplaceHttpRequestHeader("Cache-Control", "no-cache, no-store")
Expand All @@ -147,14 +143,14 @@ func onHttpResponseHeader(ctx wrapper.HttpContext, grayConfig config.GrayConfig,
}

func onHttpResponseBody(ctx wrapper.HttpContext, grayConfig config.GrayConfig, body []byte, log wrapper.Log) types.Action {
if !util.IsGreyEnabled(grayConfig) {
if !util.IsGrayEnabled(grayConfig) {
return types.ActionContinue
}
backendVersion := ctx.GetContext(config.XMseTag)
isHtml := ctx.GetContext(config.IsHTML)
isIndex := ctx.GetContext(config.IsIndex)
notFound := ctx.GetContext(config.NotFound)
if isIndex != nil && isIndex.(bool) && notFound != nil && notFound.(bool) && grayConfig.Rewrite.Host != "" && grayConfig.Rewrite.NotFound != "" {
notFoundUri := ctx.GetContext(config.NotFound)
if isIndex != nil && isIndex.(bool) && notFoundUri != nil && notFoundUri.(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) {
proxywasm.ReplaceHttpResponseBody(responseBody)
Expand Down
43 changes: 16 additions & 27 deletions plugins/wasm-go/extensions/frontend-gray/util/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,22 @@ import (
"github.com/tidwall/gjson"
)

func IsGreyEnabled(grayConfig config.GrayConfig) bool {
func IsGrayEnabled(grayConfig config.GrayConfig) bool {
// 检查是否存在重写主机
if grayConfig.Rewrite != nil && grayConfig.Rewrite.Host != "" {
return true
}

// 检查灰度部署是否为 nil 或空
grayDeployments := grayConfig.GrayDeployments
if grayDeployments == nil || len(grayDeployments) == 0 {
return false
}
hasEnabled := false
for _, grayDeployment := range grayDeployments {
if grayDeployment.Enabled {
hasEnabled = true
if grayDeployments != nil && len(grayDeployments) > 0 {
for _, grayDeployment := range grayDeployments {
if grayDeployment.Enabled {
return true
}
}
}
if hasEnabled {
return true
}

return false
}

Expand Down Expand Up @@ -96,31 +94,22 @@ func GetRule(rules []*config.GrayRule, name string) *config.GrayRule {
}

// 检查是否是页面
func CheckReqesutIsIndex(fetchMode string, accept string, p string) bool {
// fetch/xhr 请求,认为不是页面
var indexSuffixes = []string{
".html", ".htm", ".jsp", ".php", ".asp", ".aspx", ".erb", ".ejs", ".twig",
}

// IsIndexRequest determines if the request is an index request
func IsIndexRequest(fetchMode string, accept string, p string) bool {
if fetchMode == "cors" {
return false
}

indexSuffixes := []string{
".html",
".htm",
".jsp",
".php",
".asp",
".aspx",
".erb",
".ejs",
".twig",
}

// 如果后缀存在html等,则返回true
for _, suffix := range indexSuffixes {
if strings.HasSuffix(p, suffix) {
return true
}
}
// 如果存在后缀,如果不存在,则返回true

return path.Ext(p) == ""
}

Expand Down

0 comments on commit cea1812

Please sign in to comment.