feat(channel): KOOK 渠道适配器 + 框架兼容增强(wsutil/httpclient)
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled

- 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
This commit is contained in:
Aska committed 2026-09-07 12:01:35 +08:00
1 parent eab6b63eb0
commit 764d592859
24 files changed
+2800 -2

No files matched your search

@@ -0,0 +1,169 @@
// Package httpclient provides a small, reusable HTTP (/JSON) client for IM
// channel adapters that talk to a REST API with bearer-token auth and a
// common `{code,message,data}` response envelope (KOOK, and similarly shaped
// platforms). It is used by the KOOK adapter and is intended to be shared by
// future platforms; existing adapters (Telegram, OneBot) that already carry
// their own transport are left untouched.
//
// It depends only on the standard library and internal/logger. The bearer token
// is never logged or surfaced in errors.
package httpclient
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"strings"
"git.yeij.top/AskaEth/Cyrene_v2/internal/logger"
)
// ErrAPI is the sentinel returned when the remote API reports a non-zero code or
// a non-2xx HTTP status. Tests compare with errors.Is.
var ErrAPI = errors.New("httpclient: api error")
// maxBodyBytes caps how large a response body the client will read.
const maxBodyBytes = 1 << 20 // 1 MiB
// Client is a bearer-auth JSON HTTP client bound to a base URL.
type Client struct {
http *http.Client
baseURL string
token string
log *slog.Logger
}
// Option customizes a Client at construction time.
type Option func(*Client)
// WithHTTPClient injects the *http.Client used for requests. Tests pass the
// client of an httptest.Server.
func WithHTTPClient(h *http.Client) Option {
return func(c *Client) { c.http = h }
}
// WithBaseURL sets the URL root that paths are joined to. A base ending in "/"
// has its trailing slash trimmed.
func WithBaseURL(base string) Option {
return func(c *Client) { c.baseURL = strings.TrimRight(base, "/") }
}
// WithToken permits an Authorization: Bearer header on every request. The token
// is stored in memory only and never logged.
func WithToken(token string) Option {
return func(c *Client) { c.token = token }
}
// WithLogger injects the logger. A nil logger stays silent.
func WithLogger(l *slog.Logger) Option {
return func(c *Client) {
if l == nil {
c.log = logger.New(logger.Options{Out: io.Discard})
} else {
c.log = l
}
}
}
// New builds a Client. With no base URL the caller must pass absolute URLs (via
// the Do/Get helpers' path being an absolute URL).
func New(opts ...Option) *Client {
c := &Client{
http: &http.Client{},
log: logger.New(logger.Options{Out: io.Discard}),
}
for _, opt := range opts {
opt(c)
}
return c
}
// APIEnvelope is the common `{code,message,data}` response envelope used by the
// KOOK REST API. Code==0 means success; a non-zero code is mapped to ErrAPI.
type APIEnvelope struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data"`
}
// DoJSON performs a request with the given method against path (joined to the
// base URL) and returns the decoded data payload of the envelope. A non-zero
// code or a non-2xx status is wrapped with ErrAPI. A 2xx body that is not an
// envelope (e.g. a raw payload) is returned verbatim as data.
func (c *Client) DoJSON(ctx context.Context, method, path string, body any) (json.RawMessage, error) {
return c.do(ctx, method, c.resolve(path), body)
}
// GetJSON performs a GET against path with the given query parameters and
// returns the decoded data payload. A nil query adds nothing.
func (c *Client) GetJSON(ctx context.Context, path string, query url.Values) (json.RawMessage, error) {
target := c.resolve(path)
if len(query) > 0 {
target += "?" + query.Encode()
}
return c.do(ctx, http.MethodGet, target, nil)
}
// resolve joins path to the base URL, passing through an absolute path as-is.
func (c *Client) resolve(path string) string {
if c.baseURL == "" {
return path
}
return c.baseURL + path
}
// do performs the request, injecting auth and decoding the envelope.
func (c *Client) do(ctx context.Context, method, target string, body any) (json.RawMessage, error) {
var buf bytes.Buffer
if body != nil {
if err := json.NewEncoder(&buf).Encode(body); err != nil {
return nil, fmt.Errorf("httpclient: encode %s request: %w", method, err)
}
}
req, err := http.NewRequestWithContext(ctx, method, target, &buf)
if err != nil {
return nil, fmt.Errorf("httpclient: build %s %s request: %w", method, target, err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
resp, err := c.http.Do(req)
if err != nil {
return nil, fmt.Errorf("httpclient: %s %s: %w", method, target, err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, maxBodyBytes))
if err != nil {
return nil, fmt.Errorf("httpclient: read %s %s response: %w", method, target, err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("httpclient: %s %s: status %d: %s: %w", method, target, resp.StatusCode, truncate(raw), ErrAPI)
}
var envelope APIEnvelope
if err := json.Unmarshal(raw, &envelope); err != nil {
return raw, nil
}
if envelope.Code != 0 {
return nil, fmt.Errorf("httpclient: %s %s: code %d: %s: %w", method, target, envelope.Code, envelope.Message, ErrAPI)
}
return envelope.Data, nil
}
// truncate caps a byte slice to 512 bytes for inclusion in an error message.
func truncate(b []byte) string {
if len(b) > 512 {
return strings.TrimSpace(string(b[:512])) + "…"
}
return strings.TrimSpace(string(b))
}
@@ -0,0 +1,96 @@
package httpclient
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"git.yeij.top/AskaEth/Cyrene_v2/internal/logger"
)
func discardLogger() *slog.Logger { return logger.New(logger.Options{Out: io.Discard}) }
func TestGetJSON_EnvelopeAndAuth(t *testing.T) {
t.Parallel()
var mu sync.Mutex
var auth string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
auth = r.Header.Get("Authorization")
mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]any{
"code": 0, "message": "ok",
"data": map[string]any{"url": "wss://gw.example.com/gateway"},
})
}))
defer srv.Close()
c := New(
WithBaseURL(srv.URL),
WithToken("secret-token"),
WithHTTPClient(srv.Client()),
WithLogger(discardLogger()),
)
data, err := c.GetJSON(context.Background(), "/gateway/index", url.Values{"compress": {"0"}})
if err != nil {
t.Fatalf("GetJSON: %v", err)
}
if string(data) != `{"url":"wss://gw.example.com/gateway"}` {
t.Errorf("data = %s", string(data))
}
mu.Lock()
defer mu.Unlock()
if auth != "Bearer secret-token" {
t.Errorf("Authorization = %q, want Bearer secret-token", auth)
}
}
func TestDoJSON_NonZeroCode(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{"code": 40101, "message": "invalid token", "data": struct{}{}})
}))
defer srv.Close()
c := New(WithBaseURL(srv.URL), WithHTTPClient(srv.Client()), WithLogger(discardLogger()))
_, err := c.DoJSON(context.Background(), http.MethodPost, "/message/create", map[string]any{"a": 1})
if !errors.Is(err, ErrAPI) {
t.Fatalf("err = %v, want ErrAPI", err)
}
}
func TestDoJSON_StatusError(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("unauthorized"))
}))
defer srv.Close()
c := New(WithBaseURL(srv.URL), WithHTTPClient(srv.Client()), WithLogger(discardLogger()))
_, err := c.DoJSON(context.Background(), http.MethodGet, "/gateway/index", nil)
if !errors.Is(err, ErrAPI) {
t.Fatalf("err = %v, want ErrAPI", err)
}
}
func TestGetJSON_NonEnvelopeBodyPassedThrough(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`[1,2,3]`))
}))
defer srv.Close()
c := New(WithBaseURL(srv.URL), WithHTTPClient(srv.Client()), WithLogger(discardLogger()))
data, err := c.GetJSON(context.Background(), "/list", nil)
if err != nil {
t.Fatalf("GetJSON: %v", err)
}
if string(data) != "[1,2,3]" {
t.Errorf("data = %s, want [1,2,3]", string(data))
}
}
@@ -0,0 +1,54 @@
// Package wsutil provides a small, reusable WebSocket gateway client for
// stateful IM channels (KOOK, QQ OneBot, and similar). It owns the transport
// mechanics that those channels share — dialing a gateway, running a read loop,
// sending an application-level heartbeat, and reconnecting with exponential
// backoff (optionally splicing resume parameters onto the gateway URL) — while
// leaving the platform-specific signaling to the adapter via Handler hooks.
//
// It depends only on the standard library plus github.com/gorilla/websocket and
// internal/logger, never on a specific channel adapter.
package wsutil
import "time"
// Backoff is a resettable exponential backoff delay scheduler. It yields delays
// starting at base and doubling up to cap (for example 2s, 4s, 8s, ... capped at
// 60s), which is the WebSocket gateway reconnect pattern used by stateful IM
// channels. It is safe for concurrent use by a single goroutine.
type Backoff struct {
base time.Duration
max time.Duration
attempts int
}
// NewBackoff creates a backoff with the given base and cap. A non-positive base
// defaults to 1s and a non-positive cap to 60s.
func NewBackoff(base, cap time.Duration) *Backoff {
if base <= 0 {
base = time.Second
}
if cap <= 0 {
cap = 60 * time.Second
}
return &Backoff{base: base, max: cap}
}
// Next returns the delay to sleep before the next attempt and advances the
// internal attempt counter. It never exceeds the configured cap.
func (b *Backoff) Next() time.Duration {
var d time.Duration
if b.attempts >= 60 {
d = b.max
} else {
d = b.base << uint(b.attempts)
}
if d > b.max || d <= 0 {
d = b.max
}
b.attempts++
return d
}
// Reset restores the backoff to its initial state after a successful connect, so
// a later drop starts the ramp over from the base delay.
func (b *Backoff) Reset() { b.attempts = 0 }
@@ -0,0 +1,56 @@
package wsutil
import (
"testing"
"time"
)
func TestBackoffSequence(t *testing.T) {
t.Parallel()
b := NewBackoff(2*time.Second, 60*time.Second)
want := []time.Duration{2, 4, 8, 16, 32, 60, 60, 60}
for i, exp := range want {
if got := b.Next(); got != exp*time.Second {
t.Fatalf("Next[%d] = %v, want %v", i, got, exp*time.Second)
}
}
}
func TestBackoffReset(t *testing.T) {
t.Parallel()
b := NewBackoff(time.Second, time.Minute)
_ = b.Next()
_ = b.Next()
b.Reset()
if got := b.Next(); got != time.Second {
t.Errorf("after Reset, Next = %v, want 1s", got)
}
}
func TestBackoffDefaults(t *testing.T) {
t.Parallel()
b := NewBackoff(0, 0)
if got := b.Next(); got != time.Second {
t.Errorf("default base Next = %v, want 1s", got)
}
if got := b.Next(); got != 2*time.Second {
t.Errorf("default Next2 = %v, want 2s", got)
}
// cap of 60s by default: 1,2,4,8,16,32,60...
for i := 0; i < 7; i++ {
_ = b.Next()
}
if got := b.Next(); got != 60*time.Second {
t.Errorf("default cap Next = %v, want 60s", got)
}
}
func TestBackoffNoOverflow(t *testing.T) {
t.Parallel()
b := NewBackoff(time.Second, time.Second)
for i := 0; i < 200; i++ {
if got := b.Next(); got != time.Second {
t.Fatalf("Next[%d] = %v, want 1s (cap)", i, got)
}
}
}
+359
View File
@@ -0,0 +1,359 @@
package wsutil
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"git.yeij.top/AskaEth/Cyrene_v2/internal/logger"
)
const (
// defaultHeartbeatInterval is used when a client enables heartbeat without a
// configured interval.
defaultHeartbeatInterval = 30 * time.Second
// defaultPongTimeout is the read deadline margin added to the heartbeat
// interval; if the peer sends nothing within interval+pongTimeout the socket
// is considered dead and the client reconnects.
defaultPongTimeout = 6 * time.Second
// writeWait bounds a single control-frame write.
writeWait = 10 * time.Second
)
// DialFunc returns the gateway URL to connect to. On a reconnect the platform may
// return a resume-augmented URL (splice session/sn via AppendQuery) so the
// gateway can resynchronize the offline message window.
type DialFunc func(ctx context.Context) (string, error)
// Handler carries the platform-specific protocol hooks the Client invokes. A
// nil field disables that hook. The hooks run on the Client's read goroutine
// (OnConnect / OnMessage) or a dedicated heartbeat goroutine (Heartbeat).
type Handler struct {
// OnConnect is called after the WebSocket connection is established and the
// application handshake (for example KOOK's hello) succeeds. Returning an
// error aborts the session and triggers a reconnect with backoff.
OnConnect func(ctx context.Context, c *Conn) error
// OnMessage is called for every application text frame received. Returning an
// error forces a reconnect.
OnMessage func(ctx context.Context, payload []byte) error
// Heartbeat is called on the heartbeat ticker (when HeartbeatInterval > 0) to
// send an application-level keepalive frame. A nil Heartbeat disables it.
Heartbeat func(ctx context.Context, c *Conn) error
}
// Client is a reusable WebSocket gateway connection manager. It dials a gateway,
// runs the read loop, maintains an optional application-level heartbeat with a
// liveness read deadline, and reconnects with exponential backoff until the
// context is canceled. Only the platform signaling is left to the Handler.
type Client struct {
dial DialFunc
handler Handler
dialer *websocket.Dialer
header http.Header
interval time.Duration
pongWait time.Duration
backoff *Backoff
log *slog.Logger
mu sync.Mutex
conn *Conn
cancel context.CancelFunc
closed bool
}
// Option customizes a Client at construction time.
type Option func(*Client)
// WithDialer injects the WebSocket dialer used for the handshake. Tests pass a
// dialer whose net dial is redirected to a fake server.
func WithDialer(d *websocket.Dialer) Option {
return func(c *Client) { c.dialer = d }
}
// WithHeader injects extra HTTP headers on the handshake (for example an
// Authorization: Bearer token).
func WithHeader(h http.Header) Option {
return func(c *Client) { c.header = h }
}
// WithHeartbeat enables an application-level heartbeat at the given interval.
// A nil interval disables the heartbeat ticker (default off).
func WithHeartbeat(interval time.Duration) Option {
return func(c *Client) { c.interval = interval }
}
// WithPongTimeout sets the read deadline margin added to the heartbeat interval.
// A non-positive value uses the default (6s).
func WithPongTimeout(d time.Duration) Option {
return func(c *Client) { c.pongWait = d }
}
// WithBackoff injects the reconnect backoff scheduler.
func WithBackoff(b *Backoff) Option {
return func(c *Client) { c.backoff = b }
}
// WithLogger injects the logger used by the client. A nil logger stays silent.
func WithLogger(l *slog.Logger) Option {
return func(c *Client) {
if l == nil {
c.log = logger.New(logger.Options{Out: io.Discard})
} else {
c.log = l
}
}
}
// New builds a Client. dial must be non-nil.
func New(dial DialFunc, h Handler, opts ...Option) *Client {
if dial == nil {
dial = func(context.Context) (string, error) { return "", nil }
}
c := &Client{
dial: dial,
handler: h,
dialer: &websocket.Dialer{HandshakeTimeout: 15 * time.Second},
pongWait: defaultPongTimeout,
backoff: NewBackoff(2*time.Second, 60*time.Second),
log: logger.New(logger.Options{Out: io.Discard}),
}
for _, opt := range opts {
opt(c)
}
return c
}
// Run executes the connect/reconnect loop until ctx is canceled. It returns
// nil when ctx is canceled and a non-nil error on a non-context termination. It
// is intended to be run in its own goroutine by the adapter's Connect.
func (c *Client) Run(ctx context.Context) error {
for {
if ctx.Err() != nil {
return ctx.Err()
}
url, err := c.dial(ctx)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
c.log.Warn("ws gateway dial failed", "err", err)
if !c.sleepBackoff(ctx) {
return ctx.Err()
}
continue
}
if err := c.connectOnce(ctx, url); err != nil {
c.log.Warn("ws session ended", "err", err)
}
if ctx.Err() != nil {
return ctx.Err()
}
}
}
// connectOnce dials one URL and runs the connect hook plus the read loop until
// the connection drops, the read loop errors, or ctx is canceled.
func (c *Client) connectOnce(ctx context.Context, url string) error {
if c.header == nil {
c.header = http.Header{}
}
ws, _, err := c.dialer.DialContext(ctx, url, c.header)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
c.log.Warn("ws dial failed", "err", err)
c.sleepBackoff(ctx)
return err
}
conn := &Conn{ws: ws}
defer conn.Close()
// A watcher closes the connection when ctx ends so a pending read (including
// the OnConnect handshake) unblocks and Run can exit promptly.
stop := make(chan struct{})
defer close(stop)
go c.watchCtx(ctx, conn, stop)
if c.handler.OnConnect != nil {
if cerr := c.handler.OnConnect(ctx, conn); cerr != nil {
if ctx.Err() != nil {
return ctx.Err()
}
c.log.Warn("ws connect hook failed", "err", cerr)
c.sleepBackoff(ctx)
return cerr
}
}
c.setConn(conn)
c.backoff.Reset()
c.runReadLoop(ctx, conn)
c.setConn(nil)
return nil
}
// watchCtx closes the connection when ctx is canceled so a pending read
// unblocks, letting Run exit promptly.
func (c *Client) watchCtx(ctx context.Context, conn *Conn, stop <-chan struct{}) {
select {
case <-ctx.Done():
_ = conn.Close()
case <-stop:
}
}
// runReadLoop consumes text frames until the read errors, the platform handler
// returns an error, or ctx is canceled. When heartbeat is enabled it also runs a
// heartbeat ticker and refreshes a read deadline so a silent-but-live socket
// stays open while a dead one is detected.
func (c *Client) runReadLoop(ctx context.Context, conn *Conn) {
hbCtx, hbCancel := context.WithCancel(ctx)
defer hbCancel()
if c.handler.Heartbeat != nil && c.interval > 0 {
go c.heartbeatLoop(hbCtx, conn)
}
// A liveness read deadline is only meaningful when an application heartbeat
// keeps the socket active; without one, an idle-but-open connection must stay
// open indefinitely.
deadline := time.Duration(0)
if c.handler.Heartbeat != nil && c.interval > 0 {
deadline = c.interval + c.pongWait
}
for {
if ctx.Err() != nil {
return
}
if deadline > 0 {
_ = conn.SetReadDeadline(time.Now().Add(deadline))
} else {
_ = conn.SetReadDeadline(time.Time{})
}
payload, err := conn.ReadMessage()
if err != nil {
return
}
if c.handler.OnMessage != nil {
if err := c.handler.OnMessage(ctx, payload); err != nil {
if ctx.Err() == nil {
c.log.Warn("ws on-message failed", "err", err)
}
return
}
}
}
}
// heartbeatLoop sends an application-level keepalive on every interval. A
// failing heartbeat closes the connection to force a reconnect.
func (c *Client) heartbeatLoop(ctx context.Context, conn *Conn) {
t := time.NewTicker(c.interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if err := c.handler.Heartbeat(ctx, conn); err != nil {
c.log.Warn("ws heartbeat failed", "err", err)
_ = conn.Close()
return
}
}
}
}
// sleepBackoff sleeps the current backoff delay or until ctx is canceled,
// returning false (and leaving the connection for Run to exit) when ctx fires.
func (c *Client) sleepBackoff(ctx context.Context) bool {
d := c.backoff.Next()
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return false
case <-t.C:
return true
}
}
// setConn installs the live connection so Close can tear it down.
func (c *Client) setConn(conn *Conn) {
c.mu.Lock()
defer c.mu.Unlock()
c.conn = conn
}
// Close tears down the client, closing the live connection and its context.
func (c *Client) Close() error {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return nil
}
c.closed = true
conn := c.conn
cancel := c.cancel
c.mu.Unlock()
if conn != nil {
_ = conn.Close()
}
if cancel != nil {
cancel()
}
return nil
}
// BindCancel associates a context cancel func so Close can stop a running Run.
func (c *Client) BindCancel(cancel context.CancelFunc) {
c.mu.Lock()
defer c.mu.Unlock()
c.cancel = cancel
}
// Conn is a thin, concurrency-safe wrapper over one *websocket.Conn. It
// serializes writes (gorilla allows one reader plus one writer) and exposes only
// the JSON text-frame surface the gateway clients need.
type Conn struct {
ws *websocket.Conn
writeMu sync.Mutex
}
// ReadMessage reads the next complete message, returning its text payload. It
// honors any read deadline set via SetReadDeadline.
func (c *Conn) ReadMessage() ([]byte, error) {
_, p, err := c.ws.ReadMessage()
if err != nil {
return nil, err
}
return p, nil
}
// WriteMessage writes a text frame with the given payload.
func (c *Conn) WriteMessage(payload []byte) error {
c.writeMu.Lock()
defer c.writeMu.Unlock()
return c.ws.WriteMessage(websocket.TextMessage, payload)
}
// WriteJSON marshals v and writes it as a text frame.
func (c *Conn) WriteJSON(v any) error {
data, err := json.Marshal(v)
if err != nil {
return err
}
return c.WriteMessage(data)
}
// SetReadDeadline bounds the next ReadMessage by the given absolute time.
func (c *Conn) SetReadDeadline(t time.Time) error { return c.ws.SetReadDeadline(t) }
// Close closes the underlying connection exactly once.
func (c *Conn) Close() error { return c.ws.Close() }
@@ -0,0 +1,147 @@
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())
}
}
+85
View File
@@ -0,0 +1,85 @@
package wsutil
import (
"net/url"
"sort"
"strings"
)
// AppendQuery returns rawURL with the given query parameters added, preserving
// any existing query string. Parameters with an empty value are omitted. It is
// used by stateful gateway clients to splice resume parameters (resume/sn/
// session_id) and access tokens onto a gateway URL before reconnecting. Keys are
// appended in sorted order so the result is deterministic for tests.
func AppendQuery(rawURL string, params map[string]string) string {
if len(params) == 0 {
return rawURL
}
u, err := url.Parse(rawURL)
if err != nil {
return appendNaive(rawURL, params)
}
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
pairs := existingPairs(u.Query())
for _, k := range keys {
if params[k] == "" {
continue
}
pairs = append(pairs, url.QueryEscape(k)+"="+url.QueryEscape(params[k]))
}
u.RawQuery = strings.Join(pairs, "&")
return u.String()
}
// existingPairs flattens url.Values into ordered "k=v" pairs so that appending
// new parameters produces a deterministic query string. Multi-valued keys keep
// their original value order.
func existingPairs(v url.Values) []string {
keys := make([]string, 0, len(v))
for k := range v {
keys = append(keys, k)
}
sort.Strings(keys)
pairs := make([]string, 0, len(v))
for _, k := range keys {
for _, val := range v[k] {
pairs = append(pairs, url.QueryEscape(k)+"="+url.QueryEscape(val))
}
}
return pairs
}
// appendNaive appends query parameters to a URL that could not be parsed, using
// '?' or '&' based on what is already present.
func appendNaive(rawURL string, params map[string]string) string {
sep := "?"
if strings.Contains(rawURL, "?") {
sep = "&"
}
var b strings.Builder
b.WriteString(rawURL)
b.WriteString(sep)
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
first := true
for _, k := range keys {
if params[k] == "" {
continue
}
if !first {
b.WriteString("&")
}
first = false
b.WriteString(url.QueryEscape(k) + "=" + url.QueryEscape(params[k]))
}
return b.String()
}
@@ -0,0 +1,40 @@
package wsutil
import "testing"
func TestAppendQuery_PreservesExisting(t *testing.T) {
t.Parallel()
got := AppendQuery("wss://gw.example.com/gateway?compress=0&token=abc", map[string]string{
"resume": "1", "sn": "5", "session_id": "sess-123",
})
want := "wss://gw.example.com/gateway?compress=0&token=abc&resume=1&session_id=sess-123&sn=5"
if got != want {
t.Errorf("AppendQuery = %q, want %q", got, want)
}
}
func TestAppendQuery_NoExisting(t *testing.T) {
t.Parallel()
got := AppendQuery("wss://gw.example.com/gateway", map[string]string{"a": "1", "b": "2"})
want := "wss://gw.example.com/gateway?a=1&b=2"
if got != want {
t.Errorf("AppendQuery = %q, want %q", got, want)
}
}
func TestAppendQuery_OmitsEmptyValue(t *testing.T) {
t.Parallel()
got := AppendQuery("wss://gw.example.com/gateway?x=1", map[string]string{"sn": "", "resume": "1"})
want := "wss://gw.example.com/gateway?x=1&resume=1"
if got != want {
t.Errorf("AppendQuery = %q, want %q", got, want)
}
}
func TestAppendQuery_EmptyParams(t *testing.T) {
t.Parallel()
got := AppendQuery("wss://gw.example.com/gateway?x=1", nil)
if got != "wss://gw.example.com/gateway?x=1" {
t.Errorf("AppendQuery nil = %q, want unchanged", got)
}
}
@@ -287,7 +287,7 @@ func (b *Bridge) snapshot() []adapter.PlatformAdapter {
func (b *Bridge) configured(a adapter.PlatformAdapter) bool {
cfg := a.Config()
switch basePlatform(a.Name()) {
case "telegram", "weixin-ilink":
case "telegram", "weixin-ilink", "kook":
return cfgStr(cfg, "bot_token") != ""
case "qq-obv11":
if cfgStr(cfg, "mode") == "client" {