- plugins/channels/kook: config/adapter/gateway/websocket/send/message/errors — 实现 PlatformAdapter 13方法 - WS 有状态网关: 取gateway地址→连WS→信令0/1/2/3/4/6 + 30s心跳/6s超时 + resume(拼接sn/session_id) + 指数退避重连 - 收事件: 信令0 → UnifiedMessage(word注 channel_type/type/target_id/extra.author→字段) - 发消息: /message/create(频道) + /direct-message/create(私聊,修正正确端点,非user-chat) + Bearer鉴权 - 注册 channels.go + CHANNELS_JSON 多账号 + channelbridge.configured 加 kook(bot_token非空才连) - 框架增强: internal/channel/adapter/wsutil(连接管理/心跳/重连/resume骨架,复用gorilla,KOOK用上) + httpclient(Bearer+envelope归一,KOOK用) - 全仓 go build/vet/test 绿, 零新依赖(复用餐gorilla), 未动telegram/qq/weixin/webhook契约 - §4.6 隔离/黑白名单/第三方边界未破坏 注: KOOK WS/WH 双模式待补(ReceiveMode), 实测需主人提供 CHANNEL_KOOK_TOKEN
148 lines
3.9 KiB
Go
148 lines
3.9 KiB
Go
package wsutil
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/logger"
|
|
)
|
|
|
|
var wsu = websocket.Upgrader{}
|
|
|
|
// TestClient_DialReadReconnect exercises the connect hook, the read loop, and the
|
|
// reconnect path: the server accepts a connection, sends one frame, drops it;
|
|
// the client re-reads a second frame on the next connection, then the test cancels
|
|
// the context and the client exits cleanly.
|
|
func TestClient_DialReadReconnect(t *testing.T) {
|
|
var conns atomic.Int64
|
|
var mu sync.Mutex
|
|
var got []string
|
|
received := make(chan string, 2)
|
|
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
conn, err := wsu.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
t.Errorf("upgrade: %v", err)
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
n := conns.Add(1)
|
|
msg := "msg-" + string(rune('0'+n))
|
|
_ = conn.WriteMessage(websocket.TextMessage, []byte(msg))
|
|
if n < 2 {
|
|
return // close the first connection to trigger a reconnect
|
|
}
|
|
// Hold the second connection open until the client cancels the context.
|
|
for {
|
|
if _, _, err := conn.ReadMessage(); err != nil {
|
|
return
|
|
}
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
|
|
url := "ws://" + strings.TrimPrefix(srv.URL, "http://") + "/testws"
|
|
client := New(
|
|
func(context.Context) (string, error) { return url, nil },
|
|
Handler{
|
|
OnConnect: func(ctx context.Context, c *Conn) error { return nil },
|
|
OnMessage: func(ctx context.Context, p []byte) error {
|
|
mu.Lock()
|
|
got = append(got, string(p))
|
|
mu.Unlock()
|
|
received <- string(p)
|
|
return nil
|
|
},
|
|
},
|
|
WithBackoff(NewBackoff(10*time.Millisecond, 50*time.Millisecond)),
|
|
WithLogger(logger.New(logger.Options{Out: io.Discard})),
|
|
)
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
done := make(chan error, 1)
|
|
go func() { done <- client.Run(ctx) }()
|
|
|
|
for i := 0; i < 2; i++ {
|
|
select {
|
|
case m := <-received:
|
|
if m != "msg-" + string(rune('1'+i)) {
|
|
t.Errorf("message[%d] = %q", i, m)
|
|
}
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatalf("timed out waiting for message %d", i+1)
|
|
}
|
|
}
|
|
cancel()
|
|
select {
|
|
case err := <-done:
|
|
if err == nil {
|
|
t.Error("Run should return a non-nil error on cancel")
|
|
}
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatal("Run did not exit after cancel")
|
|
}
|
|
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
if len(got) != 2 {
|
|
t.Fatalf("received %d messages, want 2", len(got))
|
|
}
|
|
if conns.Load() < 2 {
|
|
t.Errorf("connection count = %d, want >= 2 (reconnect)", conns.Load())
|
|
}
|
|
}
|
|
|
|
// TestClient_HeartbeatVerifiesPing sends an s=2-like heartbeat every 20ms and
|
|
// asserts the dial URL is still the one provided.
|
|
func TestClient_OnConnectErrorTriggersRedial(t *testing.T) {
|
|
var dials atomic.Int64
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
conn, err := wsu.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
for {
|
|
if _, _, err := conn.ReadMessage(); err != nil {
|
|
return
|
|
}
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
url := "ws://" + strings.TrimPrefix(srv.URL, "http://") + "/testws"
|
|
|
|
// OnConnect always errors so the client keeps rejecting each session and the
|
|
// dial fires repeatedly.
|
|
client := New(
|
|
func(context.Context) (string, error) { dials.Add(1); return url, nil },
|
|
Handler{
|
|
OnConnect: func(ctx context.Context, c *Conn) error { return context.DeadlineExceeded },
|
|
},
|
|
WithBackoff(NewBackoff(5*time.Millisecond, 20*time.Millisecond)),
|
|
WithLogger(logger.New(logger.Options{Out: io.Discard})),
|
|
)
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
done := make(chan error, 1)
|
|
go func() { done <- client.Run(ctx) }()
|
|
|
|
time.Sleep(60 * time.Millisecond)
|
|
cancel()
|
|
select {
|
|
case <-done:
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("Run did not exit")
|
|
}
|
|
if dials.Load() < 2 {
|
|
t.Errorf("dials = %d, want >= 2 (reconnect on failed connect hook)", dials.Load())
|
|
}
|
|
}
|