fix(telemetry): 指标写入对空接收者安全,修 nil 解引用 panic

metrics 包的全局指标(UpstreamTotal 等)默认是 nil,只有 main 调过 metrics.Init() 之后才有值。任何不经过 main 的调用路径都会在 controller/tts.go -> adapter/volcano/synthesis.go -> metrics.AdapterRecorder 处 nil 解引用,整个进程崩掉。

生产路径本来没问题(二进制一定先 Init),但这类崩溃只在运行时暴露,且漏掉指标初始化属于很容易踩的装配错误,不该以 panic 收场。

改动: Counter.Add / Gauge.Set / Gauge.Add / Histogram.Observe 增加空接收者判断,nil 时静默忽略(与 noop 语义一致);在包注释里写成显式设计约定,避免以后被当成冗余代码删掉。
This commit is contained in:
sun
2026-10-03 16:13:47 +08:00
parent 21e1fd1fbb
commit 1e2be0cd5b
4 changed files with 23 additions and 2 deletions
+5 -1
View File
@@ -36,8 +36,12 @@ func newCounter(name, help string, labelNames []string) *Counter {
func (c *Counter) Inc(labels Labels) { c.Add(1, labels) }
// Add 累加 v(v 必须 >= 0)。
//
// 空接收者(nil *Counter)安全:未初始化的全局指标(如 metrics.Init() 尚未调用时
// 的 metrics.UpstreamTotal)会被静默忽略,而不是 panic。
// 这让"直接调用 handler"的测试/复用场景不会因为漏掉指标初始化而崩溃。
func (c *Counter) Add(v float64, labels Labels) {
if v < 0 {
if c == nil || v < 0 {
return
}
child := c.getOrCreate(labels)