refactor: stabilize runtime and unify config

This commit is contained in:
lpf
2026-03-14 21:40:12 +08:00
parent 60eee65fec
commit 341e578c9f
75 changed files with 3081 additions and 1627 deletions

View File

@@ -28,25 +28,13 @@ func NewMessageBus() *MessageBus {
func (mb *MessageBus) PublishInbound(msg InboundMessage) {
mb.mu.RLock()
defer mb.mu.RUnlock()
if mb.closed {
mb.mu.RUnlock()
return
}
ch := mb.inbound
mb.mu.RUnlock()
defer func() {
if recover() != nil {
logger.WarnCF("bus", logger.C0129, map[string]interface{}{
logger.FieldChannel: msg.Channel,
logger.FieldChatID: msg.ChatID,
"session_key": msg.SessionKey,
})
}
}()
select {
case ch <- msg:
case mb.inbound <- msg:
case <-time.After(queueWriteTimeout):
logger.ErrorCF("bus", logger.C0130, map[string]interface{}{
logger.FieldChannel: msg.Channel,
@@ -67,24 +55,13 @@ func (mb *MessageBus) ConsumeInbound(ctx context.Context) (InboundMessage, bool)
func (mb *MessageBus) PublishOutbound(msg OutboundMessage) {
mb.mu.RLock()
defer mb.mu.RUnlock()
if mb.closed {
mb.mu.RUnlock()
return
}
ch := mb.outbound
mb.mu.RUnlock()
defer func() {
if recover() != nil {
logger.WarnCF("bus", logger.C0131, map[string]interface{}{
logger.FieldChannel: msg.Channel,
logger.FieldChatID: msg.ChatID,
})
}
}()
select {
case ch <- msg:
case mb.outbound <- msg:
case <-time.After(queueWriteTimeout):
logger.ErrorCF("bus", logger.C0132, map[string]interface{}{
logger.FieldChannel: msg.Channel,

61
pkg/bus/bus_test.go Normal file
View File

@@ -0,0 +1,61 @@
package bus
import (
"context"
"sync"
"testing"
"time"
)
func TestMessageBusPublishAfterCloseDoesNotPanic(t *testing.T) {
t.Parallel()
mb := NewMessageBus()
mb.Close()
done := make(chan struct{})
go func() {
defer close(done)
mb.PublishInbound(InboundMessage{Channel: "test"})
mb.PublishOutbound(OutboundMessage{Channel: "test"})
}()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("publish after close blocked")
}
}
func TestMessageBusCloseWhilePublishingDoesNotPanic(t *testing.T) {
t.Parallel()
mb := NewMessageBus()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
for {
if _, ok := mb.ConsumeInbound(ctx); !ok {
return
}
}
}()
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 50; j++ {
mb.PublishInbound(InboundMessage{Channel: "test"})
mb.PublishOutbound(OutboundMessage{Channel: "test"})
}
}()
}
time.Sleep(20 * time.Millisecond)
mb.Close()
cancel()
wg.Wait()
}