feat: 初始化多机器人服务端项目框架
基于Go语言构建多机器人服务端框架,包含配置管理、事件总线、依赖注入等核心模块 添加项目基础结构、README、gitignore和初始代码实现
This commit is contained in:
162
internal/engine/dispatcher.go
Normal file
162
internal/engine/dispatcher.go
Normal file
@@ -0,0 +1,162 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
|
||||
"cellbot/internal/protocol"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Dispatcher 事件分发器
|
||||
// 管理事件处理器并按照优先级分发事件
|
||||
type Dispatcher struct {
|
||||
handlers []protocol.EventHandler
|
||||
middlewares []protocol.Middleware
|
||||
logger *zap.Logger
|
||||
eventBus *EventBus
|
||||
}
|
||||
|
||||
// NewDispatcher 创建事件分发器
|
||||
func NewDispatcher(eventBus *EventBus, logger *zap.Logger) *Dispatcher {
|
||||
return &Dispatcher{
|
||||
handlers: make([]protocol.EventHandler, 0),
|
||||
middlewares: make([]protocol.Middleware, 0),
|
||||
logger: logger.Named("dispatcher"),
|
||||
eventBus: eventBus,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterHandler 注册事件处理器
|
||||
func (d *Dispatcher) RegisterHandler(handler protocol.EventHandler) {
|
||||
d.handlers = append(d.handlers, handler)
|
||||
// 按优先级排序(数值越小优先级越高)
|
||||
sort.Slice(d.handlers, func(i, j int) bool {
|
||||
return d.handlers[i].Priority() < d.handlers[j].Priority()
|
||||
})
|
||||
|
||||
d.logger.Debug("Handler registered",
|
||||
zap.Int("priority", handler.Priority()),
|
||||
zap.Int("total_handlers", len(d.handlers)))
|
||||
}
|
||||
|
||||
// UnregisterHandler 取消注册事件处理器
|
||||
func (d *Dispatcher) UnregisterHandler(handler protocol.EventHandler) {
|
||||
for i, h := range d.handlers {
|
||||
if h == handler {
|
||||
d.handlers = append(d.handlers[:i], d.handlers[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
d.logger.Debug("Handler unregistered",
|
||||
zap.Int("total_handlers", len(d.handlers)))
|
||||
}
|
||||
|
||||
// RegisterMiddleware 注册中间件
|
||||
func (d *Dispatcher) RegisterMiddleware(middleware protocol.Middleware) {
|
||||
d.middlewares = append(d.middlewares, middleware)
|
||||
d.logger.Debug("Middleware registered",
|
||||
zap.Int("total_middlewares", len(d.middlewares)))
|
||||
}
|
||||
|
||||
// Start 启动分发器
|
||||
func (d *Dispatcher) Start(ctx context.Context) {
|
||||
// 订阅所有类型的事件
|
||||
for _, eventType := range []protocol.EventType{
|
||||
protocol.EventTypeMessage,
|
||||
protocol.EventTypeNotice,
|
||||
protocol.EventTypeRequest,
|
||||
protocol.EventTypeMeta,
|
||||
} {
|
||||
eventChan := d.eventBus.Subscribe(eventType, nil)
|
||||
go d.eventLoop(ctx, eventChan)
|
||||
}
|
||||
|
||||
d.logger.Info("Dispatcher started")
|
||||
}
|
||||
|
||||
// Stop 停止分发器
|
||||
func (d *Dispatcher) Stop() {
|
||||
d.logger.Info("Dispatcher stopped")
|
||||
}
|
||||
|
||||
// eventLoop 事件循环
|
||||
func (d *Dispatcher) eventLoop(ctx context.Context, eventChan chan protocol.Event) {
|
||||
for {
|
||||
select {
|
||||
case event, ok := <-eventChan:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
d.handleEvent(ctx, event)
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleEvent 处理单个事件
|
||||
func (d *Dispatcher) handleEvent(ctx context.Context, event protocol.Event) {
|
||||
d.logger.Debug("Processing event",
|
||||
zap.String("type", string(event.GetType())),
|
||||
zap.String("detail_type", event.GetDetailType()))
|
||||
|
||||
// 通过中间件链处理事件
|
||||
next := d.createHandlerChain(ctx, event)
|
||||
|
||||
// 执行中间件链
|
||||
if len(d.middlewares) > 0 {
|
||||
d.executeMiddlewares(ctx, event, func(ctx context.Context, e protocol.Event) error {
|
||||
next(ctx, e)
|
||||
return nil
|
||||
})
|
||||
} else {
|
||||
next(ctx, event)
|
||||
}
|
||||
}
|
||||
|
||||
// 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())))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// executeMiddlewares 执行中间件链
|
||||
func (d *Dispatcher) executeMiddlewares(ctx context.Context, event protocol.Event, next func(context.Context, protocol.Event) error) {
|
||||
// 从后向前构建中间件链
|
||||
handler := next
|
||||
for i := len(d.middlewares) - 1; i >= 0; i-- {
|
||||
middleware := d.middlewares[i]
|
||||
currentHandler := handler
|
||||
handler = func(ctx context.Context, e protocol.Event) error {
|
||||
if err := middleware.Process(ctx, e, currentHandler); err != nil {
|
||||
d.logger.Error("Middleware execution failed",
|
||||
zap.Error(err),
|
||||
zap.String("event_type", string(e.GetType())))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// 执行中间件链
|
||||
handler(ctx, event)
|
||||
}
|
||||
|
||||
// GetHandlerCount 获取处理器数量
|
||||
func (d *Dispatcher) GetHandlerCount() int {
|
||||
return len(d.handlers)
|
||||
}
|
||||
|
||||
// GetMiddlewareCount 获取中间件数量
|
||||
func (d *Dispatcher) GetMiddlewareCount() int {
|
||||
return len(d.middlewares)
|
||||
}
|
||||
182
internal/engine/eventbus.go
Normal file
182
internal/engine/eventbus.go
Normal file
@@ -0,0 +1,182 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"cellbot/internal/protocol"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Subscription 订阅信息
|
||||
type Subscription struct {
|
||||
ID string
|
||||
Chan chan protocol.Event
|
||||
Filter func(protocol.Event) bool
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// NewEventBus 创建事件总线
|
||||
func NewEventBus(logger *zap.Logger, bufferSize int) *EventBus {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &EventBus{
|
||||
subscriptions: make(map[string][]*Subscription),
|
||||
logger: logger.Named("eventbus"),
|
||||
eventChan: make(chan protocol.Event, bufferSize),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
// Start 启动事件总线
|
||||
func (eb *EventBus) Start() {
|
||||
eb.wg.Add(1)
|
||||
go eb.dispatch()
|
||||
eb.logger.Info("Event bus started")
|
||||
}
|
||||
|
||||
// Stop 停止事件总线
|
||||
func (eb *EventBus) Stop() {
|
||||
eb.cancel()
|
||||
eb.wg.Wait()
|
||||
close(eb.eventChan)
|
||||
eb.logger.Info("Event bus stopped")
|
||||
}
|
||||
|
||||
// Publish 发布事件
|
||||
func (eb *EventBus) Publish(event protocol.Event) {
|
||||
select {
|
||||
case eb.eventChan <- event:
|
||||
case <-eb.ctx.Done():
|
||||
eb.logger.Warn("Event bus is shutting down, event dropped",
|
||||
zap.String("type", string(event.GetType())))
|
||||
}
|
||||
}
|
||||
|
||||
// Subscribe 订阅事件
|
||||
func (eb *EventBus) Subscribe(eventType protocol.EventType, filter func(protocol.Event) bool) chan protocol.Event {
|
||||
eb.mu.Lock()
|
||||
defer eb.mu.Unlock()
|
||||
|
||||
sub := &Subscription{
|
||||
ID: generateSubscriptionID(),
|
||||
Chan: make(chan protocol.Event, 100),
|
||||
Filter: filter,
|
||||
}
|
||||
|
||||
key := string(eventType)
|
||||
eb.subscriptions[key] = append(eb.subscriptions[key], sub)
|
||||
|
||||
eb.logger.Debug("New subscription added",
|
||||
zap.String("event_type", key),
|
||||
zap.String("sub_id", sub.ID))
|
||||
|
||||
return sub.Chan
|
||||
}
|
||||
|
||||
// Unsubscribe 取消订阅
|
||||
func (eb *EventBus) Unsubscribe(eventType protocol.EventType, ch chan protocol.Event) {
|
||||
eb.mu.Lock()
|
||||
defer eb.mu.Unlock()
|
||||
|
||||
key := string(eventType)
|
||||
subs := eb.subscriptions[key]
|
||||
for i, sub := range subs {
|
||||
if sub.Chan == ch {
|
||||
close(sub.Chan)
|
||||
eb.subscriptions[key] = append(subs[:i], subs[i+1:]...)
|
||||
eb.logger.Debug("Subscription removed",
|
||||
zap.String("event_type", key),
|
||||
zap.String("sub_id", sub.ID))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dispatch 分发事件到订阅者
|
||||
func (eb *EventBus) dispatch() {
|
||||
defer eb.wg.Done()
|
||||
|
||||
for {
|
||||
select {
|
||||
case event, ok := <-eb.eventChan:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
eb.dispatchEvent(event)
|
||||
case <-eb.ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dispatchEvent 分发单个事件
|
||||
func (eb *EventBus) dispatchEvent(event protocol.Event) {
|
||||
eb.mu.RLock()
|
||||
key := string(event.GetType())
|
||||
subs := eb.subscriptions[key]
|
||||
// 复制订阅者列表避免锁竞争
|
||||
subsCopy := make([]*Subscription, len(subs))
|
||||
copy(subsCopy, subs)
|
||||
eb.mu.RUnlock()
|
||||
|
||||
for _, sub := range subsCopy {
|
||||
if sub.Filter == nil || sub.Filter(event) {
|
||||
select {
|
||||
case sub.Chan <- event:
|
||||
default:
|
||||
// 订阅者channel已满,丢弃事件
|
||||
eb.logger.Warn("Subscription channel full, event dropped",
|
||||
zap.String("sub_id", sub.ID),
|
||||
zap.String("event_type", key))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetSubscriptionCount 获取订阅者数量
|
||||
func (eb *EventBus) GetSubscriptionCount(eventType protocol.EventType) int {
|
||||
eb.mu.RLock()
|
||||
defer eb.mu.RUnlock()
|
||||
return len(eb.subscriptions[string(eventType)])
|
||||
}
|
||||
|
||||
// Clear 清空所有订阅
|
||||
func (eb *EventBus) Clear() {
|
||||
eb.mu.Lock()
|
||||
defer eb.mu.Unlock()
|
||||
|
||||
for eventType, subs := range eb.subscriptions {
|
||||
for _, sub := range subs {
|
||||
close(sub.Chan)
|
||||
}
|
||||
delete(eb.subscriptions, eventType)
|
||||
}
|
||||
eb.logger.Info("All subscriptions cleared")
|
||||
}
|
||||
|
||||
// generateSubscriptionID 生成订阅ID
|
||||
func generateSubscriptionID() string {
|
||||
return "sub-" + randomString(8)
|
||||
}
|
||||
|
||||
// randomString 生成随机字符串
|
||||
func randomString(length int) string {
|
||||
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
b := make([]byte, length)
|
||||
for i := range b {
|
||||
b[i] = charset[i%len(charset)]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
250
internal/engine/eventbus_test.go
Normal file
250
internal/engine/eventbus_test.go
Normal file
@@ -0,0 +1,250 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cellbot/internal/protocol"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func TestEventBus_PublishSubscribe(t *testing.T) {
|
||||
logger := zap.NewNop()
|
||||
eventBus := NewEventBus(logger, 100)
|
||||
eventBus.Start()
|
||||
defer eventBus.Stop()
|
||||
|
||||
// 创建测试事件
|
||||
event := &protocol.BaseEvent{
|
||||
Type: protocol.EventTypeMessage,
|
||||
DetailType: "private",
|
||||
Timestamp: time.Now().Unix(),
|
||||
SelfID: "test_bot",
|
||||
Data: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
// 订阅事件
|
||||
eventChan := eventBus.Subscribe(protocol.EventTypeMessage, nil)
|
||||
|
||||
// 发布事件
|
||||
eventBus.Publish(event)
|
||||
|
||||
// 接收事件
|
||||
select {
|
||||
case receivedEvent := <-eventChan:
|
||||
if receivedEvent.GetType() != protocol.EventTypeMessage {
|
||||
t.Errorf("Expected event type '%s', got '%s'", protocol.EventTypeMessage, receivedEvent.GetType())
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Error("Timeout waiting for event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventBus_Filter(t *testing.T) {
|
||||
logger := zap.NewNop()
|
||||
eventBus := NewEventBus(logger, 100)
|
||||
eventBus.Start()
|
||||
defer eventBus.Stop()
|
||||
|
||||
// 创建测试事件
|
||||
event1 := &protocol.BaseEvent{
|
||||
Type: protocol.EventTypeMessage,
|
||||
DetailType: "private",
|
||||
Timestamp: time.Now().Unix(),
|
||||
SelfID: "test_bot",
|
||||
Data: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
event2 := &protocol.BaseEvent{
|
||||
Type: protocol.EventTypeMessage,
|
||||
DetailType: "group",
|
||||
Timestamp: time.Now().Unix(),
|
||||
SelfID: "test_bot",
|
||||
Data: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
// 订阅并过滤:只接收private消息
|
||||
filter := func(e protocol.Event) bool {
|
||||
return e.GetDetailType() == "private"
|
||||
}
|
||||
eventChan := eventBus.Subscribe(protocol.EventTypeMessage, filter)
|
||||
|
||||
// 发布两个事件
|
||||
eventBus.Publish(event1)
|
||||
eventBus.Publish(event2)
|
||||
|
||||
// 应该只收到private消息
|
||||
select {
|
||||
case receivedEvent := <-eventChan:
|
||||
if receivedEvent.GetDetailType() != "private" {
|
||||
t.Errorf("Expected detail type 'private', got '%s'", receivedEvent.GetDetailType())
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Error("Timeout waiting for event")
|
||||
}
|
||||
|
||||
// 不应该再收到第二个事件
|
||||
select {
|
||||
case <-eventChan:
|
||||
t.Error("Should not receive group message")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
// 正确,不应该收到
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventBus_Concurrent(t *testing.T) {
|
||||
logger := zap.NewNop()
|
||||
eventBus := NewEventBus(logger, 10000)
|
||||
eventBus.Start()
|
||||
defer eventBus.Stop()
|
||||
|
||||
numSubscribers := 10
|
||||
numPublishers := 10
|
||||
numEvents := 100
|
||||
|
||||
// 创建多个订阅者
|
||||
subscribers := make([]chan protocol.Event, numSubscribers)
|
||||
for i := 0; i < numSubscribers; i++ {
|
||||
subscribers[i] = eventBus.Subscribe(protocol.EventTypeMessage, nil)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(numPublishers)
|
||||
|
||||
// 多个发布者并发发布事件
|
||||
for i := 0; i < numPublishers; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for j := 0; j < numEvents; j++ {
|
||||
event := &protocol.BaseEvent{
|
||||
Type: protocol.EventTypeMessage,
|
||||
DetailType: "private",
|
||||
Timestamp: time.Now().Unix(),
|
||||
SelfID: "test_bot",
|
||||
Data: make(map[string]interface{}),
|
||||
}
|
||||
eventBus.Publish(event)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// 验证每个订阅者都收到了事件
|
||||
for _, ch := range subscribers {
|
||||
count := 0
|
||||
for count < numPublishers*numEvents {
|
||||
select {
|
||||
case <-ch:
|
||||
count++
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
t.Errorf("Timeout waiting for events, received %d, expected %d", count, numPublishers*numEvents)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventBus_Benchmark(b *testing.B) {
|
||||
logger := zap.NewNop()
|
||||
eventBus := NewEventBus(logger, 100000)
|
||||
eventBus.Start()
|
||||
defer eventBus.Stop()
|
||||
|
||||
eventChan := eventBus.Subscribe(protocol.EventTypeMessage, nil)
|
||||
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
event := &protocol.BaseEvent{
|
||||
Type: protocol.EventTypeMessage,
|
||||
DetailType: "private",
|
||||
Timestamp: time.Now().Unix(),
|
||||
SelfID: "test_bot",
|
||||
Data: make(map[string]interface{}),
|
||||
}
|
||||
eventBus.Publish(event)
|
||||
}
|
||||
})
|
||||
|
||||
// 消耗channel避免阻塞
|
||||
go func() {
|
||||
for range eventChan {
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func TestDispatcher_HandlerPriority(t *testing.T) {
|
||||
logger := zap.NewNop()
|
||||
eventBus := NewEventBus(logger, 100)
|
||||
dispatcher := NewDispatcher(eventBus, logger)
|
||||
|
||||
// 创建测试处理器
|
||||
handlers := make([]*TestHandler, 3)
|
||||
priorities := []int{3, 1, 2}
|
||||
|
||||
for i, priority := range priorities {
|
||||
handlers[i] = &TestHandler{
|
||||
priority: priority,
|
||||
matched: false,
|
||||
executed: false,
|
||||
}
|
||||
dispatcher.RegisterHandler(handlers[i])
|
||||
}
|
||||
|
||||
// 验证处理器按优先级排序
|
||||
if dispatcher.GetHandlerCount() != 3 {
|
||||
t.Errorf("Expected 3 handlers, got %d", dispatcher.GetHandlerCount())
|
||||
}
|
||||
|
||||
event := &protocol.BaseEvent{
|
||||
Type: protocol.EventTypeMessage,
|
||||
DetailType: "private",
|
||||
Timestamp: time.Now().Unix(),
|
||||
SelfID: "test_bot",
|
||||
Data: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// 分发事件
|
||||
dispatcher.handleEvent(ctx, event)
|
||||
|
||||
// 验证处理器是否按优先级执行
|
||||
executedOrder := make([]int, 0)
|
||||
for _, handler := range handlers {
|
||||
if handler.executed {
|
||||
executedOrder = append(executedOrder, handler.priority)
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否按升序执行
|
||||
for i := 1; i < len(executedOrder); i++ {
|
||||
if executedOrder[i] < executedOrder[i-1] {
|
||||
t.Errorf("Handlers not executed in priority order: %v", executedOrder)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandler 测试处理器
|
||||
type TestHandler struct {
|
||||
priority int
|
||||
matched bool
|
||||
executed bool
|
||||
}
|
||||
|
||||
func (h *TestHandler) Handle(ctx context.Context, event protocol.Event) error {
|
||||
h.executed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *TestHandler) Priority() int {
|
||||
return h.priority
|
||||
}
|
||||
|
||||
func (h *TestHandler) Match(event protocol.Event) bool {
|
||||
h.matched = true
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user