chore: update dependencies and improve bot configuration
- Upgrade Go version to 1.24.0 and update toolchain. - Update various dependencies in go.mod and go.sum, including: - Upgrade `fasthttp/websocket` to v1.5.12 - Upgrade `fsnotify/fsnotify` to v1.9.0 - Upgrade `valyala/fasthttp` to v1.58.0 - Add new dependencies for `bytedance/sonic` and `google/uuid`. - Refactor bot configuration in config.toml to support multiple bot protocols, including "milky" and "onebot11". - Modify internal configuration structures to accommodate new bot settings. - Enhance event dispatcher with metrics tracking and asynchronous processing capabilities. - Implement WebSocket connection management with heartbeat and reconnection logic. - Update server handling for bot management and event publishing.
This commit is contained in:
@@ -2,33 +2,69 @@ package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime/debug"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"cellbot/internal/protocol"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// DispatcherMetrics 分发器指标
|
||||
type DispatcherMetrics struct {
|
||||
ProcessedTotal int64 // 处理的事件总数
|
||||
SuccessTotal int64 // 成功处理的事件数
|
||||
FailedTotal int64 // 失败的事件数
|
||||
PanicTotal int64 // Panic次数
|
||||
AvgProcessTime float64 // 平均处理时间(毫秒)
|
||||
LastProcessTime int64 // 最后处理时间(Unix时间戳)
|
||||
}
|
||||
|
||||
// Dispatcher 事件分发器
|
||||
// 管理事件处理器并按照优先级分发事件
|
||||
type Dispatcher struct {
|
||||
handlers []protocol.EventHandler
|
||||
handlers []protocol.EventHandler
|
||||
middlewares []protocol.Middleware
|
||||
logger *zap.Logger
|
||||
eventBus *EventBus
|
||||
logger *zap.Logger
|
||||
eventBus *EventBus
|
||||
metrics DispatcherMetrics
|
||||
mu sync.RWMutex
|
||||
workerPool chan struct{} // 工作池,限制并发数
|
||||
maxWorkers int
|
||||
async bool // 是否异步处理
|
||||
totalTime int64 // 总处理时间(纳秒)
|
||||
}
|
||||
|
||||
// NewDispatcher 创建事件分发器
|
||||
func NewDispatcher(eventBus *EventBus, logger *zap.Logger) *Dispatcher {
|
||||
return NewDispatcherWithConfig(eventBus, logger, 100, true)
|
||||
}
|
||||
|
||||
// NewDispatcherWithConfig 使用配置创建事件分发器
|
||||
func NewDispatcherWithConfig(eventBus *EventBus, logger *zap.Logger, maxWorkers int, async bool) *Dispatcher {
|
||||
if maxWorkers <= 0 {
|
||||
maxWorkers = 100
|
||||
}
|
||||
|
||||
return &Dispatcher{
|
||||
handlers: make([]protocol.EventHandler, 0),
|
||||
middlewares: make([]protocol.Middleware, 0),
|
||||
logger: logger.Named("dispatcher"),
|
||||
eventBus: eventBus,
|
||||
workerPool: make(chan struct{}, maxWorkers),
|
||||
maxWorkers: maxWorkers,
|
||||
async: async,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterHandler 注册事件处理器
|
||||
func (d *Dispatcher) RegisterHandler(handler protocol.EventHandler) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
d.handlers = append(d.handlers, handler)
|
||||
// 按优先级排序(数值越小优先级越高)
|
||||
sort.Slice(d.handlers, func(i, j int) bool {
|
||||
@@ -42,6 +78,9 @@ func (d *Dispatcher) RegisterHandler(handler protocol.EventHandler) {
|
||||
|
||||
// UnregisterHandler 取消注册事件处理器
|
||||
func (d *Dispatcher) UnregisterHandler(handler protocol.EventHandler) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
for i, h := range d.handlers {
|
||||
if h == handler {
|
||||
d.handlers = append(d.handlers[:i], d.handlers[i+1:]...)
|
||||
@@ -54,6 +93,9 @@ func (d *Dispatcher) UnregisterHandler(handler protocol.EventHandler) {
|
||||
|
||||
// RegisterMiddleware 注册中间件
|
||||
func (d *Dispatcher) RegisterMiddleware(middleware protocol.Middleware) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
d.middlewares = append(d.middlewares, middleware)
|
||||
d.logger.Debug("Middleware registered",
|
||||
zap.Int("total_middlewares", len(d.middlewares)))
|
||||
@@ -88,7 +130,21 @@ func (d *Dispatcher) eventLoop(ctx context.Context, eventChan chan protocol.Even
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
d.handleEvent(ctx, event)
|
||||
|
||||
if d.IsAsync() {
|
||||
// 异步处理,使用工作池限制并发
|
||||
d.workerPool <- struct{}{} // 获取工作槽位
|
||||
go func(e protocol.Event) {
|
||||
defer func() {
|
||||
<-d.workerPool // 释放工作槽位
|
||||
}()
|
||||
d.handleEvent(ctx, e)
|
||||
}(event)
|
||||
} else {
|
||||
// 同步处理
|
||||
d.handleEvent(ctx, event)
|
||||
}
|
||||
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
@@ -97,47 +153,114 @@ func (d *Dispatcher) eventLoop(ctx context.Context, eventChan chan protocol.Even
|
||||
|
||||
// handleEvent 处理单个事件
|
||||
func (d *Dispatcher) handleEvent(ctx context.Context, event protocol.Event) {
|
||||
d.logger.Debug("Processing event",
|
||||
startTime := time.Now()
|
||||
|
||||
// 使用defer捕获panic
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
atomic.AddInt64(&d.metrics.PanicTotal, 1)
|
||||
atomic.AddInt64(&d.metrics.FailedTotal, 1)
|
||||
d.logger.Error("Panic in event handler",
|
||||
zap.Any("panic", r),
|
||||
zap.String("stack", string(debug.Stack())),
|
||||
zap.String("event_type", string(event.GetType())))
|
||||
}
|
||||
|
||||
// 更新指标
|
||||
duration := time.Since(startTime)
|
||||
atomic.AddInt64(&d.metrics.ProcessedTotal, 1)
|
||||
atomic.AddInt64(&d.totalTime, duration.Nanoseconds())
|
||||
atomic.StoreInt64(&d.metrics.LastProcessTime, time.Now().Unix())
|
||||
|
||||
// 计算平均处理时间
|
||||
processed := atomic.LoadInt64(&d.metrics.ProcessedTotal)
|
||||
if processed > 0 {
|
||||
avgNs := atomic.LoadInt64(&d.totalTime) / processed
|
||||
d.metrics.AvgProcessTime = float64(avgNs) / 1e6 // 转换为毫秒
|
||||
}
|
||||
}()
|
||||
|
||||
d.logger.Info("Processing event",
|
||||
zap.String("type", string(event.GetType())),
|
||||
zap.String("detail_type", event.GetDetailType()))
|
||||
zap.String("detail_type", event.GetDetailType()),
|
||||
zap.String("self_id", event.GetSelfID()))
|
||||
|
||||
// 通过中间件链处理事件
|
||||
d.mu.RLock()
|
||||
middlewares := d.middlewares
|
||||
d.mu.RUnlock()
|
||||
|
||||
next := d.createHandlerChain(ctx, event)
|
||||
|
||||
// 执行中间件链
|
||||
if len(d.middlewares) > 0 {
|
||||
d.executeMiddlewares(ctx, event, func(ctx context.Context, e protocol.Event) error {
|
||||
if len(middlewares) > 0 {
|
||||
d.executeMiddlewares(ctx, event, middlewares, func(ctx context.Context, e protocol.Event) error {
|
||||
next(ctx, e)
|
||||
return nil
|
||||
})
|
||||
} else {
|
||||
next(ctx, event)
|
||||
}
|
||||
|
||||
atomic.AddInt64(&d.metrics.SuccessTotal, 1)
|
||||
}
|
||||
|
||||
// createHandlerChain 创建处理器链
|
||||
func (d *Dispatcher) createHandlerChain(ctx context.Context, event protocol.Event) func(context.Context, protocol.Event) {
|
||||
return func(ctx context.Context, e protocol.Event) {
|
||||
for _, handler := range d.handlers {
|
||||
if handler.Match(event) {
|
||||
if err := handler.Handle(ctx, e); err != nil {
|
||||
d.logger.Error("Handler execution failed",
|
||||
zap.Error(err),
|
||||
zap.String("event_type", string(e.GetType())))
|
||||
}
|
||||
d.mu.RLock()
|
||||
handlers := make([]protocol.EventHandler, len(d.handlers))
|
||||
copy(handlers, d.handlers)
|
||||
d.mu.RUnlock()
|
||||
|
||||
for i, handler := range handlers {
|
||||
matched := handler.Match(event)
|
||||
d.logger.Info("Checking handler",
|
||||
zap.Int("handler_index", i),
|
||||
zap.Int("priority", handler.Priority()),
|
||||
zap.Bool("matched", matched))
|
||||
if matched {
|
||||
d.logger.Info("Handler matched, calling Handle",
|
||||
zap.Int("handler_index", i))
|
||||
// 使用defer捕获单个handler的panic
|
||||
func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
d.logger.Error("Panic in handler",
|
||||
zap.Any("panic", r),
|
||||
zap.String("stack", string(debug.Stack())),
|
||||
zap.String("event_type", string(e.GetType())))
|
||||
}
|
||||
}()
|
||||
|
||||
if err := handler.Handle(ctx, e); err != nil {
|
||||
d.logger.Error("Handler execution failed",
|
||||
zap.Error(err),
|
||||
zap.String("event_type", string(e.GetType())))
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// executeMiddlewares 执行中间件链
|
||||
func (d *Dispatcher) executeMiddlewares(ctx context.Context, event protocol.Event, next func(context.Context, protocol.Event) error) {
|
||||
func (d *Dispatcher) executeMiddlewares(ctx context.Context, event protocol.Event, middlewares []protocol.Middleware, next func(context.Context, protocol.Event) error) {
|
||||
// 从后向前构建中间件链
|
||||
handler := next
|
||||
for i := len(d.middlewares) - 1; i >= 0; i-- {
|
||||
middleware := d.middlewares[i]
|
||||
for i := len(middlewares) - 1; i >= 0; i-- {
|
||||
middleware := middlewares[i]
|
||||
currentHandler := handler
|
||||
handler = func(ctx context.Context, e protocol.Event) error {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
d.logger.Error("Panic in middleware",
|
||||
zap.Any("panic", r),
|
||||
zap.String("stack", string(debug.Stack())),
|
||||
zap.String("event_type", string(e.GetType())))
|
||||
}
|
||||
}()
|
||||
|
||||
if err := middleware.Process(ctx, e, currentHandler); err != nil {
|
||||
d.logger.Error("Middleware execution failed",
|
||||
zap.Error(err),
|
||||
@@ -153,10 +276,54 @@ func (d *Dispatcher) executeMiddlewares(ctx context.Context, event protocol.Even
|
||||
|
||||
// GetHandlerCount 获取处理器数量
|
||||
func (d *Dispatcher) GetHandlerCount() int {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
return len(d.handlers)
|
||||
}
|
||||
|
||||
// GetMiddlewareCount 获取中间件数量
|
||||
func (d *Dispatcher) GetMiddlewareCount() int {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
return len(d.middlewares)
|
||||
}
|
||||
|
||||
// GetMetrics 获取分发器指标
|
||||
func (d *Dispatcher) GetMetrics() DispatcherMetrics {
|
||||
return DispatcherMetrics{
|
||||
ProcessedTotal: atomic.LoadInt64(&d.metrics.ProcessedTotal),
|
||||
SuccessTotal: atomic.LoadInt64(&d.metrics.SuccessTotal),
|
||||
FailedTotal: atomic.LoadInt64(&d.metrics.FailedTotal),
|
||||
PanicTotal: atomic.LoadInt64(&d.metrics.PanicTotal),
|
||||
AvgProcessTime: d.metrics.AvgProcessTime,
|
||||
LastProcessTime: atomic.LoadInt64(&d.metrics.LastProcessTime),
|
||||
}
|
||||
}
|
||||
|
||||
// LogMetrics 记录指标日志
|
||||
func (d *Dispatcher) LogMetrics() {
|
||||
metrics := d.GetMetrics()
|
||||
|
||||
d.logger.Info("Dispatcher metrics",
|
||||
zap.Int64("processed_total", metrics.ProcessedTotal),
|
||||
zap.Int64("success_total", metrics.SuccessTotal),
|
||||
zap.Int64("failed_total", metrics.FailedTotal),
|
||||
zap.Int64("panic_total", metrics.PanicTotal),
|
||||
zap.Float64("avg_process_time_ms", metrics.AvgProcessTime),
|
||||
zap.Int("handler_count", d.GetHandlerCount()),
|
||||
zap.Int("middleware_count", d.GetMiddlewareCount()))
|
||||
}
|
||||
|
||||
// SetAsync 设置是否异步处理
|
||||
func (d *Dispatcher) SetAsync(async bool) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.async = async
|
||||
}
|
||||
|
||||
// IsAsync 是否异步处理
|
||||
func (d *Dispatcher) IsAsync() bool {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
return d.async
|
||||
}
|
||||
|
||||
@@ -2,33 +2,54 @@ package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"cellbot/internal/protocol"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Subscription 订阅信息
|
||||
type Subscription struct {
|
||||
ID string
|
||||
Chan chan protocol.Event
|
||||
Filter func(protocol.Event) bool
|
||||
ID string
|
||||
Chan chan protocol.Event
|
||||
Filter func(protocol.Event) bool
|
||||
CreatedAt time.Time
|
||||
EventCount int64 // 接收的事件数量
|
||||
}
|
||||
|
||||
// EventBusMetrics 事件总线指标
|
||||
type EventBusMetrics struct {
|
||||
PublishedTotal int64 // 发布的事件总数
|
||||
DispatchedTotal int64 // 分发的事件总数
|
||||
DroppedTotal int64 // 丢弃的事件总数
|
||||
SubscriberTotal int64 // 订阅者总数
|
||||
LastEventTime int64 // 最后一次事件时间(Unix时间戳)
|
||||
}
|
||||
|
||||
// EventBus 事件总线
|
||||
// 基于channel的高性能发布订阅实现
|
||||
type EventBus struct {
|
||||
subscriptions map[string][]*Subscription
|
||||
mu sync.RWMutex
|
||||
logger *zap.Logger
|
||||
eventChan chan protocol.Event
|
||||
wg sync.WaitGroup
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
mu sync.RWMutex
|
||||
logger *zap.Logger
|
||||
eventChan chan protocol.Event
|
||||
wg sync.WaitGroup
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
metrics EventBusMetrics
|
||||
bufferSize int
|
||||
}
|
||||
|
||||
// NewEventBus 创建事件总线
|
||||
func NewEventBus(logger *zap.Logger, bufferSize int) *EventBus {
|
||||
if bufferSize <= 0 {
|
||||
bufferSize = 1000
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &EventBus{
|
||||
subscriptions: make(map[string][]*Subscription),
|
||||
@@ -36,6 +57,7 @@ func NewEventBus(logger *zap.Logger, bufferSize int) *EventBus {
|
||||
eventChan: make(chan protocol.Event, bufferSize),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
bufferSize: bufferSize,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,31 +78,89 @@ func (eb *EventBus) Stop() {
|
||||
|
||||
// Publish 发布事件
|
||||
func (eb *EventBus) Publish(event protocol.Event) {
|
||||
eb.logger.Info("Publishing event to channel",
|
||||
zap.String("event_type", string(event.GetType())),
|
||||
zap.String("detail_type", event.GetDetailType()),
|
||||
zap.Int("channel_len", len(eb.eventChan)),
|
||||
zap.Int("channel_cap", cap(eb.eventChan)))
|
||||
|
||||
select {
|
||||
case eb.eventChan <- event:
|
||||
atomic.AddInt64(&eb.metrics.PublishedTotal, 1)
|
||||
atomic.StoreInt64(&eb.metrics.LastEventTime, time.Now().Unix())
|
||||
eb.logger.Info("Event successfully queued",
|
||||
zap.String("event_type", string(event.GetType())))
|
||||
case <-eb.ctx.Done():
|
||||
atomic.AddInt64(&eb.metrics.DroppedTotal, 1)
|
||||
eb.logger.Warn("Event bus is shutting down, event dropped",
|
||||
zap.String("type", string(event.GetType())))
|
||||
default:
|
||||
// 如果channel满了,也丢弃事件
|
||||
atomic.AddInt64(&eb.metrics.DroppedTotal, 1)
|
||||
eb.logger.Warn("Event channel full, event dropped",
|
||||
zap.String("type", string(event.GetType())),
|
||||
zap.Int("buffer_size", eb.bufferSize),
|
||||
zap.Int("channel_len", len(eb.eventChan)))
|
||||
}
|
||||
}
|
||||
|
||||
// PublishBatch 批量发布事件
|
||||
func (eb *EventBus) PublishBatch(events []protocol.Event) {
|
||||
for _, event := range events {
|
||||
eb.Publish(event)
|
||||
}
|
||||
}
|
||||
|
||||
// PublishAsync 异步发布事件(不阻塞)
|
||||
func (eb *EventBus) PublishAsync(event protocol.Event) {
|
||||
go eb.Publish(event)
|
||||
}
|
||||
|
||||
// TryPublish 尝试发布事件(非阻塞)
|
||||
func (eb *EventBus) TryPublish(event protocol.Event) bool {
|
||||
select {
|
||||
case eb.eventChan <- event:
|
||||
atomic.AddInt64(&eb.metrics.PublishedTotal, 1)
|
||||
atomic.StoreInt64(&eb.metrics.LastEventTime, time.Now().Unix())
|
||||
return true
|
||||
case <-eb.ctx.Done():
|
||||
atomic.AddInt64(&eb.metrics.DroppedTotal, 1)
|
||||
return false
|
||||
default:
|
||||
atomic.AddInt64(&eb.metrics.DroppedTotal, 1)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Subscribe 订阅事件
|
||||
func (eb *EventBus) Subscribe(eventType protocol.EventType, filter func(protocol.Event) bool) chan protocol.Event {
|
||||
return eb.SubscribeWithBuffer(eventType, filter, 100)
|
||||
}
|
||||
|
||||
// SubscribeWithBuffer 订阅事件(指定缓冲区大小)
|
||||
func (eb *EventBus) SubscribeWithBuffer(eventType protocol.EventType, filter func(protocol.Event) bool, bufferSize int) chan protocol.Event {
|
||||
eb.mu.Lock()
|
||||
defer eb.mu.Unlock()
|
||||
|
||||
if bufferSize <= 0 {
|
||||
bufferSize = 100
|
||||
}
|
||||
|
||||
sub := &Subscription{
|
||||
ID: generateSubscriptionID(),
|
||||
Chan: make(chan protocol.Event, 100),
|
||||
Filter: filter,
|
||||
ID: generateSubscriptionID(),
|
||||
Chan: make(chan protocol.Event, bufferSize),
|
||||
Filter: filter,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
key := string(eventType)
|
||||
eb.subscriptions[key] = append(eb.subscriptions[key], sub)
|
||||
atomic.AddInt64(&eb.metrics.SubscriberTotal, 1)
|
||||
|
||||
eb.logger.Debug("New subscription added",
|
||||
zap.String("event_type", key),
|
||||
zap.String("sub_id", sub.ID))
|
||||
zap.String("sub_id", sub.ID),
|
||||
zap.Int("buffer_size", bufferSize))
|
||||
|
||||
return sub.Chan
|
||||
}
|
||||
@@ -96,9 +176,13 @@ func (eb *EventBus) Unsubscribe(eventType protocol.EventType, ch chan protocol.E
|
||||
if sub.Chan == ch {
|
||||
close(sub.Chan)
|
||||
eb.subscriptions[key] = append(subs[:i], subs[i+1:]...)
|
||||
atomic.AddInt64(&eb.metrics.SubscriberTotal, -1)
|
||||
|
||||
eb.logger.Debug("Subscription removed",
|
||||
zap.String("event_type", key),
|
||||
zap.String("sub_id", sub.ID))
|
||||
zap.String("sub_id", sub.ID),
|
||||
zap.Int64("event_count", sub.EventCount),
|
||||
zap.Duration("lifetime", time.Since(sub.CreatedAt)))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -108,14 +192,20 @@ func (eb *EventBus) Unsubscribe(eventType protocol.EventType, ch chan protocol.E
|
||||
func (eb *EventBus) dispatch() {
|
||||
defer eb.wg.Done()
|
||||
|
||||
eb.logger.Info("Event bus dispatch loop started")
|
||||
|
||||
for {
|
||||
select {
|
||||
case event, ok := <-eb.eventChan:
|
||||
if !ok {
|
||||
eb.logger.Info("Event channel closed, stopping dispatch")
|
||||
return
|
||||
}
|
||||
eb.logger.Debug("Received event from channel",
|
||||
zap.String("event_type", string(event.GetType())))
|
||||
eb.dispatchEvent(event)
|
||||
case <-eb.ctx.Done():
|
||||
eb.logger.Info("Context cancelled, stopping dispatch")
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -131,18 +221,40 @@ func (eb *EventBus) dispatchEvent(event protocol.Event) {
|
||||
copy(subsCopy, subs)
|
||||
eb.mu.RUnlock()
|
||||
|
||||
eb.logger.Info("Dispatching event",
|
||||
zap.String("event_type", key),
|
||||
zap.String("detail_type", event.GetDetailType()),
|
||||
zap.Int("subscriber_count", len(subsCopy)))
|
||||
|
||||
dispatched := 0
|
||||
for _, sub := range subsCopy {
|
||||
if sub.Filter == nil || sub.Filter(event) {
|
||||
select {
|
||||
case sub.Chan <- event:
|
||||
atomic.AddInt64(&sub.EventCount, 1)
|
||||
dispatched++
|
||||
eb.logger.Debug("Event dispatched to subscriber",
|
||||
zap.String("sub_id", sub.ID))
|
||||
default:
|
||||
// 订阅者channel已满,丢弃事件
|
||||
atomic.AddInt64(&eb.metrics.DroppedTotal, 1)
|
||||
eb.logger.Warn("Subscription channel full, event dropped",
|
||||
zap.String("sub_id", sub.ID),
|
||||
zap.String("event_type", key))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if dispatched > 0 {
|
||||
atomic.AddInt64(&eb.metrics.DispatchedTotal, int64(dispatched))
|
||||
eb.logger.Info("Event dispatched successfully",
|
||||
zap.String("event_type", key),
|
||||
zap.Int("dispatched_count", dispatched))
|
||||
} else {
|
||||
eb.logger.Warn("No subscribers for event",
|
||||
zap.String("event_type", key),
|
||||
zap.String("detail_type", event.GetDetailType()))
|
||||
}
|
||||
}
|
||||
|
||||
// GetSubscriptionCount 获取订阅者数量
|
||||
@@ -166,6 +278,67 @@ func (eb *EventBus) Clear() {
|
||||
eb.logger.Info("All subscriptions cleared")
|
||||
}
|
||||
|
||||
// GetMetrics 获取事件总线指标
|
||||
func (eb *EventBus) GetMetrics() EventBusMetrics {
|
||||
return EventBusMetrics{
|
||||
PublishedTotal: atomic.LoadInt64(&eb.metrics.PublishedTotal),
|
||||
DispatchedTotal: atomic.LoadInt64(&eb.metrics.DispatchedTotal),
|
||||
DroppedTotal: atomic.LoadInt64(&eb.metrics.DroppedTotal),
|
||||
SubscriberTotal: atomic.LoadInt64(&eb.metrics.SubscriberTotal),
|
||||
LastEventTime: atomic.LoadInt64(&eb.metrics.LastEventTime),
|
||||
}
|
||||
}
|
||||
|
||||
// GetAllSubscriptions 获取所有订阅信息
|
||||
func (eb *EventBus) GetAllSubscriptions() map[string]int {
|
||||
eb.mu.RLock()
|
||||
defer eb.mu.RUnlock()
|
||||
|
||||
result := make(map[string]int)
|
||||
for eventType, subs := range eb.subscriptions {
|
||||
result[eventType] = len(subs)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// GetBufferUsage 获取缓冲区使用情况
|
||||
func (eb *EventBus) GetBufferUsage() float64 {
|
||||
return float64(len(eb.eventChan)) / float64(eb.bufferSize)
|
||||
}
|
||||
|
||||
// IsHealthy 检查事件总线健康状态
|
||||
func (eb *EventBus) IsHealthy() bool {
|
||||
// 检查缓冲区使用率是否过高
|
||||
if eb.GetBufferUsage() > 0.9 {
|
||||
return false
|
||||
}
|
||||
|
||||
// 检查是否有过多的丢弃事件
|
||||
metrics := eb.GetMetrics()
|
||||
if metrics.PublishedTotal > 0 {
|
||||
dropRate := float64(metrics.DroppedTotal) / float64(metrics.PublishedTotal)
|
||||
if dropRate > 0.1 { // 丢弃率超过10%
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// LogMetrics 记录指标日志
|
||||
func (eb *EventBus) LogMetrics() {
|
||||
metrics := eb.GetMetrics()
|
||||
subs := eb.GetAllSubscriptions()
|
||||
|
||||
eb.logger.Info("EventBus metrics",
|
||||
zap.Int64("published_total", metrics.PublishedTotal),
|
||||
zap.Int64("dispatched_total", metrics.DispatchedTotal),
|
||||
zap.Int64("dropped_total", metrics.DroppedTotal),
|
||||
zap.Int64("subscriber_total", metrics.SubscriberTotal),
|
||||
zap.Float64("buffer_usage", eb.GetBufferUsage()),
|
||||
zap.Any("subscriptions", subs))
|
||||
}
|
||||
|
||||
// generateSubscriptionID 生成订阅ID
|
||||
func generateSubscriptionID() string {
|
||||
return "sub-" + randomString(8)
|
||||
@@ -173,10 +346,15 @@ func generateSubscriptionID() string {
|
||||
|
||||
// randomString 生成随机字符串
|
||||
func randomString(length int) string {
|
||||
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
b := make([]byte, length)
|
||||
for i := range b {
|
||||
b[i] = charset[i%len(charset)]
|
||||
b := make([]byte, length/2)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
// 降级到简单实现
|
||||
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
result := make([]byte, length)
|
||||
for i := range result {
|
||||
result[i] = charset[i%len(charset)]
|
||||
}
|
||||
return string(result)
|
||||
}
|
||||
return string(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
312
internal/engine/handler.go
Normal file
312
internal/engine/handler.go
Normal file
@@ -0,0 +1,312 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"cellbot/internal/protocol"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// BaseHandler 基础处理器
|
||||
type BaseHandler struct {
|
||||
priority int
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewBaseHandler 创建基础处理器
|
||||
func NewBaseHandler(priority int, logger *zap.Logger) *BaseHandler {
|
||||
return &BaseHandler{
|
||||
priority: priority,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 获取优先级
|
||||
func (h *BaseHandler) Priority() int {
|
||||
return h.priority
|
||||
}
|
||||
|
||||
// MessageHandler 消息处理器
|
||||
type MessageHandler struct {
|
||||
*BaseHandler
|
||||
matchFunc func(protocol.Event) bool
|
||||
handleFunc func(context.Context, protocol.Event) error
|
||||
}
|
||||
|
||||
// NewMessageHandler 创建消息处理器
|
||||
func NewMessageHandler(priority int, logger *zap.Logger, matchFunc func(protocol.Event) bool, handleFunc func(context.Context, protocol.Event) error) *MessageHandler {
|
||||
return &MessageHandler{
|
||||
BaseHandler: NewBaseHandler(priority, logger.Named("handler.message")),
|
||||
matchFunc: matchFunc,
|
||||
handleFunc: handleFunc,
|
||||
}
|
||||
}
|
||||
|
||||
// Match 判断是否匹配事件
|
||||
func (h *MessageHandler) Match(event protocol.Event) bool {
|
||||
if event.GetType() != protocol.EventTypeMessage {
|
||||
return false
|
||||
}
|
||||
|
||||
if h.matchFunc != nil {
|
||||
return h.matchFunc(event)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Handle 处理事件
|
||||
func (h *MessageHandler) Handle(ctx context.Context, event protocol.Event) error {
|
||||
if h.handleFunc != nil {
|
||||
return h.handleFunc(ctx, event)
|
||||
}
|
||||
|
||||
h.logger.Info("Message event handled",
|
||||
zap.String("detail_type", event.GetDetailType()),
|
||||
zap.String("self_id", event.GetSelfID()))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CommandHandler 命令处理器
|
||||
type CommandHandler struct {
|
||||
*BaseHandler
|
||||
prefix string
|
||||
commands map[string]func(context.Context, protocol.Event, []string) error
|
||||
}
|
||||
|
||||
// NewCommandHandler 创建命令处理器
|
||||
func NewCommandHandler(priority int, logger *zap.Logger, prefix string) *CommandHandler {
|
||||
return &CommandHandler{
|
||||
BaseHandler: NewBaseHandler(priority, logger.Named("handler.command")),
|
||||
prefix: prefix,
|
||||
commands: make(map[string]func(context.Context, protocol.Event, []string) error),
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterCommand 注册命令
|
||||
func (h *CommandHandler) RegisterCommand(cmd string, handler func(context.Context, protocol.Event, []string) error) {
|
||||
h.commands[cmd] = handler
|
||||
h.logger.Debug("Command registered", zap.String("command", cmd))
|
||||
}
|
||||
|
||||
// Match 判断是否匹配事件
|
||||
func (h *CommandHandler) Match(event protocol.Event) bool {
|
||||
if event.GetType() != protocol.EventTypeMessage {
|
||||
return false
|
||||
}
|
||||
|
||||
data := event.GetData()
|
||||
rawMessage, ok := data["raw_message"].(string)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
return strings.HasPrefix(rawMessage, h.prefix)
|
||||
}
|
||||
|
||||
// Handle 处理事件
|
||||
func (h *CommandHandler) Handle(ctx context.Context, event protocol.Event) error {
|
||||
data := event.GetData()
|
||||
rawMessage, ok := data["raw_message"].(string)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 去除前缀
|
||||
cmdText := strings.TrimPrefix(rawMessage, h.prefix)
|
||||
cmdText = strings.TrimSpace(cmdText)
|
||||
|
||||
// 解析命令和参数
|
||||
parts := strings.Fields(cmdText)
|
||||
if len(parts) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
cmd := parts[0]
|
||||
args := parts[1:]
|
||||
|
||||
// 查找命令处理器
|
||||
handler, exists := h.commands[cmd]
|
||||
if !exists {
|
||||
h.logger.Debug("Unknown command", zap.String("command", cmd))
|
||||
return nil
|
||||
}
|
||||
|
||||
h.logger.Info("Executing command",
|
||||
zap.String("command", cmd),
|
||||
zap.Strings("args", args))
|
||||
|
||||
return handler(ctx, event, args)
|
||||
}
|
||||
|
||||
// KeywordHandler 关键词处理器
|
||||
type KeywordHandler struct {
|
||||
*BaseHandler
|
||||
keywords map[string]func(context.Context, protocol.Event) error
|
||||
caseSensitive bool
|
||||
}
|
||||
|
||||
// NewKeywordHandler 创建关键词处理器
|
||||
func NewKeywordHandler(priority int, logger *zap.Logger, caseSensitive bool) *KeywordHandler {
|
||||
return &KeywordHandler{
|
||||
BaseHandler: NewBaseHandler(priority, logger.Named("handler.keyword")),
|
||||
keywords: make(map[string]func(context.Context, protocol.Event) error),
|
||||
caseSensitive: caseSensitive,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterKeyword 注册关键词
|
||||
func (h *KeywordHandler) RegisterKeyword(keyword string, handler func(context.Context, protocol.Event) error) {
|
||||
if !h.caseSensitive {
|
||||
keyword = strings.ToLower(keyword)
|
||||
}
|
||||
h.keywords[keyword] = handler
|
||||
h.logger.Debug("Keyword registered", zap.String("keyword", keyword))
|
||||
}
|
||||
|
||||
// Match 判断是否匹配事件
|
||||
func (h *KeywordHandler) Match(event protocol.Event) bool {
|
||||
if event.GetType() != protocol.EventTypeMessage {
|
||||
return false
|
||||
}
|
||||
|
||||
data := event.GetData()
|
||||
rawMessage, ok := data["raw_message"].(string)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
if !h.caseSensitive {
|
||||
rawMessage = strings.ToLower(rawMessage)
|
||||
}
|
||||
|
||||
for keyword := range h.keywords {
|
||||
if strings.Contains(rawMessage, keyword) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Handle 处理事件
|
||||
func (h *KeywordHandler) Handle(ctx context.Context, event protocol.Event) error {
|
||||
data := event.GetData()
|
||||
rawMessage, ok := data["raw_message"].(string)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !h.caseSensitive {
|
||||
rawMessage = strings.ToLower(rawMessage)
|
||||
}
|
||||
|
||||
// 执行所有匹配的关键词处理器
|
||||
for keyword, handler := range h.keywords {
|
||||
if strings.Contains(rawMessage, keyword) {
|
||||
h.logger.Info("Keyword matched",
|
||||
zap.String("keyword", keyword))
|
||||
|
||||
if err := handler(ctx, event); err != nil {
|
||||
h.logger.Error("Keyword handler failed",
|
||||
zap.String("keyword", keyword),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NoticeHandler 通知处理器
|
||||
type NoticeHandler struct {
|
||||
*BaseHandler
|
||||
noticeTypes map[string]func(context.Context, protocol.Event) error
|
||||
}
|
||||
|
||||
// NewNoticeHandler 创建通知处理器
|
||||
func NewNoticeHandler(priority int, logger *zap.Logger) *NoticeHandler {
|
||||
return &NoticeHandler{
|
||||
BaseHandler: NewBaseHandler(priority, logger.Named("handler.notice")),
|
||||
noticeTypes: make(map[string]func(context.Context, protocol.Event) error),
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterNoticeType 注册通知类型处理器
|
||||
func (h *NoticeHandler) RegisterNoticeType(noticeType string, handler func(context.Context, protocol.Event) error) {
|
||||
h.noticeTypes[noticeType] = handler
|
||||
h.logger.Debug("Notice type registered", zap.String("notice_type", noticeType))
|
||||
}
|
||||
|
||||
// Match 判断是否匹配事件
|
||||
func (h *NoticeHandler) Match(event protocol.Event) bool {
|
||||
if event.GetType() != protocol.EventTypeNotice {
|
||||
return false
|
||||
}
|
||||
|
||||
detailType := event.GetDetailType()
|
||||
_, exists := h.noticeTypes[detailType]
|
||||
return exists
|
||||
}
|
||||
|
||||
// Handle 处理事件
|
||||
func (h *NoticeHandler) Handle(ctx context.Context, event protocol.Event) error {
|
||||
detailType := event.GetDetailType()
|
||||
handler, exists := h.noticeTypes[detailType]
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
h.logger.Info("Notice event handled",
|
||||
zap.String("notice_type", detailType))
|
||||
|
||||
return handler(ctx, event)
|
||||
}
|
||||
|
||||
// RequestHandler 请求处理器
|
||||
type RequestHandler struct {
|
||||
*BaseHandler
|
||||
requestTypes map[string]func(context.Context, protocol.Event) error
|
||||
}
|
||||
|
||||
// NewRequestHandler 创建请求处理器
|
||||
func NewRequestHandler(priority int, logger *zap.Logger) *RequestHandler {
|
||||
return &RequestHandler{
|
||||
BaseHandler: NewBaseHandler(priority, logger.Named("handler.request")),
|
||||
requestTypes: make(map[string]func(context.Context, protocol.Event) error),
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterRequestType 注册请求类型处理器
|
||||
func (h *RequestHandler) RegisterRequestType(requestType string, handler func(context.Context, protocol.Event) error) {
|
||||
h.requestTypes[requestType] = handler
|
||||
h.logger.Debug("Request type registered", zap.String("request_type", requestType))
|
||||
}
|
||||
|
||||
// Match 判断是否匹配事件
|
||||
func (h *RequestHandler) Match(event protocol.Event) bool {
|
||||
if event.GetType() != protocol.EventTypeRequest {
|
||||
return false
|
||||
}
|
||||
|
||||
detailType := event.GetDetailType()
|
||||
_, exists := h.requestTypes[detailType]
|
||||
return exists
|
||||
}
|
||||
|
||||
// Handle 处理事件
|
||||
func (h *RequestHandler) Handle(ctx context.Context, event protocol.Event) error {
|
||||
detailType := event.GetDetailType()
|
||||
handler, exists := h.requestTypes[detailType]
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
h.logger.Info("Request event handled",
|
||||
zap.String("request_type", detailType))
|
||||
|
||||
return handler(ctx, event)
|
||||
}
|
||||
283
internal/engine/middleware.go
Normal file
283
internal/engine/middleware.go
Normal file
@@ -0,0 +1,283 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"cellbot/internal/protocol"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
// LoggingMiddleware 日志中间件
|
||||
type LoggingMiddleware struct {
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewLoggingMiddleware 创建日志中间件
|
||||
func NewLoggingMiddleware(logger *zap.Logger) *LoggingMiddleware {
|
||||
return &LoggingMiddleware{
|
||||
logger: logger.Named("middleware.logging"),
|
||||
}
|
||||
}
|
||||
|
||||
// Process 处理事件
|
||||
func (m *LoggingMiddleware) Process(ctx context.Context, event protocol.Event, next func(context.Context, protocol.Event) error) error {
|
||||
start := time.Now()
|
||||
|
||||
m.logger.Info("Event received",
|
||||
zap.String("type", string(event.GetType())),
|
||||
zap.String("detail_type", event.GetDetailType()),
|
||||
zap.String("self_id", event.GetSelfID()))
|
||||
|
||||
err := next(ctx, event)
|
||||
|
||||
m.logger.Info("Event processed",
|
||||
zap.String("type", string(event.GetType())),
|
||||
zap.Duration("duration", time.Since(start)),
|
||||
zap.Error(err))
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// RateLimitMiddleware 限流中间件
|
||||
type RateLimitMiddleware struct {
|
||||
limiters map[string]*rate.Limiter
|
||||
mu sync.RWMutex
|
||||
logger *zap.Logger
|
||||
rps int // 每秒请求数
|
||||
burst int // 突发容量
|
||||
}
|
||||
|
||||
// NewRateLimitMiddleware 创建限流中间件
|
||||
func NewRateLimitMiddleware(logger *zap.Logger, rps, burst int) *RateLimitMiddleware {
|
||||
if rps <= 0 {
|
||||
rps = 100
|
||||
}
|
||||
if burst <= 0 {
|
||||
burst = rps * 2
|
||||
}
|
||||
|
||||
return &RateLimitMiddleware{
|
||||
limiters: make(map[string]*rate.Limiter),
|
||||
logger: logger.Named("middleware.ratelimit"),
|
||||
rps: rps,
|
||||
burst: burst,
|
||||
}
|
||||
}
|
||||
|
||||
// Process 处理事件
|
||||
func (m *RateLimitMiddleware) Process(ctx context.Context, event protocol.Event, next func(context.Context, protocol.Event) error) error {
|
||||
// 根据事件类型获取限流器
|
||||
key := string(event.GetType())
|
||||
|
||||
m.mu.RLock()
|
||||
limiter, exists := m.limiters[key]
|
||||
m.mu.RUnlock()
|
||||
|
||||
if !exists {
|
||||
m.mu.Lock()
|
||||
limiter = rate.NewLimiter(rate.Limit(m.rps), m.burst)
|
||||
m.limiters[key] = limiter
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// 等待令牌
|
||||
if err := limiter.Wait(ctx); err != nil {
|
||||
m.logger.Warn("Rate limit exceeded",
|
||||
zap.String("event_type", key),
|
||||
zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
return next(ctx, event)
|
||||
}
|
||||
|
||||
// RetryMiddleware 重试中间件
|
||||
type RetryMiddleware struct {
|
||||
logger *zap.Logger
|
||||
maxRetries int
|
||||
delay time.Duration
|
||||
}
|
||||
|
||||
// NewRetryMiddleware 创建重试中间件
|
||||
func NewRetryMiddleware(logger *zap.Logger, maxRetries int, delay time.Duration) *RetryMiddleware {
|
||||
if maxRetries <= 0 {
|
||||
maxRetries = 3
|
||||
}
|
||||
if delay <= 0 {
|
||||
delay = time.Second
|
||||
}
|
||||
|
||||
return &RetryMiddleware{
|
||||
logger: logger.Named("middleware.retry"),
|
||||
maxRetries: maxRetries,
|
||||
delay: delay,
|
||||
}
|
||||
}
|
||||
|
||||
// Process 处理事件
|
||||
func (m *RetryMiddleware) Process(ctx context.Context, event protocol.Event, next func(context.Context, protocol.Event) error) error {
|
||||
var err error
|
||||
for i := 0; i <= m.maxRetries; i++ {
|
||||
if i > 0 {
|
||||
m.logger.Info("Retrying event",
|
||||
zap.String("event_type", string(event.GetType())),
|
||||
zap.Int("attempt", i),
|
||||
zap.Int("max_retries", m.maxRetries))
|
||||
|
||||
// 指数退避
|
||||
backoff := m.delay * time.Duration(1<<uint(i-1))
|
||||
select {
|
||||
case <-time.After(backoff):
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
err = next(ctx, event)
|
||||
if err == nil {
|
||||
if i > 0 {
|
||||
m.logger.Info("Event succeeded after retry",
|
||||
zap.String("event_type", string(event.GetType())),
|
||||
zap.Int("attempts", i+1))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
m.logger.Warn("Event processing failed",
|
||||
zap.String("event_type", string(event.GetType())),
|
||||
zap.Int("attempt", i+1),
|
||||
zap.Error(err))
|
||||
}
|
||||
|
||||
m.logger.Error("Event failed after all retries",
|
||||
zap.String("event_type", string(event.GetType())),
|
||||
zap.Int("total_attempts", m.maxRetries+1),
|
||||
zap.Error(err))
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// TimeoutMiddleware 超时中间件
|
||||
type TimeoutMiddleware struct {
|
||||
logger *zap.Logger
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
// NewTimeoutMiddleware 创建超时中间件
|
||||
func NewTimeoutMiddleware(logger *zap.Logger, timeout time.Duration) *TimeoutMiddleware {
|
||||
if timeout <= 0 {
|
||||
timeout = 30 * time.Second
|
||||
}
|
||||
|
||||
return &TimeoutMiddleware{
|
||||
logger: logger.Named("middleware.timeout"),
|
||||
timeout: timeout,
|
||||
}
|
||||
}
|
||||
|
||||
// Process 处理事件
|
||||
func (m *TimeoutMiddleware) Process(ctx context.Context, event protocol.Event, next func(context.Context, protocol.Event) error) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, m.timeout)
|
||||
defer cancel()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- next(ctx, event)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
m.logger.Warn("Event processing timeout",
|
||||
zap.String("event_type", string(event.GetType())),
|
||||
zap.Duration("timeout", m.timeout))
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// RecoveryMiddleware 恢复中间件(捕获panic)
|
||||
type RecoveryMiddleware struct {
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewRecoveryMiddleware 创建恢复中间件
|
||||
func NewRecoveryMiddleware(logger *zap.Logger) *RecoveryMiddleware {
|
||||
return &RecoveryMiddleware{
|
||||
logger: logger.Named("middleware.recovery"),
|
||||
}
|
||||
}
|
||||
|
||||
// Process 处理事件
|
||||
func (m *RecoveryMiddleware) Process(ctx context.Context, event protocol.Event, next func(context.Context, protocol.Event) error) (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
m.logger.Error("Recovered from panic",
|
||||
zap.Any("panic", r),
|
||||
zap.String("event_type", string(event.GetType())))
|
||||
err = protocol.ErrNotImplemented // 或者自定义错误
|
||||
}
|
||||
}()
|
||||
|
||||
return next(ctx, event)
|
||||
}
|
||||
|
||||
// MetricsMiddleware 指标中间件
|
||||
type MetricsMiddleware struct {
|
||||
logger *zap.Logger
|
||||
eventCounts map[string]int64
|
||||
eventTimes map[string]time.Duration
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewMetricsMiddleware 创建指标中间件
|
||||
func NewMetricsMiddleware(logger *zap.Logger) *MetricsMiddleware {
|
||||
return &MetricsMiddleware{
|
||||
logger: logger.Named("middleware.metrics"),
|
||||
eventCounts: make(map[string]int64),
|
||||
eventTimes: make(map[string]time.Duration),
|
||||
}
|
||||
}
|
||||
|
||||
// Process 处理事件
|
||||
func (m *MetricsMiddleware) Process(ctx context.Context, event protocol.Event, next func(context.Context, protocol.Event) error) error {
|
||||
start := time.Now()
|
||||
err := next(ctx, event)
|
||||
duration := time.Since(start)
|
||||
|
||||
eventType := string(event.GetType())
|
||||
|
||||
m.mu.Lock()
|
||||
m.eventCounts[eventType]++
|
||||
m.eventTimes[eventType] += duration
|
||||
m.mu.Unlock()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetMetrics 获取指标
|
||||
func (m *MetricsMiddleware) GetMetrics() map[string]interface{} {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
metrics := make(map[string]interface{})
|
||||
for eventType, count := range m.eventCounts {
|
||||
avgTime := m.eventTimes[eventType] / time.Duration(count)
|
||||
metrics[eventType] = map[string]interface{}{
|
||||
"count": count,
|
||||
"avg_time": avgTime.String(),
|
||||
}
|
||||
}
|
||||
|
||||
return metrics
|
||||
}
|
||||
|
||||
// LogMetrics 记录指标
|
||||
func (m *MetricsMiddleware) LogMetrics() {
|
||||
metrics := m.GetMetrics()
|
||||
m.logger.Info("Event metrics", zap.Any("metrics", metrics))
|
||||
}
|
||||
Reference in New Issue
Block a user