事件
- 作者仓库星标 21,000
- 作者仓库 waveterm
- 领域
- 工程开发
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 88 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @wavetermdev · 未声明许可证
- 上下文用量评级
- 低消耗
- 接入复杂程度
- 即装即用
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- 未声明(默认跨平台)
- 运行环境要求
- 未检出明确要求
- 检测到的文件与系统行为
-
- 只读
- 允许写入 / 修改
- 网络行为
- 仅限本地
- 安装命令数
- 无(仅作为资料)
需要注意: 未声明工具权限范围;实际权限由运行环境决定。
第 1 步:定义事件常量
将事件类型常量添加到 `pkg/wps/wpstypes.go`: 命名约定:使用描述性 PascalCase 作为常量名称,并带有 `Event_` 前缀 使用小写字母和冒号作为字符串值(例如,“namespace:eventname”) 将具有相同命名空间前缀的相关事件分组
第 2 步:添加到所有事件
将新常量添加到 `pkg/wps/wpstypes.go` 中的 `AllEvents` 切片:
第 3 步:在 WaveEventDataTypes 中注册(必需)
您必须将条目添加到`pkg/tsgen/tsgenevent.go`中的`WaveEventDataTypes`。这会驱动事件的 `data` 字段的 TypeScript 类型生成: 对于值类型使用 `reflect.TypeOf(YourType{})` 对于指针类型使用 `reflect.TypeOf((*YourType)(nil))` 如果没有为事件发送数据,则使用 `nil`
步骤 4:定义事件数据结构(可选)
如果您的事件携带结构化数据,请为其定义一个类型:
第 5 步:向前端公开类型(如果需要)
如果您的事件数据类型尚未通过 RPC 调用公开,则需要将其添加到 `pkg/tsgen/tsgen.go` 以便生成 TypeScript 类型:然后运行代码生成:这将使用类型的 TypeScript 定义更新 `frontend/types/gotypes.d.ts`,确保处理这些事件时前端的类型安全。
# WPS Events Guide
## Overview
WPS (Wave PubSub) is Wave Terminal's publish-subscribe event system that enables different parts of the application to communicate asynchronously. The system uses a broker pattern to route events from publishers to subscribers based on event types and scopes.
## Key Files
- `pkg/wps/wpstypes.go` - Event type constants and data structures
- `pkg/wps/wps.go` - Broker implementation and core logic
- `pkg/wcore/wcore.go` - Example usage patterns
## Event Structure
Events in WPS have the following structure:
```go
type WaveEvent struct {
Event string `json:"event"` // Event type constant
Scopes []string `json:"scopes,omitempty"` // Optional scopes for targeted delivery
Sender string `json:"sender,omitempty"` // Optional sender identifier
Persist int `json:"persist,omitempty"` // Number of events to persist in history
Data any `json:"data,omitempty"` // Event payload
}
```
## Adding a New Event Type
### Step 1: Define the Event Constant
Add your event type constant to `pkg/wps/wpstypes.go`:
```go
const (
Event_BlockClose = "blockclose"
Event_ConnChange = "connchange"
// ... other events ...
Event_YourNewEvent = "your:newevent" // type: YourEventData (or "none" if no data)
)
```
**Naming Convention:**
- Use descriptive PascalCase for the constant name with `Event_` prefix
- Use lowercase with colons for the string value (e.g., "namespace:eventname")
- Group related events with the same namespace prefix
- Always add a `// type: <TypeName>` comment; use `// type: none` if no data is sent
### Step 2: Add to AllEvents
Add your new constant to the `AllEvents` slice in `pkg/wps/wpstypes.go`:
```go
var AllEvents []string = []string{
// ... existing events ...
Event_YourNewEvent,
}
```
### Step 3: Register in WaveEventDataTypes (REQUIRED)
You **must** add an entry to `WaveEventDataTypes` in `pkg/tsgen/tsgenevent.go`. This drives TypeScript type generation for the event's `data` field:
```go
var WaveEventDataTypes = map[string]reflect.Type{
// ... existing entries ...
wps.Event_YourNewEvent: reflect.TypeOf(YourEventData{}), // value type
// wps.Event_YourNewEvent: reflect.TypeOf((*YourEventData)(nil)), // pointer type
// wps.Event_YourNewEvent: nil, // no data (type: none)
}
```
- Use `reflect.TypeOf(YourType{})` for value types
- Use `reflect.TypeOf((*YourType)(nil))` for pointer types
- Use `nil` if no data is sent for the event
### Step 4: Define Event Data Structure (Optional)
If your event carries structured data, define a type for it:
```go
type YourEventData struct {
Field1 string `json:"field1"`
Field2 int `json:"field2"`
}
```
### Step 5: Expose Type to Frontend (If Needed)
If your event data type isn't already exposed via an RPC call, you need to add it to `pkg/tsgen/tsgen.go` so TypeScript types are generated:
```go
// add extra types to generate here
var ExtraTypes = []any{
waveobj.ORef{},
// ... other types ...
uctypes.RateLimitInfo{}, // Example: already added
YourEventData{}, // Add your new type here
}
```
Then run code generation:
```bash
task generate
```
This will update `frontend/types/gotypes.d.ts` with TypeScript definitions for your type, ensuring type safety in the frontend when handling these events.
## Publishing Events
### Basic Publishing
To publish an event, use the global broker:
```go
import "github.com/wavetermdev/waveterm/pkg/wps"
wps.Broker.Publish(wps.WaveEvent{
Event: wps.Event_YourNewEvent,
Data: yourData,
})
```
### Publishing with Scopes
Scopes allow targeted event delivery. Subscribers can filter events by scope:
```go
wps.Broker.Publish(wps.WaveEvent{
Event: wps.Event_WaveObjUpdate,
Scopes: []string{oref.String()}, // Target specific object
Data: updateData,
})
```
### Publishing in a Goroutine
To avoid blocking the caller, publish events asynchronously:
```go
go func() {
wps.Broker.Publish(wps.WaveEvent{
Event: wps.Event_YourNewEvent,
Data: data,
})
}()
```
**When to use goroutines:**
- When publishing from performance-critical code paths
- When the event is informational and doesn't need immediate delivery
- When publishing from code that holds locks (to prevent deadlocks)
### Event Persistence
Events can be persisted in memory for late subscribers:
```go
wps.Broker.Publish(wps.WaveEvent{
Event: wps.Event_YourNewEvent,
Persist: 100, // Keep last 100 events
Data: data,
})
```
## Complete Example: Rate Limit Updates
This example shows how rate limit information is published when AI chat responses include rate limit headers.
### 1. Define the Event Type
In `pkg/wps/wpstypes.go`:
```go
const (
// ... other events ...
Event_WaveAIRateLimit = "waveai:ratelimit"
)
```
### 2. Publish the Event
In `pkg/aiusechat/usechat.go`:
```go
import "github.com/wavetermdev/waveterm/pkg/wps"
func updateRateLimit(info *uctypes.RateLimitInfo) {
if info == nil {
return
}
rateLimitLock.Lock()
defer rateLimitLock.Unlock()
globalRateLimitInfo = info
// Publish event in goroutine to avoid blocking
go func() {
wps.Broker.Publish(wps.WaveEvent{
Event: wps.Event_WaveAIRateLimit,
Data: info, // RateLimitInfo struct
})
}()
}
```
### 3. Subscribe to the Event (Frontend)
In the frontend, subscribe to events via WebSocket:
```typescript
// Subscribe to rate limit updates
const subscription = {
event: "waveai:ratelimit",
allscopes: true, // Receive all rate limit events
};
```
## Subscribing to Events
### From Go Code
```go
// Subscribe to all events of a type
wps.Broker.Subscribe(routeId, wps.SubscriptionRequest{
Event: wps.Event_YourNewEvent,
AllScopes: true,
})
// Subscribe to specific scopes
wps.Broker.Subscribe(routeId, wps.SubscriptionRequest{
Event: wps.Event_WaveObjUpdate,
Scopes: []string{"workspace:123"},
})
// Unsubscribe
wps.Broker.Unsubscribe(routeId, wps.Event_YourNewEvent)
```
### Scope Matching
Scopes support wildcard matching:
- `*` matches a single scope segment
- `**` matches multiple scope segments
```go
// Subscribe to all workspace events
wps.Broker.Subscribe(routeId, wps.SubscriptionRequest{
Event: wps.Event_WaveObjUpdate,
Scopes: []string{"workspace:*"},
})
```
## Best Practices
1. **Use Namespaces**: Prefix event names with a namespace (e.g., `waveai:`, `workspace:`, `block:`)
2. **Don't Block**: Use goroutines when publishing from performance-critical code or while holding locks
3. **Type-Safe Data**: Define struct types for event data rather than using maps
4. **Scope Wisely**: Use scopes to limit event delivery and reduce unnecessary processing
5. **Document Events**: Add comments explaining when events are fired and what data they carry
6. **Consider Persistence**: Use `Persist` for events that late subscribers might need (like status updates). This is normally not used. We normally do a live RPC call to get the current value and then subscribe for updates.
## Common Event Patterns
### Status Updates
```go
wps.Broker.Publish(wps.WaveEvent{
Event: wps.Event_ControllerStatus,
Scopes: []string{blockId},
Persist: 1, // Keep only latest status
Data: statusData,
})
```
### Object Updates
```go
wps.Broker.Publish(wps.WaveEvent{
Event: wps.Event_WaveObjUpdate,
Scopes: []string{oref.String()},
Data: waveobj.WaveObjUpdate{
UpdateType: waveobj.UpdateType_Update,
OType: obj.GetOType(),
OID: waveobj.GetOID(obj),
Obj: obj,
},
})
```
### Batch Updates
```go
// Helper function for multiple updates
func (b *BrokerType) SendUpdateEvents(updates waveobj.UpdatesRtnType) {
for _, update := range updates {
b.Publish(WaveEvent{
Event: Event_WaveObjUpdate,
Scopes: []string{waveobj.MakeORef(update.OType, update.OID).String()},
Data: update,
})
}
}
```
## Debugging
To debug event flow:
1. Check broker subscription map: `wps.Broker.SubMap`
2. View persisted events: `wps.Broker.ReadEventHistory(eventType, scope, maxItems)`
3. Add logging in publish/subscribe methods
4. Monitor WebSocket traffic in browser dev tools
## Quick Reference
When adding a new event:
- [ ] Add event constant to [`pkg/wps/wpstypes.go`](pkg/wps/wpstypes.go) with a `// type: <TypeName>` comment (use `none` if no data)
- [ ] Add the constant to `AllEvents` in [`pkg/wps/wpstypes.go`](pkg/wps/wpstypes.go)
- [ ] **REQUIRED**: Add an entry to `WaveEventDataTypes` in [`pkg/tsgen/tsgenevent.go`](pkg/tsgen/tsgenevent.go) — use `nil` for events with no data
- [ ] Define event data structure (if needed)
- [ ] Add data type to `pkg/tsgen/tsgen.go` for frontend use (if not already exposed via RPC)
- [ ] Run `task generate` to update TypeScript types
- [ ] Publish events using `wps.Broker.Publish()`
- [ ] Use goroutines for non-blocking publish when appropriate
- [ ] Subscribe to events in relevant components
章节与文件索引
按说明文件中的顺序排列。
概述
关键文件
事件结构
第 1 步:定义事件常量
第 2 步:添加到所有事件
文件/命令 -> pkg/wps/wpstypes.go · pkg/wps/wps.go · pkg/wcore/wcore.go · json:"event" · json:"scopes,omitempty" · json:"sender,omitempty" · json:"persist,omitempty" · json:"data,omitempty"
内容校验值 -> aa1d1faaa66a
当前原文的自动摘译,尚未人工审校。
概述
WPS (Wave PubSub) 是 Wave Terminal 的发布-订阅事件系统,使应用程序的不同部分能够异步通信。系统使用代理模式根据事件类型和范围将事件从发布者路由到订阅者。
关键文件
pkg/wps/wpstypes.go- 事件类型常量和数据结构pkg/wps/wps.go- 代理实现和核心逻辑pkg/wcore/wcore.go- 示例使用模式事件结构
WPS 中的事件具有以下结构:
第 2 步:添加到所有事件
将新常量添加到
pkg/wps/wpstypes.go中的AllEvents切片中: