AlexStocks commented on code in PR #32:
URL:
https://github.com/apache/dubbo-go-extensions/pull/32#discussion_r4431014830
##########
filter/hystrix/filter.go:
##########
@@ -96,12 +83,26 @@ type Filter struct {
// Invoke is an implementation of filter, provides Hystrix pattern latency and
fault tolerance
func (f *Filter) Invoke(ctx context.Context, invoker base.Invoker, invocation
base.Invocation) result.Result {
- cmdName := getResourceName(invoker, invocation, f.isConsumer)
+ resourceName := getResourceName(invoker, invocation)
+ scope := extension.ServerScope
+ if f.isConsumer {
+ scope = extension.ClientScope
+ }
+ cmdName := internalCommandName(scope, resourceName)
Review Comment:
🔴 **未配置的方法会继承 hystrix 默认值:1s 超时 + 10 并发,且没有任何日志**
`cmdName` 在这里无条件算出来,紧接着就 `hystrix.Do`。而 hystrix-go 的 `getSettings`
在命令不存在时会**自动**用默认值创建:
```go
// hystrix-go/settings.go
func getSettings(name string) *Settings {
s, exists := circuitSettings[name]
if !exists {
ConfigureCommand(name, CommandConfig{}) // ← 全部走默认:1000ms /
10 并发
s = getSettings(name)
}
return s
}
```
问题的严重性来自本 PR 的新行为:`FilterNames` 返回 `hystrix_consumer`/`hystrix_provider`
后,core 会把它合并进**整个** client/server 的 filter 链(`MergeFilterNames`)。也就是说用户只要为 1
个方法配了熔断,其余所有方法都被塞进 hystrix,各自拿到 `Timeout=1000ms`、`MaxConcurrentRequests=10`。
我做了实测:先只配置 `configured:::Run`,然后用 20 个 goroutine 并发调一个**从未配置过**的方法(每次 200ms):
```
未配置方法 20 并发调用:失败 10 个,其中 CircuitOpen()=true 的 10 个
```
恰好 10 个被拒,就是 `DefaultMaxConcurrent`。provider 侧更危险:默认 1s 超时意味着任何耗时超过 1s
的方法都会对调用方返回 `hystrix: timeout`,而 handler 还在后台继续跑。
**Suggestion**:让"包住哪些方法"变成显式决定,两种做法都行:
- 在 `Config` 里记录本次 `Init` 配置过的命令名(`map[Scope]map[string]struct{}`),`Invoke`
里 `if !configured(cmdName) { return invoker.Invoke(ctx, invocation) }`;再提供一个
`"*"` 或 `default:` 键作为"全部方法"的显式开关(plumbing 见 `options.go:45` 那条评论)。
- 或者保留"全部方法都包",但把默认值改成等价于关闭(`Timeout` 极大 / `MaxConcurrentRequests` 极大),并在
README 顶部用醒目段落说明这会作用于该 scope 下所有方法。
无论选哪种,`README` 里"the extension adds the matching filter to the client or
server filter chain
automatically"这句都需要补上"因此**未配置的方法也会被熔断器包住**"这一句——现在读者不会意识到这件事。
##########
filter/hystrix/filter.go:
##########
@@ -96,12 +83,26 @@ type Filter struct {
// Invoke is an implementation of filter, provides Hystrix pattern latency and
fault tolerance
func (f *Filter) Invoke(ctx context.Context, invoker base.Invoker, invocation
base.Invocation) result.Result {
- cmdName := getResourceName(invoker, invocation, f.isConsumer)
+ resourceName := getResourceName(invoker, invocation)
+ scope := extension.ServerScope
+ if f.isConsumer {
+ scope = extension.ClientScope
+ }
+ cmdName := internalCommandName(scope, resourceName)
- var res result.Result
+ var (
+ res result.Result
+ resMu sync.Mutex
+ fallbackUsed bool
+ )
err := hystrix.Do(cmdName, func() error {
- res = invoker.Invoke(ctx, invocation)
- return res.Error()
+ invokeResult := invoker.Invoke(ctx, invocation)
+ resMu.Lock()
+ if !fallbackUsed {
+ res = invokeResult
+ }
+ resMu.Unlock()
+ return invokeResult.Error()
}, func(err error) error {
// Return fallback error
_, isCircuitOpen := err.(hystrix.CircuitError)
Review Comment:
🟡 **`err.(hystrix.CircuitError)` 把"超时"和"并发拒绝"都判成了"熔断打开"**
`CircuitError` 是一个**值类型**,而 hystrix-go 里超时、并发拒绝、熔断打开三者都是它:
```go
// hystrix-go/hystrix.go
type CircuitError struct{ Message string }
ErrMaxConcurrency = CircuitError{Message: "max concurrency"}
ErrCircuitOpen = CircuitError{Message: "circuit open"}
ErrTimeout = CircuitError{Message: "timeout"}
```
所以类型断言对三种情况全部为 true。实测:
```
超时场景:err="hystrix: timeout" CircuitOpen()=true
```
`CircuitOpen()` 是导出 API,调用方靠它区分"熔断打开,快速失败/降级"和"这次超时了,可以重试"。现在这个区分是失效的——业务方看到
`CircuitOpen()==true` 会误判成熔断已打开。
这是存量逻辑(本次没改这几行),但**本 PR 新加的 `filter_test.go:111`
把错误行为写进了断言**:那个用例第一个请求是干净的超时(熔断还没开),却断言 `firstError.CircuitOpen()` 为
true。现在的测试实际上在保护 bug。
**Suggestion**:
```go
// ErrTimeout / ErrCircuitOpen / ErrMaxConcurrency 都是可比较的值,直接比
isCircuitOpen := errors.Is(err, hystrix.ErrCircuitOpen)
```
顺带建议把 `FilterError` 的文档写清"`CircuitOpen()` 仅表示熔断打开",并考虑暴露 `Unwrap() error`
让调用方能拿到原始的 `ErrTimeout`/`ErrMaxConcurrency`(现在原始错误只能靠 `Error()` 字符串匹配)。改完记得把
`filter_test.go:111` 的断言改成 `false`,并在 `second` 上保留 `true`——那才是真正的熔断打开。
##########
filter/hystrix/filter.go:
##########
@@ -110,12 +111,17 @@ func (f *Filter) Invoke(ctx context.Context, invoker
base.Invoker, invocation ba
} else {
logger.Debugf("[Hystrix Filter] Hystrix fallback for
%s: %v", cmdName, err)
}
+ resMu.Lock()
+ fallbackUsed = true
res = &result.RPCResult{}
res.SetResult(nil)
res.SetError(NewHystrixFilterError(err, isCircuitOpen))
+ resMu.Unlock()
return err
})
+ resMu.Lock()
Review Comment:
💭 **末尾这个 if 两个分支完全一样,真正想防的 nil 反而没防住**
```go
resMu.Lock()
defer resMu.Unlock()
if err != nil {
return res
}
return res
```
`err` 非空与否返回值相同,等价于 `return res`。如果本意是"防御 `res == nil` 的情况",那这个写法并没有防住:真的为
nil 时照样 `return nil`,而 dubbo-go 的调用链拿到 `result.Result` 后会直接 `.Error()`,等于把 nil
解引用炸到用户侧。
理论上 `res` 为 nil 的路径确实存在:`GoC` 在 `GetCircuit` 返回 error 时会 `cmd.errChan <-
err` 直接返回,**不经过 fallback**,于是 `res` 一直是 nil。虽然 `GetCircuit` 当前实现不返回
error,但把这条当不变量写死在这里不太稳。
**Suggestion**:
```go
resMu.Lock()
defer resMu.Unlock()
if res == nil {
fallbackResult := &result.RPCResult{}
fallbackResult.SetError(NewHystrixFilterError(err, false))
return fallbackResult
}
return res
```
顺便:`resMu.Lock(); defer resMu.Unlock()` 只包了一次读,用不着 `defer`,直接
`Lock`/`Unlock` 更直白。
##########
filter/hystrix/options.go:
##########
@@ -0,0 +1,317 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package hystrix
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+
+ hystrixgo "github.com/afex/hystrix-go/hystrix"
+)
+
+const hystrixExtensionName = "hystrix"
+
+var (
+ _ extension.Config = (*Config)(nil)
+ _ extension.Option = configOption{}
+)
+
+// Config stores a Hystrix configuration for each Dubbo service method.
+// Command names are resource names in the form interface:group:version:method.
+type Config struct {
+ Commands map[string]CommandConfig `yaml:",remain"`
+
+ defaults CommandConfig
+}
+
+// CommandConfig configures one Hystrix command. Zero values use hystrix-go's
+// defaults.
+type CommandConfig struct {
+ Timeout int `yaml:"timeout"`
+ MaxConcurrentRequests int `yaml:"max-concurrent-requests"`
+ RequestVolumeThreshold int `yaml:"request-volume-threshold"`
+ SleepWindow int `yaml:"sleep-window"`
+ ErrorPercentThreshold int `yaml:"error-percent-threshold"`
+}
+
+func (c *Config) Prefix() string {
+ return hystrixExtensionName
+}
+
+func (c *Config) New() extension.Config {
+ return &Config{
+ Commands: make(map[string]CommandConfig),
+ defaults: defaultCommandConfig(),
+ }
+}
+
+func (c *Config) Init(scope extension.Scope) error {
+ if _, err := filterNameForScope(scope); err != nil {
+ return err
+ }
+
+ commandNames := make([]string, 0, len(c.Commands))
+ for commandName := range c.Commands {
+ commandNames = append(commandNames, commandName)
+ }
+ sort.Strings(commandNames)
+
+ configured := make(map[string]CommandConfig, len(commandNames))
+ for _, commandName := range commandNames {
+ if strings.TrimSpace(commandName) == "" {
+ return fmt.Errorf("hystrix command name is required")
+ }
+ if strings.TrimSpace(commandName) != commandName {
+ return fmt.Errorf("hystrix command name %q must not
contain surrounding whitespace", commandName)
+ }
+ command, err := c.defaultedCommand(c.Commands[commandName])
+ if err != nil {
+ return fmt.Errorf("hystrix command %q: %w",
commandName, err)
+ }
+ configured[internalCommandName(scope, commandName)] = command
+ }
+
+ for _, commandName := range commandNames {
Review Comment:
🟡 **`Init` 写的是进程级全局状态,但它既不可撤销也没实现 `Rollbacker`**
hystrix-go 的 `circuitSettings` 是包级 map,`ConfigureCommand` 只增不删:
```go
var circuitSettings map[string]*Settings // 全局
func ConfigureCommand(name string, config CommandConfig) {
circuitSettings[name] = &Settings{...} }
```
由此带来两个问题:
**1. `Rollback` 缺失。** core 的 `initializeConfigs` 在某个扩展 `Init` 失败时会回调已完成扩展的
`Rollback`,`Config` 接口文档也写明"Init 返回错误时必须释放已获取的资源"。`Config` 没实现 `Rollbacker`,所以:
```go
cli, err := client.NewClient(
client.WithExtension(
hystrix.WithConfig(hystrix.WithCommandName("a:::Run"),
hystrix.WithTimeout(50)),
someOtherExtensionThatFails,
),
)
// err != nil,但 dubbo:consumer:a:::Run 的 50ms 超时已经写进全局了
```
之后用不同配置重建 client,读到的是叠加后的脏状态。建议实现一个幂等的 `Rollback(scope)`:记录本次 `Init`
写过的命令名,回滚时把它们恢复成默认值(hystrix-go 没有按名删除的 API,`Flush()` 是全清且会连带清掉熔断状态,要在注释里说明这个代价)。
**2. 同进程多实例互相覆盖。** 命令名只由 `interface:group:version:method` + scope 决定,不含
client 身份。同一个进程里两个 client 给同一资源配了不同 `timeout`,后 `Init` 的赢,先建的 client
会静默改用别人的配置和别人的熔断状态。这是 hystrix-go 的固有限制,但 README 值得写一句"命令名在进程内全局唯一,多实例共享熔断状态"。
**顺带一个小的自洽性建议**:`FilterNames` 对非法 scope 返回 `nil` 而 `Init`
返回错误,同一个输入两种结论。我理解原因(core 在 `Init` 之前调 `FilterNames`,非法 scope 由 `Init`
兜底),所以建议在 `FilterNames` 上加一行注释说明这个分工,否则后来者会以为是漏了错误处理。
##########
filter/hystrix/options.go:
##########
@@ -0,0 +1,317 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package hystrix
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+
+ hystrixgo "github.com/afex/hystrix-go/hystrix"
+)
+
+const hystrixExtensionName = "hystrix"
+
+var (
+ _ extension.Config = (*Config)(nil)
+ _ extension.Option = configOption{}
+)
+
+// Config stores a Hystrix configuration for each Dubbo service method.
+// Command names are resource names in the form interface:group:version:method.
+type Config struct {
+ Commands map[string]CommandConfig `yaml:",remain"`
+
+ defaults CommandConfig
Review Comment:
🟡 **`defaults` 字段没有任何公开入口,等于不可达的抽象**
`defaults` 只在 `New()` 里被赋成 `defaultCommandConfig()`,`Apply` 里 `command =
hystrixConfig.defaults`,`defaultedCommand` 里 `defaults :=
c.defaults`——三处都读,**零处写**,也没有 YAML 键或 option 能改它。结果 `defaultedCommand` 里那个 `if
defaults == (CommandConfig{})` 分支永远不会走,`defaults` 实际是个常量。
但"给所有方法一组默认值"恰恰是用户最需要的:结合 `filter.go:91` 那条问题,一个有 200 个方法的 provider,按现在的 API
要么 200 段重复 YAML,要么接受"未配置方法继承 hystrix 默认值"。
**Suggestion**:既然 plumbing 已经写好了,把它暴露出来就行——比如允许一个保留键:
```yaml
hystrix:
consumer:
"default": # 或 "*"
timeout: 3000
max-concurrent-requests: 200
"greet.GreetService:::Greet":
timeout: 500 # 单方法覆盖
```
`Init` 里把这个键拎出来单独处理,不当作命令名,赋给
`c.defaults`。这样同时解决了"全局默认值"和"我只想配个别方法"两个需求,也顺手把 `defaultedCommand` 的 `defaults
== 零值` 分支变成真正可达的路径。
如果决定不做,建议直接删掉这个字段把 `defaultCommandConfig()` 内联,别留一个读不到写不了的状态。
##########
filter/hystrix/filter.go:
##########
@@ -96,12 +83,26 @@ type Filter struct {
// Invoke is an implementation of filter, provides Hystrix pattern latency and
fault tolerance
func (f *Filter) Invoke(ctx context.Context, invoker base.Invoker, invocation
base.Invocation) result.Result {
- cmdName := getResourceName(invoker, invocation, f.isConsumer)
+ resourceName := getResourceName(invoker, invocation)
+ scope := extension.ServerScope
+ if f.isConsumer {
+ scope = extension.ClientScope
+ }
+ cmdName := internalCommandName(scope, resourceName)
- var res result.Result
+ var (
+ res result.Result
+ resMu sync.Mutex
+ fallbackUsed bool
+ )
err := hystrix.Do(cmdName, func() error {
Review Comment:
🟡 **`hystrix.Do` 丢掉了调用方 ctx,上游取消会被记成熔断失败**
`hystrix.Do` 内部是 `DoC(context.Background(), ...)`:
```go
func Do(name string, run runFunc, fallback fallbackFunc) error {
...
return DoC(context.Background(), name, runC, fallbackC)
}
```
后果有两层:
1. 传进 `Invoke` 的 `ctx` 对 hystrix 完全不可见。调用方已经取消(客户端超时、上游断开、服务关闭),hystrix
不知道,run goroutine 会一直跑到自己的 `Timeout` 才结束——这段时间仍在占用 `MaxConcurrentRequests` 配额。
2. 更麻烦的是统计口径:run 最后返回一个 ctx 相关的错误,hystrix 记成 `failure`,计入
`ErrorPercentThreshold`。也就是说**一批上游取消足以把熔断器打开**,而实际后端完全健康。
`hystrix.DoC(ctx, ...)` 支持这个语义:`ctx.Done()` 会走 `errorWithFallback(ctx,
ctx.Err())`,事件类型记为 `context_canceled` / `context_deadline_exceeded`(hystrix-go
的 `errorWithFallback` 里就是这么分的),不计入普通失败。
**Suggestion**:
```go
err := hystrix.DoC(ctx, cmdName, func(ctx context.Context) error {
invokeResult := invoker.Invoke(ctx, invocation)
...
}, func(ctx context.Context, err error) error {
...
})
```
副作用是 `fallback` 里拿到的 error 可能是 `context.Canceled`,`CircuitOpen()` 会是
false——正好符合语义。建议补一个"ctx 取消后 `Invoke` 尽快返回且错误可辨识"的用例。
##########
filter/hystrix/filter_test.go:
##########
@@ -73,6 +75,62 @@ func TestHystrixFilter_Invoke(t *testing.T) {
assert.NoError(t, result.Error())
}
+func TestGetResourceName(t *testing.T) {
+ url, err :=
common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider")
+ require.NoError(t, err)
+ invoker := base.NewBaseInvoker(url)
+ invocation := invocation.NewRPCInvocation("TestMethod", []any{},
make(map[string]any))
+
+ assert.Equal(t, "com.ikurento.user.UserProvider:::TestMethod",
getResourceName(invoker, invocation))
+ assert.Equal(t,
"dubbo:consumer:com.ikurento.user.UserProvider:::TestMethod",
+ internalCommandName(extension.ClientScope,
getResourceName(invoker, invocation)))
+ assert.Equal(t,
"dubbo:provider:com.ikurento.user.UserProvider:::TestMethod",
+ internalCommandName(extension.ServerScope,
getResourceName(invoker, invocation)))
+}
+
+func TestHystrixFilterTimeoutAndCircuitFallback(t *testing.T) {
+ const resourceName = "hystrix-timeout-test:::Run"
+ hystrix.ConfigureCommand(internalCommandName(extension.ClientScope,
resourceName), hystrix.CommandConfig{
+ Timeout: 10,
+ MaxConcurrentRequests: 10,
+ RequestVolumeThreshold: 1,
+ SleepWindow: 60000,
+ ErrorPercentThreshold: 1,
+ })
+
+ url, err :=
common.NewURL("dubbo://127.0.0.1:20000/hystrix-timeout-test")
+ require.NoError(t, err)
+ invoker := &delayedInvoker{Invoker: base.NewBaseInvoker(url), delay: 50
* time.Millisecond}
+ hystrixFilter := &Filter{isConsumer: true}
+ invocation := invocation.NewRPCInvocation("Run", []any{},
make(map[string]any))
+
+ first := hystrixFilter.Invoke(context.Background(), invoker, invocation)
+ require.Error(t, first.Error())
+ var firstError *FilterError
+ require.True(t, errors.As(first.Error(), &firstError))
+ assert.True(t, firstError.CircuitOpen())
+
+ second := hystrixFilter.Invoke(context.Background(), invoker,
invocation)
+ require.Error(t, second.Error())
+ var secondError *FilterError
+ require.True(t, errors.As(second.Error(), &secondError))
+ assert.True(t, secondError.CircuitOpen())
+
+ // Let the timed-out invocation finish and verify it cannot replace the
+ // fallback result returned by Invoke.
+ time.Sleep(60 * time.Millisecond)
Review Comment:
💭 **这个 sleep 后面没有断言,注释声称的验证其实不成立**
```go
// Let the timed-out invocation finish and verify it cannot replace the
// fallback result returned by Invoke.
time.Sleep(60 * time.Millisecond)
```
注释说"verify it cannot replace the fallback result",但 sleep
之后什么都没有。而且即使在这里补断言也验证不到——原因是 `first` 已经是 fallback 结果的**快照**,晚到的写入改的是 `res`
这个变量,不是已返回的对象;在 `10ms` 超时 / `50ms` 延迟这组参数下,run 的写入发生在 `Invoke`
返回**之后**,两者时间上不重叠,连 `-race` 都抓不住(我本地 `-race` 跑这个用例是干净的)。
也就是说 `resMu` + `fallbackUsed` 的修复方向是对的(消除潜在并发写,并把"迟到结果不覆盖
fallback"变成不变量),但现有用例不能作为它被覆盖的证据。
**Suggestion**:二选一——
1. 删掉 sleep 和这段注释,别声称验证了没验证的东西;`resMu` 就在注释里说明是"防御超时后迟到写入",不做测试承诺;
2. 或者把 invoker 改成可控完成:`delayedInvoker` 里用 channel 阻塞,超时后**在 `Invoke`
返回之前**放行 run,人为制造真正的重叠窗口,并确保 CI 跑 `-race`。
另外两点:
- `10ms` 超时 + `50ms` 延迟在 CI 高负载时容易抖(超时没触发就直接成功),建议放宽到 `50ms` / `300ms`。
- 这个文件改了全局 `circuitSettings`(`SleepWindow: 60000`),建议加 `TestMain` 里
`hystrix.Flush()`,避免用例顺序变化后互相污染。
##########
filter/hystrix/options.go:
##########
@@ -0,0 +1,317 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package hystrix
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+
+ hystrixgo "github.com/afex/hystrix-go/hystrix"
+)
+
+const hystrixExtensionName = "hystrix"
+
+var (
+ _ extension.Config = (*Config)(nil)
+ _ extension.Option = configOption{}
+)
+
+// Config stores a Hystrix configuration for each Dubbo service method.
+// Command names are resource names in the form interface:group:version:method.
+type Config struct {
+ Commands map[string]CommandConfig `yaml:",remain"`
Review Comment:
🟡 **`yaml:",remain"` 没有 schema:任何多余的键都会变成一个"全默认"的命令,且静默生效**
mapstructure 的 `,remain` 会把 scope 块里**所有**没被结构体消费的键收进来。这意味着命令名完全不校验格式(`Init`
只查了空串和首尾空格),拼错、多写一层、字段名打错,都不会报错。
实测两种典型误配:
```yaml
hystrix:
consumer:
commands: # 用户多写了一层(README 里警告过,但没有强制)
"typo.Service:::Run": {timeout: 42}
"typo-field:::Run": {timeoutt: 42} # 字段名拼错
```
结果:
```
命令 "commands":已注册 timeout=1000ms maxConcurrent=10
命令 "typo-field:::Run":已注册 timeout=1000ms maxConcurrent=10
```
也就是说:用户写的 `timeout: 42` 一条都没生效,却凭空多了两个"全默认"的命令,其中一个甚至叫
`commands`,`ConfigureCommand` 照单全收,**零日志零报错**。这类问题在线上就是"我明明配了为什么不生效",且极难排查。
字段名拼错(`timeoutt`)这本该是 mapstructure 能报的,但 `decodeConfig` 用了默认的 `ErrorUnused:
false`,所以也被吞掉了。
**Suggestion**:在 `Init` 的校验循环里补一条格式检查,成本很低:
```go
if strings.Count(commandName, ":") != 3 {
return fmt.Errorf("hystrix command %q must be
interface:group:version:method", commandName)
}
```
这能同时挡掉 `commands`(0 个冒号)和"多写一层"的情况。另外可以考虑在 `decodeConfig` 层面单独解码 `Commands`
并打开 `ErrorUnused: true`,让字段名拼错直接报错。
##########
filter/hystrix/options.go:
##########
@@ -0,0 +1,317 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package hystrix
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+)
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common/constant"
+ "dubbo.apache.org/dubbo-go/v3/common/extension"
+
+ hystrixgo "github.com/afex/hystrix-go/hystrix"
+)
+
+const hystrixExtensionName = "hystrix"
+
+var (
+ _ extension.Config = (*Config)(nil)
+ _ extension.Option = configOption{}
+)
+
+// Config stores a Hystrix configuration for each Dubbo service method.
+// Command names are resource names in the form interface:group:version:method.
+type Config struct {
+ Commands map[string]CommandConfig `yaml:",remain"`
+
+ defaults CommandConfig
+}
+
+// CommandConfig configures one Hystrix command. Zero values use hystrix-go's
+// defaults.
+type CommandConfig struct {
+ Timeout int `yaml:"timeout"`
+ MaxConcurrentRequests int `yaml:"max-concurrent-requests"`
+ RequestVolumeThreshold int `yaml:"request-volume-threshold"`
+ SleepWindow int `yaml:"sleep-window"`
+ ErrorPercentThreshold int `yaml:"error-percent-threshold"`
+}
+
+func (c *Config) Prefix() string {
+ return hystrixExtensionName
+}
+
+func (c *Config) New() extension.Config {
+ return &Config{
+ Commands: make(map[string]CommandConfig),
+ defaults: defaultCommandConfig(),
+ }
+}
+
+func (c *Config) Init(scope extension.Scope) error {
+ if _, err := filterNameForScope(scope); err != nil {
+ return err
+ }
+
+ commandNames := make([]string, 0, len(c.Commands))
+ for commandName := range c.Commands {
+ commandNames = append(commandNames, commandName)
+ }
+ sort.Strings(commandNames)
+
+ configured := make(map[string]CommandConfig, len(commandNames))
+ for _, commandName := range commandNames {
+ if strings.TrimSpace(commandName) == "" {
+ return fmt.Errorf("hystrix command name is required")
+ }
+ if strings.TrimSpace(commandName) != commandName {
+ return fmt.Errorf("hystrix command name %q must not
contain surrounding whitespace", commandName)
+ }
+ command, err := c.defaultedCommand(c.Commands[commandName])
+ if err != nil {
+ return fmt.Errorf("hystrix command %q: %w",
commandName, err)
+ }
+ configured[internalCommandName(scope, commandName)] = command
+ }
+
+ for _, commandName := range commandNames {
+ internalName := internalCommandName(scope, commandName)
+ command := configured[internalName]
+ hystrixgo.ConfigureCommand(internalName,
hystrixgo.CommandConfig{
+ Timeout: command.Timeout,
+ MaxConcurrentRequests: command.MaxConcurrentRequests,
+ RequestVolumeThreshold: command.RequestVolumeThreshold,
+ SleepWindow: command.SleepWindow,
+ ErrorPercentThreshold: command.ErrorPercentThreshold,
+ })
+ }
+ return nil
+}
+
+func (c *Config) FilterNames(scope extension.Scope) []string {
+ filterName, err := filterNameForScope(scope)
+ if err != nil {
+ return nil
+ }
+ return []string{filterName}
+}
+
+func filterNameForScope(scope extension.Scope) (string, error) {
+ switch scope {
+ case extension.ClientScope:
+ return constant.HystrixConsumerFilterKey, nil
+ case extension.ServerScope:
+ return constant.HystrixProviderFilterKey, nil
+ default:
+ return "", fmt.Errorf("hystrix does not support scope %d",
scope)
+ }
+}
+
+func defaultCommandConfig() CommandConfig {
+ return CommandConfig{
+ Timeout: hystrixgo.DefaultTimeout,
+ MaxConcurrentRequests: hystrixgo.DefaultMaxConcurrent,
+ RequestVolumeThreshold: hystrixgo.DefaultVolumeThreshold,
+ SleepWindow: hystrixgo.DefaultSleepWindow,
+ ErrorPercentThreshold: hystrixgo.DefaultErrorPercentThreshold,
+ }
+}
+
+func (c *Config) defaultedCommand(command CommandConfig) (CommandConfig,
error) {
+ defaults := c.defaults
+ if defaults == (CommandConfig{}) {
+ defaults = defaultCommandConfig()
+ }
+ fields := []*int{
+ &command.Timeout,
+ &command.MaxConcurrentRequests,
+ &command.RequestVolumeThreshold,
+ &command.SleepWindow,
+ &command.ErrorPercentThreshold,
+ }
+ defaultFields := []int{
+ defaults.Timeout,
+ defaults.MaxConcurrentRequests,
+ defaults.RequestVolumeThreshold,
+ defaults.SleepWindow,
+ defaults.ErrorPercentThreshold,
+ }
+ fieldNames := []string{
+ "timeout",
+ "max-concurrent-requests",
+ "request-volume-threshold",
+ "sleep-window",
+ "error-percent-threshold",
+ }
+ for index, field := range fields {
+ if *field < 0 {
+ return CommandConfig{}, fmt.Errorf("%s must not be
negative", fieldNames[index])
+ }
+ if *field == 0 {
+ *field = defaultFields[index]
+ }
+ }
+ if command.ErrorPercentThreshold > 100 {
+ return CommandConfig{}, fmt.Errorf("error-percent-threshold
must be at most 100")
+ }
+ return command, nil
+}
+
+// ConfigOption changes one command in a WithConfig option.
+type ConfigOption func(*commandOptions)
+
+type commandOptions struct {
+ name string
+ values CommandConfig
+ fields uint8
+}
+
+const (
+ timeoutField uint8 = 1 << iota
+ maxConcurrentRequestsField
+ requestVolumeThresholdField
+ sleepWindowField
+ errorPercentThresholdField
+)
+
+// WithCommandName selects the service-method resource name configured by
+// WithConfig. For example: "greet.GreetService:::Greet".
+func WithCommandName(name string) ConfigOption {
+ return func(options *commandOptions) { options.name = name }
+}
+
+// WithTimeout sets the command timeout in milliseconds.
+func WithTimeout(timeout int) ConfigOption {
+ return func(options *commandOptions) {
+ options.values.Timeout = timeout
+ options.fields |= timeoutField
+ }
+}
+
+// WithMaxConcurrentRequests sets the maximum number of concurrent executions.
+func WithMaxConcurrentRequests(max int) ConfigOption {
+ return func(options *commandOptions) {
+ options.values.MaxConcurrentRequests = max
+ options.fields |= maxConcurrentRequestsField
+ }
+}
+
+// WithRequestVolumeThreshold sets the minimum request count used to evaluate
+// the circuit error percentage.
+func WithRequestVolumeThreshold(threshold int) ConfigOption {
+ return func(options *commandOptions) {
+ options.values.RequestVolumeThreshold = threshold
+ options.fields |= requestVolumeThresholdField
+ }
+}
+
+// WithSleepWindow sets the time before Hystrix allows a trial request, in
+// milliseconds.
+func WithSleepWindow(window int) ConfigOption {
+ return func(options *commandOptions) {
+ options.values.SleepWindow = window
+ options.fields |= sleepWindowField
+ }
+}
+
+// WithErrorPercentThreshold sets the error percentage that opens the circuit.
+func WithErrorPercentThreshold(threshold int) ConfigOption {
+ return func(options *commandOptions) {
+ options.values.ErrorPercentThreshold = threshold
+ options.fields |= errorPercentThresholdField
+ }
+}
+
+type configOption struct {
+ options []ConfigOption
+}
+
+func (configOption) Prefix() string {
+ return hystrixExtensionName
+}
+
+func (option configOption) Apply(config extension.Config) error {
+ hystrixConfig, ok := config.(*Config)
+ if !ok || hystrixConfig == nil {
+ return fmt.Errorf("hystrix received unexpected config type %T",
config)
+ }
+ if hystrixConfig.Commands == nil {
+ hystrixConfig.Commands = make(map[string]CommandConfig)
+ }
+
+ options := commandOptions{}
+ for index, apply := range option.options {
+ if apply == nil {
+ return fmt.Errorf("hystrix config option %d is nil",
index)
+ }
+ apply(&options)
+ }
+ if strings.TrimSpace(options.name) == "" {
Review Comment:
💭 **空的 `WithConfig()` 静默通过,但仍然会把整个 scope 的熔断打开**
`WithConfig()` 不传任何参数时 `len(option.options) == 0`,这里直接 `return
nil`。看起来是"无操作",但上层 `groupOptionsByPrefix` 已经把 `hystrix` 标记为 active:
- `FilterNames` 返回 `["hystrix_consumer"]` → core 自动把 filter 加进整个 client;
- `Init` 时 `Commands` 为空 → 一条命令都不配,但 `Invoke` 仍然对每个方法调 `hystrix.Do`;
- 于是每个方法都拿到 hystrix 默认值(1s / 10 并发),和 `filter.go:91` 是同一个后果。
也就是说一次手误(`client.WithExtension(hystrix.WithConfig())`)会让所有调用被 1s 超时和 10
并发限制住,而且没有任何提示。
**Suggestion**:空调用直接报错,比静默放行更安全:
```go
if len(option.options) == 0 {
return fmt.Errorf("hystrix WithConfig requires at least one option")
}
```
如果确实想支持"用默认值启用 hystrix",那也应该是显式 API(例如 `WithDefaultCommand()`),而不是靠空参数碰巧达成。
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]