chore: 初始化提交
This commit is contained in:
commit
943c0a0e5a
71 files changed
+7122
No files matched your search
@@ -0,0 +1,61 @@
|
||||
package sse
|
||||
|
||||
import "sync"
|
||||
|
||||
// 事件类型固定为以下取值,前端按 taskId 归并。
|
||||
const (
|
||||
EventTaskCreated = "task.created"
|
||||
EventTaskProgress = "task.progress"
|
||||
EventTaskFinished = "task.finished"
|
||||
EventTaskFailed = "task.failed"
|
||||
)
|
||||
|
||||
// Event SSE 事件的统一格式。
|
||||
type Event struct {
|
||||
Type string `json:"type"`
|
||||
TaskID string `json:"taskId"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
// Broker 进程内事件广播。订阅者过慢时直接丢弃事件,避免阻塞 worker。
|
||||
type Broker struct {
|
||||
mu sync.RWMutex
|
||||
subscribers map[chan Event]struct{}
|
||||
}
|
||||
|
||||
func NewBroker() *Broker {
|
||||
return &Broker{subscribers: make(map[chan Event]struct{})}
|
||||
}
|
||||
|
||||
// Subscribe 返回事件通道与取消函数。
|
||||
func (b *Broker) Subscribe() (<-chan Event, func()) {
|
||||
ch := make(chan Event, 16)
|
||||
|
||||
b.mu.Lock()
|
||||
b.subscribers[ch] = struct{}{}
|
||||
b.mu.Unlock()
|
||||
|
||||
var once sync.Once
|
||||
cancel := func() {
|
||||
once.Do(func() {
|
||||
b.mu.Lock()
|
||||
delete(b.subscribers, ch)
|
||||
b.mu.Unlock()
|
||||
close(ch)
|
||||
})
|
||||
}
|
||||
|
||||
return ch, cancel
|
||||
}
|
||||
|
||||
func (b *Broker) Publish(event Event) {
|
||||
b.mu.RLock()
|
||||
defer b.mu.RUnlock()
|
||||
|
||||
for ch := range b.subscribers {
|
||||
select {
|
||||
case ch <- event:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user