Skip to content

fix(watchers): convert 用 comma-ok 类型断言,避免事件流 panic#249

Open
pengpeng wants to merge 1 commit intomainfrom
cursor/fix-watchers-typeassert
Open

fix(watchers): convert 用 comma-ok 类型断言,避免事件流 panic#249
pengpeng wants to merge 1 commit intomainfrom
cursor/fix-watchers-typeassert

Conversation

@pengpeng
Copy link
Copy Markdown
Member

@pengpeng pengpeng commented May 5, 2026

概要

`pkg/watchers/watchers.go` 中 `AddToWatchers` 内部的 `convert` 闭包:

```go
err := runtime.DefaultUnstructuredConverter.FromUnstructured(
obj.(*unstructured.Unstructured).Object, newObj)
```

直接做了类型断言。一旦事件流送进来的对象不是 `*unstructured.Unstructured`(典型场景:cache tombstone `DeletedFinalStateUnknown` 包装、测试注入、未来 informer 变更),整条 watch worker goroutine 会被 "interface conversion" panic 掉。`AddEventHandler` 又在 Add/Update/Delete 三处都包了这个 closure,影响面更大。

改动

改用 comma-ok 形式:

```go
u, ok := obj.(*unstructured.Unstructured)
if !ok {
err := fmt.Errorf("watchers: expected *unstructured.Unstructured, got %T", obj)
klog.Error(err)
return err
}
```

错误 log 里带上实际 %T 类型,返回 error 给上层 FilterFunc / handler,只丢弃这个事件而不是把整个 watcher 干掉。

验证方式

  • `go build ./pkg/watchers/` 通过。
  • 手工:注入一个非 `*unstructured.Unstructured` 的对象到 informer cache(或在测试里直接调 convert),watcher goroutine 不再 panic,日志看到 "watchers: expected *unstructured.Unstructured, got "。

Made with Cursor

The shared `convert` closure inside AddToWatchers did
`obj.(*unstructured.Unstructured)` directly. Anything other than
that exact concrete type (cache tombstones via
DeletedFinalStateUnknown wrappers, test injections, future
informer changes) would panic the watch worker goroutine with
"interface conversion" - and AddEventHandler installs the same
panicky closure on Add/Update/Delete.

Switch to the comma-ok form, log a clear error including the
actual %T, and return an error so FilterFunc / handlers simply
drop the event rather than the whole watcher goroutine dying.

Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant