diff --git a/channel/channel_lifecycle_test.go b/channel/channel_lifecycle_test.go new file mode 100644 index 00000000..f1a7411f --- /dev/null +++ b/channel/channel_lifecycle_test.go @@ -0,0 +1,222 @@ +package channel + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + websocket "github.com/gorilla/websocket" + lark "github.com/larksuite/oapi-sdk-go/v3" + larkws "github.com/larksuite/oapi-sdk-go/v3/ws" +) + +const channelLifecycleTimeout = 2 * time.Second + +type channelLifecycleFixture struct { + bootstrap *httptest.Server + gateway *httptest.Server + accepted chan *websocket.Conn + + mu sync.Mutex + conns []*websocket.Conn +} + +func newChannelLifecycleFixture(t *testing.T) (*channelLifecycleFixture, *larkws.Client, func()) { + t.Helper() + + fixture := &channelLifecycleFixture{accepted: make(chan *websocket.Conn, 4)} + upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} + fixture.gateway = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + fixture.mu.Lock() + fixture.conns = append(fixture.conns, conn) + fixture.mu.Unlock() + fixture.accepted <- conn + for { + if _, _, err := conn.ReadMessage(); err != nil { + return + } + } + })) + endpoint := "ws" + strings.TrimPrefix(fixture.gateway.URL, "http") + "/channel" + fixture.bootstrap = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(&larkws.EndpointResp{ + Code: larkws.OK, + Data: &larkws.Endpoint{ + Url: endpoint, + ClientConfig: &larkws.ClientConfig{ + ReconnectCount: 0, + ReconnectInterval: 1, + PingInterval: 3600, + }, + }, + }); err != nil { + return + } + })) + cleanup := func() { + fixture.mu.Lock() + conns := append([]*websocket.Conn(nil), fixture.conns...) + fixture.mu.Unlock() + for _, conn := range conns { + if err := conn.Close(); err != nil && !isClosedChannelLifecycleConnectionError(err) { + t.Errorf("close channel test connection: %v", err) + } + } + fixture.bootstrap.Close() + fixture.gateway.Close() + } + + wsClient := larkws.NewClient("app-id", "app-secret", + larkws.WithDomain(fixture.bootstrap.URL), + larkws.WithAutoReconnect(false), + ) + return fixture, wsClient, cleanup +} + +func isClosedChannelLifecycleConnectionError(err error) bool { + if err == nil { + return false + } + message := strings.ToLower(err.Error()) + return strings.Contains(message, "use of closed network connection") || + strings.Contains(message, "closed network connection") || + strings.Contains(message, "connection already closed") +} + +func newChannelLifecycleAPIClient() *lark.Client { + mockHTTP := &MockHttpClient{ + DoFunc: func(req *http.Request) (*http.Response, error) { + header := make(http.Header) + header.Set("Content-Type", "application/json") + body := `{"code":0,"msg":"success"}` + switch req.URL.Path { + case "/open-apis/auth/v3/tenant_access_token/internal": + body = `{"code":0,"msg":"success","tenant_access_token":"test-token","expire":7200}` + case "/open-apis/bot/v3/info": + body = `{"code":0,"msg":"success","bot":{"open_id":"test-bot","app_name":"Test Bot","activate_status":2}}` + } + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(body)), + Header: header, + }, nil + }, + } + return lark.NewClient("app-id", "app-secret", lark.WithHttpClient(mockHTTP)) +} + +func startChannelLifecycle(ch interface { + Start(context.Context) error +}, ctx context.Context) <-chan error { + result := make(chan error, 1) + go func() { + result <- ch.Start(ctx) + }() + return result +} + +func waitChannelLifecycleSignal(t *testing.T, signal <-chan struct{}, name string) { + t.Helper() + select { + case <-signal: + case <-time.After(channelLifecycleTimeout): + t.Fatalf("timed out waiting for %s", name) + } +} + +func waitChannelLifecycleResult(result <-chan error) (error, bool) { + select { + case err := <-result: + return err, true + case <-time.After(channelLifecycleTimeout): + return nil, false + } +} + +func TestChannelStartReturnsContextCancellationAndBridgesCallbacksOnce(t *testing.T) { + _, wsClient, cleanupFixture := newChannelLifecycleFixture(t) + defer cleanupFixture() + ch := NewChannel(newChannelLifecycleAPIClient(), wsClient) + + ready := make(chan struct{}, 2) + disconnected := make(chan struct{}, 2) + var errorsSeen int32 + ch.OnReady(func() { ready <- struct{}{} }) + ch.OnDisconnected(func() { disconnected <- struct{}{} }) + ch.OnError(func(error) { atomic.AddInt32(&errorsSeen, 1) }) + + ctx, cancel := context.WithCancel(context.Background()) + result := startChannelLifecycle(ch, ctx) + waitChannelLifecycleSignal(t, ready, "Channel Ready") + cancel() + + err, ok := waitChannelLifecycleResult(result) + if !ok { + t.Error("Channel.Start did not return after context cancellation") + if stopErr := ch.Stop(context.Background()); stopErr != nil { + t.Errorf("Channel.Stop cleanup returned %v", stopErr) + } + } else if !errors.Is(err, context.Canceled) { + t.Errorf("Channel.Start returned %v, want context.Canceled", err) + } + waitChannelLifecycleSignal(t, disconnected, "Channel Disconnected") + select { + case <-ready: + t.Error("Channel bridged Ready more than once") + default: + } + select { + case <-disconnected: + t.Error("Channel bridged Disconnected more than once") + default: + } + if got := atomic.LoadInt32(&errorsSeen); got != 0 { + t.Errorf("normal context cancellation bridged OnError %d times, want 0", got) + } +} + +func TestChannelStopEndsBlockingStartWithNil(t *testing.T) { + _, wsClient, cleanupFixture := newChannelLifecycleFixture(t) + defer cleanupFixture() + ch := NewChannel(newChannelLifecycleAPIClient(), wsClient) + + ready := make(chan struct{}, 1) + disconnected := make(chan struct{}, 1) + ch.OnReady(func() { ready <- struct{}{} }) + ch.OnDisconnected(func() { disconnected <- struct{}{} }) + + result := startChannelLifecycle(ch, context.Background()) + waitChannelLifecycleSignal(t, ready, "Channel Ready") + if err := ch.Stop(context.Background()); err != nil { + t.Fatalf("Channel.Stop returned %v", err) + } + if err, ok := waitChannelLifecycleResult(result); !ok { + t.Error("Channel.Start did not return after Channel.Stop") + } else if err != nil { + t.Errorf("Channel.Start returned %v after Channel.Stop, want nil", err) + } + waitChannelLifecycleSignal(t, disconnected, "Channel Disconnected") +} + +func TestChannelStartAndStopKeepNilWebSocketClientNoOp(t *testing.T) { + ch := NewChannel(newChannelLifecycleAPIClient(), nil) + if err := ch.Start(context.Background()); err != nil { + t.Errorf("Channel.Start with nil WebSocket Client returned %v", err) + } + if err := ch.Stop(context.Background()); err != nil { + t.Errorf("Channel.Stop with nil WebSocket Client returned %v", err) + } +} diff --git a/doc/channel.md b/doc/channel.md index e4042c69..36074816 100644 --- a/doc/channel.md +++ b/doc/channel.md @@ -29,6 +29,7 @@ package main import ( "context" "fmt" + "log" "os" "os/signal" @@ -69,22 +70,41 @@ func main() { return err }) - // 6. Start Channel so lifecycle hooks are wired through Channel itself - if err := ch.Start(context.Background()); err != nil { - panic(err) - } + // 6. Start blocks for the whole WebSocket lifecycle, so run it alongside + // signal handling. The buffered channel lets Start report its result even + // when shutdown wins the select below. + startResult := make(chan error, 1) + go func() { + startResult <- ch.Start(context.Background()) + }() - // 7. Wait for termination + // 7. Stop on an interrupt, then wait for Start to return. stop := make(chan os.Signal, 1) signal.Notify(stop, os.Interrupt) - <-stop - - _ = ch.Stop(context.Background()) + defer signal.Stop(stop) + + select { + case err := <-startResult: + if err != nil { + log.Printf("channel stopped with error: %v", err) + } + case <-stop: + if err := ch.Stop(context.Background()); err != nil { + log.Printf("stop channel: %v", err) + } + if err := <-startResult; err != nil { + log.Printf("channel stopped with error: %v", err) + } + } } ``` Use `ch.Start(ctx)` instead of calling `wsClient.Start(ctx)` directly. `Channel` wires its own ready/reconnect/disconnect/error hooks during `Start()`. +`ch.Start(ctx)` blocks for the complete WebSocket lifecycle. If `ctx` is canceled or reaches its deadline first, it returns `ctx.Err()`. If `ch.Stop(...)` wins first, `Start` returns `nil`. A terminal connection failure is returned as an error. When these events race, the first accepted stop result is retained. + +After a connection has succeeded, stopping or ending that lifecycle makes the underlying WebSocket client terminal. Create a new `ws.Client` and `Channel` instead of calling `Start` again. A startup failure that happens before the first successful connection may be retried on the same client. + --- ## Event listening @@ -147,7 +167,7 @@ ch.OnDisconnected(func() { }) ``` -These hooks are attached by `ch.Start(ctx)`. +These hooks are attached by `ch.Start(ctx)`. `OnReady`, recoverable `OnError`, `OnReconnecting`, and `OnReconnected` run synchronously in the lifecycle coordinator. A blocking hook delays coordinator progress, `Start` returning, and subsequent cleanup; hook implementations must return. `ch.Stop(...)` itself does not wait for a running hook, but `Start` can finish cleanup only after that hook returns. Once shutdown has been accepted, the client does not dispatch new ready, reconnect, or event callbacks. `OnDisconnected` runs only after the corresponding ready/reconnected callback has returned (or panicked). --- @@ -359,3 +379,4 @@ Retryable outbound failures are retried automatically before the error is return 3. **Card buttons not firing** is usually either a missing `card.action.trigger` subscription or a V1 card schema. V2 uses `column_set` -> `column` -> `button` with `behaviors: [{ type: "callback", value }]`. Handle it with `OnCardAction(...)`. 4. **Use `Stream()`** for progressive output. For markdown streams call `Append()`. For card streams call `UpdateCard()`. 5. **Start Channel through `ch.Start(ctx)`**. If you start `wsClient` directly, Channel lifecycle hooks such as `OnReady()` and `OnReconnected()` will not be wired by `Channel`. +6. **Treat `Start` as the lifecycle join point.** Run signal handling concurrently, call `Stop`, and wait for `Start` to return. Passing a nil context is invalid. diff --git a/doc/channel.zh.md b/doc/channel.zh.md index 9259ae93..c8dda8ea 100644 --- a/doc/channel.zh.md +++ b/doc/channel.zh.md @@ -29,6 +29,7 @@ package main import ( "context" "fmt" + "log" "os" "os/signal" @@ -69,22 +70,40 @@ func main() { return err }) - // 6. 通过 Channel 启动,让生命周期回调由 Channel 完成接线 - if err := ch.Start(context.Background()); err != nil { - panic(err) - } + // 6. Start 会阻塞整个 WebSocket 生命周期,因此需要和信号处理并行。 + // 使用容量为 1 的 channel,确保退出信号先到时 Start 仍能上报结果。 + startResult := make(chan error, 1) + go func() { + startResult <- ch.Start(context.Background()) + }() - // 7. 阻塞等待退出信号 + // 7. 收到退出信号后停止 Channel,并等待 Start 返回 stop := make(chan os.Signal, 1) signal.Notify(stop, os.Interrupt) - <-stop - - _ = ch.Stop(context.Background()) + defer signal.Stop(stop) + + select { + case err := <-startResult: + if err != nil { + log.Printf("Channel 异常停止:%v", err) + } + case <-stop: + if err := ch.Stop(context.Background()); err != nil { + log.Printf("停止 Channel 失败:%v", err) + } + if err := <-startResult; err != nil { + log.Printf("Channel 异常停止:%v", err) + } + } } ``` 建议使用 `ch.Start(ctx)`,不要直接调用 `wsClient.Start(ctx)`。因为 `Channel` 会在 `Start()` 中接入自己的 `OnReady` / 重连 / 断线 / 错误回调。 +`ch.Start(ctx)` 会阻塞整个 WebSocket 生命周期。如果最先发生的是 `ctx` 取消或超时,它返回 `ctx.Err()`;如果最先调用 `ch.Stop(...)`,`Start` 返回 `nil`;如果发生不可恢复的连接错误,`Start` 返回该错误。当这些事件并发发生时,以第一个被接受的停止结果为准,后续原因不会覆盖它。 + +一旦连接成功过,主动停止或生命周期结束后,底层 WebSocket Client 就进入终态。此时应新建 `ws.Client` 和 `Channel`,不要再次调用同一个 Client 的 `Start`。只有首次连接成功前发生的启动失败,才允许在同一个 Client 上重试。 + --- ## 事件监听 @@ -147,7 +166,7 @@ ch.OnDisconnected(func() { }) ``` -这些回调由 `ch.Start(ctx)` 完成接线。 +这些回调由 `ch.Start(ctx)` 完成接线。`OnReady`、可恢复的 `OnError`、`OnReconnecting` 和 `OnReconnected` 会在生命周期 coordinator 中同步执行。阻塞这些回调会延迟 coordinator 推进、`Start` 返回和后续清理,因此回调实现必须返回。`ch.Stop(...)` 自身不会等待正在运行的回调,但只有该回调返回后,`Start` 才能完成清理并返回。停止请求被接受后,不再派发新的 ready、重连或事件回调;`OnDisconnected` 只会在对应的 ready/reconnected 回调返回(或 panic)后执行。 --- @@ -359,3 +378,4 @@ if errors.As(err, &channelErr) { 3. **卡片按钮不响应**通常是:没加 `card.action.trigger` 订阅,或者卡片仍是 V1 schema。V2 建议使用 `column_set` -> `column` -> `button`,并配置 `behaviors: [{ type: "callback", value }]`。高层处理入口是 `OnCardAction(...)`。 4. **流式请用 `Stream()`**。Markdown 流用 `Append()`,卡片流用 `UpdateCard()`,不要手动循环 `Send()` 模拟流式。 5. **请通过 `ch.Start(ctx)` 启动 Channel**。如果你直接启动 `wsClient`,`Channel` 自己的 `OnReady()` / `OnReconnected()` 等生命周期回调不会由 `Channel` 接线。 +6. **把 `Start` 当作生命周期的汇合点**。信号处理需要并行运行;调用 `Stop` 后还要等待 `Start` 返回。传入 nil context 属于无效调用。 diff --git a/ws/client.go b/ws/client.go index ead7e9c1..49f6933c 100644 --- a/ws/client.go +++ b/ws/client.go @@ -1,21 +1,12 @@ package ws import ( - "bytes" - "context" - "encoding/json" "fmt" - "io" - "math/rand" "net/http" - "net/url" - "runtime/debug" - "strconv" - "strings" "sync" "time" - ws "github.com/gorilla/websocket" + "github.com/gorilla/websocket" lark "github.com/larksuite/oapi-sdk-go/v3" larkcache "github.com/larksuite/oapi-sdk-go/v3/cache" larkcard "github.com/larksuite/oapi-sdk-go/v3/card" @@ -34,31 +25,24 @@ type Client struct { domain string headers http.Header source string - conn *ws.Conn - connUrl *url.URL - serviceID string - connID string - // connIDMu guards connID: fmtLog reads it from goroutines that do not hold c.mu. - connIDMu sync.RWMutex - autoReconnect bool // 是否自动重连,默认开启 - reconnectNonce int // 首次重连抖动,单位秒 - reconnectCount int // 重连次数,负数无限次 - reconnectInterval time.Duration // 重连间隔 - pingInterval time.Duration // Ping间隔 - cache *larkcache.Cache - mu sync.Mutex - onReady func() - onError func(err error) - onReconnecting func() - onReconnected func() - onDisconnected func() -} - -var bootstrapHTTPClient = http.DefaultClient - -type bootstrapErrorResp struct { - Code int `json:"code"` - Msg string `json:"msg"` + autoReconnect bool // 是否自动重连,默认开启 + reconnectNonce int // 首次重连抖动,单位秒 + reconnectCount int // 重连次数,负数无限次 + reconnectInterval time.Duration // 重连间隔 + pingInterval time.Duration // Ping间隔 + writeTimeout time.Duration // 单次写入超时 + httpClient larkcore.HttpClient + websocketDialer *websocket.Dialer + cache *larkcache.Cache + onReady func() + onError func(err error) + onReconnecting func() + onReconnected func() + onDisconnected func() + + stateMu sync.Mutex + run *clientRun + terminal bool } type ClientOption func(cli *Client) @@ -93,6 +77,37 @@ func WithAutoReconnect(b bool) ClientOption { } } +// WithWriteTimeout sets the maximum duration of one websocket write. A +// non-positive timeout keeps the default value. +func WithWriteTimeout(timeout time.Duration) ClientOption { + return func(cli *Client) { + if timeout > 0 { + cli.writeTimeout = timeout + } + } +} + +// WithHttpClient sets the HTTP client used to fetch the websocket endpoint. +// When httpClient is an *http.Client, its Timeout also bounds that request. +func WithHttpClient(httpClient larkcore.HttpClient) ClientOption { + return func(cli *Client) { + if httpClient != nil { + cli.httpClient = httpClient + } + } +} + +// WithWebSocketDialer sets the dialer used to establish websocket connections. +// Its Proxy, TLSClientConfig and HandshakeTimeout settings apply only to this +// Client instance. +func WithWebSocketDialer(dialer *websocket.Dialer) ClientOption { + return func(cli *Client) { + if dialer != nil { + cli.websocketDialer = dialer + } + } +} + func WithDomain(domain string) ClientOption { return func(cli *Client) { cli.domain = domain @@ -116,6 +131,7 @@ func WithClientAssertionProvider(provider larkcore.ClientAssertionProvider) Clie cli.clientAssertionProvider = provider } } + func WithOnReady(f func()) ClientOption { return func(cli *Client) { cli.onReady = f @@ -147,41 +163,37 @@ func WithOnDisconnected(f func()) ClientOption { } func (c *Client) SetOnReady(f func()) { - c.mu.Lock() - defer c.mu.Unlock() + c.stateMu.Lock() + defer c.stateMu.Unlock() c.onReady = f } func (c *Client) SetOnReconnecting(f func()) { - c.mu.Lock() - defer c.mu.Unlock() + c.stateMu.Lock() + defer c.stateMu.Unlock() c.onReconnecting = f } func (c *Client) SetOnReconnected(f func()) { - c.mu.Lock() - defer c.mu.Unlock() + c.stateMu.Lock() + defer c.stateMu.Unlock() c.onReconnected = f } func (c *Client) SetOnError(f func(err error)) { - c.mu.Lock() - defer c.mu.Unlock() + c.stateMu.Lock() + defer c.stateMu.Unlock() c.onError = f } func (c *Client) SetOnDisconnected(f func()) { - c.mu.Lock() - defer c.mu.Unlock() + c.stateMu.Lock() + defer c.stateMu.Unlock() c.onDisconnected = f } -func (c *Client) Close() { - c.autoReconnect = false - c.disconnect(context.Background()) -} - func NewClient(appId, appSecret string, opts ...ClientOption) *Client { + dialer := *websocket.DefaultDialer cli := &Client{ appID: appId, appSecret: appSecret, @@ -190,6 +202,9 @@ func NewClient(appId, appSecret string, opts ...ClientOption) *Client { reconnectCount: -1, reconnectInterval: 2 * time.Minute, pingInterval: 2 * time.Minute, + writeTimeout: 10 * time.Second, + httpClient: &http.Client{Timeout: 10 * time.Second}, + websocketDialer: &dialer, cache: larkcache.New(30 * time.Second), domain: lark.FeishuBaseUrl, } @@ -205,576 +220,44 @@ func NewClient(appId, appSecret string, opts ...ClientOption) *Client { return cli } -func (c *Client) Start(ctx context.Context) (err error) { - err = c.connect(ctx) - if err != nil { - c.logger.Error(ctx, c.fmtLog("connect failed, err: %v", err)...) - if c.onError != nil { - c.onError(err) - } - if _, ok := err.(*ClientError); ok { - return - } - c.disconnect(ctx) - if c.autoReconnect { - if err = c.reconnect(ctx); err != nil { - return err - } - } else { - return err - } - } else { - if c.onReady != nil { - c.onReady() - } - } - go c.pingLoop(ctx) - select {} -} - -func (c *Client) connect(ctx context.Context) (err error) { - c.mu.Lock() - defer c.mu.Unlock() - if c.conn != nil { - return - } - - // 获取建连URL - connUrl, err := c.getConnURL(ctx) - if err != nil { - c.logger.Warn(ctx, c.fmtLog("get conn url failed, err: %v", err)...) - return - } - - // 验证URL - u, err := url.Parse(connUrl) - if err != nil { - return - } - connID := u.Query().Get(DeviceID) - serviceID := u.Query().Get(ServiceID) - - conn, resp, err := ws.DefaultDialer.Dial(connUrl, nil) - if err != nil && resp == nil { - return - } - if resp.StatusCode != http.StatusSwitchingProtocols { - // 连接失败 - return parseErr(resp) - } - - c.conn = conn - c.connUrl = u - c.setConnID(connID) - c.serviceID = serviceID - - c.logger.Info(ctx, c.fmtLog("connected to %s", u)...) - - go c.receiveMessageLoop(ctx) - return -} - -func (c *Client) reconnect(ctx context.Context) (err error) { - if c.onReconnecting != nil { - c.onReconnecting() - } - - reconnectCount, _, reconnectNonce, _ := c.configSnapshot() - - // 首次重连随机抖动 - if reconnectNonce > 0 { - rand.Seed(time.Now().UnixNano()) - num := rand.Intn(reconnectNonce * 1000) - time.Sleep(time.Duration(num) * time.Millisecond) - } - - if reconnectCount >= 0 { - for i := 0; i < reconnectCount; i++ { - success, err := c.tryConnect(ctx, i) - if success { - if c.onReconnected != nil { - c.onReconnected() - } - return nil - } - if err != nil { - return err - } - _, reconnectInterval, _, _ := c.configSnapshot() - time.Sleep(reconnectInterval) - } - return fmt.Errorf("unable to connect to server after %d retries", reconnectCount) - } else { - i := 0 - for { - success, err := c.tryConnect(ctx, i) - if success { - if c.onReconnected != nil { - c.onReconnected() - } - return nil - } - if err != nil { - return err - } - _, reconnectInterval, _, _ := c.configSnapshot() - time.Sleep(reconnectInterval) - i += 1 - } - } -} - -func (c *Client) tryConnect(ctx context.Context, cnt int) (bool, error) { - c.logger.Info(ctx, c.fmtLog("trying to reconnect: %d", cnt+1)...) - err := c.connect(ctx) - if err == nil { - return true, nil - } else if _, ok := err.(*ClientError); ok { - if c.onError != nil { - c.onError(err) - } - return false, err - } else { - c.logger.Error(ctx, c.fmtLog("connect failed, err: %v", err)...) - if c.onError != nil { - c.onError(err) - } - return false, nil - } -} - -func (c *Client) disconnect(ctx context.Context) { - c.mu.Lock() - defer c.mu.Unlock() - if c.conn == nil { - return - } - - _ = c.conn.Close() - c.logger.Info(ctx, c.fmtLog("disconnected to %s", c.connUrl)...) - - if c.onDisconnected != nil { - c.onDisconnected() - } - - defer func() { - c.conn = nil - c.connUrl = nil - c.setConnID("") - c.serviceID = "" - }() -} - -func (c *Client) getConnURL(ctx context.Context) (url string, err error) { - requestURL := strings.TrimRight(c.domain, "/") + GenEndpointUri - body := &BootstrapRequest{AppID: c.appID} - headers := make(http.Header) - - if c.clientAssertionProvider == nil && c.appSecret == "" { - return "", NewClientError(larkcore.ErrCodeAppSecretAndClientAssertionEmpty, "appSecret and clientAssertionProvider cannot be nil") - } - - if c.clientAssertionProvider != nil { - aud, extractErr := extractAudFromWSURL(c.domain) - if extractErr != nil { - return "", extractErr - } - clientAssertionToken, retrieveErr := c.clientAssertionProvider.RetrieveToken(ctx, aud) - if retrieveErr != nil { - return "", retrieveErr - } - if clientAssertionToken == nil || clientAssertionToken.Value == "" { - return "", NewClientError(larkcore.ErrCodeClientAssertionTokenEmpty, "client assertion token is empty") - } - body.ClientAssertion = clientAssertionToken.Value - body.AppSecret = "" - if clientAssertionToken.TargetInfo != nil { - requestURL = buildWSProxyURL(clientAssertionToken.TargetInfo.TargetService, clientAssertionToken.TargetInfo.TargetPrefix, GenEndpointUri) - headers.Set(larkcore.HeaderXTargetService, aud) - } - } else { - body.AppSecret = c.appSecret - } - - bs, err := json.Marshal(body) - if err != nil { - return - } - - req, err := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, bytes.NewBuffer(bs)) - if err != nil { - return - } - - req.Header.Add("locale", "zh") - req.Header.Add("Content-Type", "application/json") - for k, values := range c.headers { - for _, value := range values { - req.Header.Add(k, value) - } - } - for k, values := range headers { - req.Header.Del(k) - for _, value := range values { - req.Header.Add(k, value) - } - } - req.Header.Set("User-Agent", larkcore.UserAgent(c.source)) - resp, err := bootstrapHTTPClient.Do(req) - if err != nil { - return - } - defer resp.Body.Close() - respBody, err := io.ReadAll(resp.Body) - if err != nil { - return - } - if resp.StatusCode != http.StatusOK { - c.logger.Warn(ctx, "response status code %d", resp.StatusCode) - serverMsg := "system busy" - bootstrapErrResp := &bootstrapErrorResp{} - if json.Unmarshal(respBody, bootstrapErrResp) == nil { - if bootstrapErrResp.Msg != "" { - serverMsg = bootstrapErrResp.Msg - } - } - err = NewServerError(resp.StatusCode, serverMsg) - return - } - - endpointResp := &EndpointResp{} - err = json.Unmarshal(respBody, endpointResp) - if err != nil { - return - } - - switch endpointResp.Code { - case OK: - case SystemBusy: - return "", NewServerError(endpointResp.Code, "system busy") - case InternalError: - return "", NewServerError(endpointResp.Code, endpointResp.Msg) - default: - return "", NewClientError(endpointResp.Code, endpointResp.Msg) - } - - endpoint := endpointResp.Data - if endpoint == nil || endpoint.Url == "" { - err = NewServerError(http.StatusInternalServerError, "endpoint is null") - return - } - - url = endpoint.Url - if endpoint.ClientConfig != nil { - // getConnURL is only ever called from connect, which already holds c.mu; - // use the locked variant to avoid self-deadlocking on the non-reentrant mutex. - c.configureLocked(endpoint.ClientConfig) - } - - return -} - -func extractAudFromWSURL(rawURL string) (string, error) { - if !strings.Contains(rawURL, "://") { - rawURL = "https://" + rawURL - } - parsedURL, err := url.Parse(rawURL) - if err != nil { - return "", err - } - if parsedURL.Host != "" { - return parsedURL.Host, nil - } - return "", fmt.Errorf("invalid url: %s", rawURL) -} - -func buildWSProxyURL(targetService, targetPrefix, apiPath string) string { - if !strings.Contains(targetService, "://") { - targetService = "https://" + targetService - } - return targetService + targetPrefix + apiPath -} - -func (c *Client) pingLoop(ctx context.Context) { - defer func() { - if err := recover(); err != nil { - c.logger.Warn(ctx, c.fmtLog("ping loop panic, err: %v, stack: %s", err, string(debug.Stack()))...) - } - go c.pingLoop(ctx) - }() - - for { - conn, serviceID := c.connState() - if conn != nil { - i, _ := strconv.ParseInt(serviceID, 10, 32) - frame := NewPingFrame(int32(i)) - bs, _ := frame.Marshal() - - err := c.writeMessage(ws.BinaryMessage, bs) - if err != nil { - c.logger.Warn(ctx, c.fmtLog("ping failed, err: %v", err)...) - } else { - c.logger.Debug(ctx, c.fmtLog("ping success")...) - } - } - _, _, _, pingInterval := c.configSnapshot() - time.Sleep(pingInterval) - } -} - -func (c *Client) receiveMessageLoop(ctx context.Context) { - defer func() { - if err := recover(); err != nil { - c.logger.Error(ctx, c.fmtLog("receive message loop panic, err: %v, stack: %s", err, string(debug.Stack()))...) - } - c.disconnect(ctx) - if c.autoReconnect { - if err := c.reconnect(ctx); err != nil { - c.logger.Error(ctx, err) - } - } - }() - - for { - conn, _ := c.connState() - if conn == nil { - c.logger.Error(ctx, c.fmtLog("connection is closed, receive message loop exit")...) - return - } - - mt, msg, err := conn.ReadMessage() - if err != nil { - c.logger.Error(ctx, c.fmtLog("receive message failed, err: %v", err)...) - return - } - - if mt != ws.BinaryMessage { - c.logger.Warn(ctx, c.fmtLog("receive unknown message, message_type: %d, message: %s", mt, msg)...) - continue - } - - go c.handleMessage(ctx, msg) - } -} - -func (c *Client) handleMessage(ctx context.Context, msg []byte) { - defer func() { - if err := recover(); err != nil { - c.logger.Error(ctx, c.fmtLog("handle message panic, err: %v, stack: %s", err, string(debug.Stack()))...) - } - }() - - var frame Frame - if err := frame.Unmarshal(msg); err != nil { - c.logger.Error(ctx, c.fmtLog("unmarshal message failed, error: %v", err)...) - return - } - - switch FrameType(frame.Method) { - case FrameTypeControl: - c.handleControlFrame(ctx, frame) - case FrameTypeData: - c.handleDataFrame(ctx, frame) - default: - } -} - -func (c *Client) handleControlFrame(ctx context.Context, frame Frame) { - hs := Headers(frame.Headers) - t := hs.GetString(HeaderType) - - switch MessageType(t) { - case MessageTypePong: - c.logger.Debug(ctx, c.fmtLog("receive pong")...) - if len(frame.Payload) == 0 { - return - } - conf := &ClientConfig{} - if err := json.Unmarshal(frame.Payload, conf); err != nil { - c.logger.Warn(ctx, c.fmtLog("unmarshal client config failed, err: %v", err)...) - return - } - c.configure(conf) - default: - } +func (c *Client) fmtLog(format string, i ...interface{}) []interface{} { + return []interface{}{fmt.Sprintf(format, i...)} } -func (c *Client) handleDataFrame(ctx context.Context, frame Frame) { - hs := Headers(frame.Headers) - sum := hs.GetInt(HeaderSum) - seq := hs.GetInt(HeaderSeq) - msgID := hs.GetString(HeaderMessageID) - traceID := hs.GetString(HeaderTraceID) - type_ := hs.GetString(HeaderType) - - pl := frame.Payload - if sum > 1 { - // 合包 - pl = c.combine(msgID, sum, seq, pl) - if pl == nil { - return - } - } - - c.logger.Debug(ctx, c.fmtLog("receive message, message_type: %s, message_id: %s, trace_id: %s, payload: %s", - type_, msgID, traceID, pl)) - - var err error - var rsp interface{} - start := time.Now().UnixNano() / int64(time.Millisecond) // 兼容 go < 1.17 - switch MessageType(type_) { - case MessageTypeEvent: - rsp, err = c.eventHandler.Do(ctx, pl) - case MessageTypeCard: - return - default: - return - } - end := time.Now().UnixNano() / int64(time.Millisecond) - hs.Add(HeaderBizRt, strconv.FormatInt(end-start, 10)) - - resp := NewResponseByCode(http.StatusOK) - if err != nil { - c.logger.Error(ctx, c.fmtLog("handle message failed, message_type: %s, message_id: %s, trace_id: %s, err: %v", - type_, msgID, traceID, err)...) - resp = NewResponseByCode(http.StatusInternalServerError) - } else { - if rsp != nil { // for cardCallback - resp.Data, err = json.Marshal(rsp) - if err != nil { - c.logger.Error(ctx, c.fmtLog("handle message failed, message_type: %s, message_id: %s, trace_id: %s, err: %v", - type_, msgID, traceID, err)...) - resp = NewResponseByCode(http.StatusInternalServerError) - } - } - } - - p, _ := json.Marshal(resp) - frame.Payload = p - frame.Headers = hs - bs, _ := frame.Marshal() - - err = c.writeMessage(ws.BinaryMessage, bs) - if err != nil { - c.logger.Error(ctx, c.fmtLog("response message failed, type: %s, message_id: %s, trace_id: %s, err: %v", type_, msgID, traceID, err)...) - return - } +func (c *Client) configure(conf *ClientConfig) { + c.stateMu.Lock() + defer c.stateMu.Unlock() + c.applyConfigLocked(conf) } -func (c *Client) combine(msgID string, sum, seq int, bs []byte) []byte { - val := c.cache.Get(msgID) - if val == nil { - buf := make([][]byte, sum) - buf[seq] = bs - c.cache.Set(msgID, buf, 5*time.Second) - return nil +func (c *Client) applyConfig(run *clientRun, conf *ClientConfig) bool { + if run.ctx.Err() != nil { + return false } - - buf := val.([][]byte) - buf[seq] = bs - capacity := 0 - for _, v := range buf { - if len(v) == 0 { - c.cache.Set(msgID, buf, 5*time.Second) - return nil - } - capacity += len(v) + c.stateMu.Lock() + defer c.stateMu.Unlock() + if run.stopReason != runStopNone { + return false } - - pl := make([]byte, 0, capacity) - for _, v := range buf { - pl = append(pl, v...) + if conf != nil { + c.applyConfigLocked(conf) } - - return pl + return true } -func (c *Client) writeMessage(messageType int, data []byte) error { - c.mu.Lock() - defer c.mu.Unlock() - if c.conn == nil { - return fmt.Errorf("connection is closed") - } - return c.conn.WriteMessage(messageType, data) -} - -func (c *Client) fmtLog(format string, i ...interface{}) []interface{} { - log := []interface{}{fmt.Sprintf(format, i...)} - if connID := c.connIDSnapshot(); connID != "" { - log = append(log, fmt.Sprintf("[conn_id=%s]", connID)) - } - - return log -} - -// Leaf lock, not c.mu: connect and disconnect already hold c.mu when they call fmtLog. -func (c *Client) setConnID(id string) { - c.connIDMu.Lock() - c.connID = id - c.connIDMu.Unlock() -} - -func (c *Client) connIDSnapshot() string { - c.connIDMu.RLock() - defer c.connIDMu.RUnlock() - return c.connID -} - -// configure applies a server-pushed config. It is the entry point for callers -// that do NOT already hold c.mu (the pong control-frame handler runs in its own -// goroutine). The connect path holds c.mu while building the URL, so it calls -// configureLocked directly to avoid re-entering the non-reentrant mutex. -func (c *Client) configure(conf *ClientConfig) { - c.mu.Lock() - defer c.mu.Unlock() - c.configureLocked(conf) -} - -// configureLocked writes the connection-control fields. The caller must hold c.mu. -func (c *Client) configureLocked(conf *ClientConfig) { +func (c *Client) applyConfigLocked(conf *ClientConfig) { c.reconnectCount = conf.ReconnectCount c.reconnectInterval = time.Duration(conf.ReconnectInterval) * time.Second c.reconnectNonce = conf.ReconnectNonce c.pingInterval = time.Duration(conf.PingInterval) * time.Second } -// configSnapshot reads the connection-control fields under c.mu and returns a -// consistent copy, so readers (pingLoop, reconnect) never observe a torn write. func (c *Client) configSnapshot() (reconnectCount int, reconnectInterval time.Duration, reconnectNonce int, pingInterval time.Duration) { - c.mu.Lock() - defer c.mu.Unlock() + c.stateMu.Lock() + defer c.stateMu.Unlock() return c.reconnectCount, c.reconnectInterval, c.reconnectNonce, c.pingInterval } -// connState reads conn/serviceID under c.mu. Callers must release the lock (i.e. -// use the returned snapshot) before any blocking call such as writeMessage or -// ReadMessage, since writeMessage takes c.mu again and the mutex is not reentrant. -func (c *Client) connState() (conn *ws.Conn, serviceID string) { - c.mu.Lock() - defer c.mu.Unlock() - return c.conn, c.serviceID -} - -func parseErr(resp *http.Response) error { - code, _ := strconv.Atoi(resp.Header.Get(HeaderHandshakeStatus)) - msg := resp.Header.Get(HeaderHandshakeMsg) - switch code { - case AuthFailed: - // Auth失败 - authCode, _ := strconv.Atoi(resp.Header.Get(HeaderHandshakeAuthErrCode)) - if authCode == ExceedConnLimit { - return NewClientError(code, msg) - } else { - return NewServerError(code, msg) - } - case Forbidden: - // 被封禁 - return NewClientError(code, msg) - default: - return NewServerError(code, msg) - } -} - // EventHandler returns the configured event dispatcher. func (c *Client) EventHandler() *dispatcher.EventDispatcher { return c.eventHandler diff --git a/ws/client_connid_race_test.go b/ws/client_connid_race_test.go deleted file mode 100644 index 6840d4ab..00000000 --- a/ws/client_connid_race_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package ws - -import ( - "fmt" - "sync" - "testing" -) - -// Fails under -race without the connIDMu guard. -func TestFmtLogConnIDNoRace(t *testing.T) { - c := &Client{} - - const goroutines = 4 - const iterations = 2000 - var wg sync.WaitGroup - - for w := 0; w < goroutines; w++ { - wg.Add(1) - go func(w int) { - defer wg.Done() - for i := 0; i < iterations; i++ { - c.setConnID(fmt.Sprintf("conn-%d-%d", w, i)) - c.setConnID("") - } - }(w) - } - - for r := 0; r < goroutines; r++ { - wg.Add(1) - go func() { - defer wg.Done() - for i := 0; i < iterations; i++ { - if out := c.fmtLog("probe %d", i); len(out) != 1 && len(out) != 2 { - t.Errorf("fmtLog returned %d parts, want 1 or 2", len(out)) - return - } - } - }() - } - - wg.Wait() -} diff --git a/ws/client_context_test.go b/ws/client_context_test.go new file mode 100644 index 00000000..27f4fabf --- /dev/null +++ b/ws/client_context_test.go @@ -0,0 +1,134 @@ +package ws + +import ( + "context" + "errors" + "testing" + "time" + + larkcore "github.com/larksuite/oapi-sdk-go/v3/core" +) + +type lifecycleContextKey struct{} + +type contextInspectingAssertionProvider struct { + observed chan contextObservation + waitDone bool +} + +type contextObservation struct { + value interface{} + deadline time.Time + hasDeadline bool + err error +} + +func (p *contextInspectingAssertionProvider) RetrieveToken(ctx context.Context, aud string) (*larkcore.Token, error) { + if p.waitDone { + <-ctx.Done() + } + deadline, hasDeadline := ctx.Deadline() + p.observed <- contextObservation{ + value: ctx.Value(lifecycleContextKey{}), + deadline: deadline, + hasDeadline: hasDeadline, + err: ctx.Err(), + } + return nil, errors.New("context inspection complete") +} + +func TestStartPropagatesContextValueAndDeadlineToAssertionProvider(t *testing.T) { + deadline := time.Now().Add(time.Minute) + callerCtx := context.WithValue(context.Background(), lifecycleContextKey{}, "caller-value") + callerCtx, cancel := context.WithDeadline(callerCtx, deadline) + defer cancel() + + provider := &contextInspectingAssertionProvider{observed: make(chan contextObservation, 1)} + client := NewClient("app-id", "", WithClientAssertionProvider(provider), WithAutoReconnect(false)) + if err := client.Start(callerCtx); err == nil { + t.Fatal("Start returned nil after assertion provider failure") + } + observation := <-provider.observed + if observation.value != "caller-value" { + t.Fatalf("provider context value = %#v, want caller-value", observation.value) + } + if !observation.hasDeadline || !observation.deadline.Equal(deadline) { + t.Fatalf("provider deadline = %v, %v; want %v, true", observation.deadline, observation.hasDeadline, deadline) + } +} + +func TestStartPropagatesDeadlineErrorToAssertionProvider(t *testing.T) { + callerCtx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + + provider := &contextInspectingAssertionProvider{ + observed: make(chan contextObservation, 1), + waitDone: true, + } + client := NewClient("app-id", "", WithClientAssertionProvider(provider), WithAutoReconnect(false)) + if err := client.Start(callerCtx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Start returned %v, want context.DeadlineExceeded", err) + } + observation := <-provider.observed + if !errors.Is(observation.err, context.DeadlineExceeded) { + t.Fatalf("provider context Err = %v, want context.DeadlineExceeded", observation.err) + } +} + +func TestRunContextFollowsCallerCancellation(t *testing.T) { + callerCtx, cancel := context.WithCancel(context.Background()) + defer cancel() + + client := NewClient("app-id", "app-secret") + run, err := client.beginRun(callerCtx) + if err != nil { + t.Fatalf("beginRun returned error: %v", err) + } + + cancel() + select { + case <-run.ctx.Done(): + case <-time.After(time.Second): + t.Fatal("run context did not follow caller cancellation") + } + if !errors.Is(run.ctx.Err(), context.Canceled) { + t.Fatalf("run context Err = %v, want context.Canceled", run.ctx.Err()) + } + if finishErr := client.finishRun(run); !errors.Is(finishErr, context.Canceled) { + t.Fatalf("finishRun returned %v, want context.Canceled", finishErr) + } +} + +func TestConnectionStateRejectsCallerCancellation(t *testing.T) { + callerCtx, cancel := context.WithCancel(context.Background()) + defer cancel() + + client := NewClient("app-id", "app-secret") + run, err := client.beginRun(callerCtx) + if err != nil { + t.Fatalf("beginRun returned error: %v", err) + } + conn := &clientConn{ + connectionResult: make(chan error, 1), + } + client.stateMu.Lock() + run.conn = conn + client.stateMu.Unlock() + + cancel() + if client.isConnectionActive(run, conn) { + t.Fatal("canceled caller context left connection active") + } + if client.stopRun(run, runStopByFailure, errors.New("late connection failure")) { + t.Fatal("canceled caller context accepted a later connection failure") + } + if current, ok := client.currentConnection(run); ok || current != nil { + t.Fatalf("currentConnection = (%p, %v), want (nil, false)", current, ok) + } + if client.startMessageTask(run, nil) { + t.Fatal("canceled caller context admitted a message task") + } + if finishErr := client.finishRun(run); !errors.Is(finishErr, context.Canceled) { + t.Fatalf("finishRun returned %v, want context.Canceled", finishErr) + } +} diff --git a/ws/client_dispatch_test.go b/ws/client_dispatch_test.go new file mode 100644 index 00000000..bf2a2d0c --- /dev/null +++ b/ws/client_dispatch_test.go @@ -0,0 +1,136 @@ +package ws + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "time" + + larkevent "github.com/larksuite/oapi-sdk-go/v3/event" + "github.com/larksuite/oapi-sdk-go/v3/event/dispatcher" +) + +func activeRunAndConn() (*clientRun, *clientConn) { + runCtx, runCancel := context.WithCancel(context.Background()) + run := &clientRun{ctx: runCtx, cancel: runCancel} + conn := &clientConn{ + connectionResult: make(chan error, 1), + } + run.conn = conn + return run, conn +} + +func TestConnectionAdmissionAfterStop(t *testing.T) { + run, conn := activeRunAndConn() + defer run.cancel() + client := NewClient("app-id", "app-secret") + client.run = run + if !client.isConnectionActive(run, conn) { + t.Fatal("active run/conn was not admitted") + } + if !client.stopRun(run, runStopByClose, nil) { + t.Fatal("stopRun rejected the active run") + } + if client.isConnectionActive(run, conn) { + t.Fatal("stopped run/conn remained eligible for handler dispatch") + } +} + +func TestStoppedRunRejectsNewMessageWorker(t *testing.T) { + run, _ := activeRunAndConn() + defer run.cancel() + client := NewClient("app-id", "app-secret") + client.run = run + if !client.stopRun(run, runStopByClose, nil) { + t.Fatal("stopRun rejected the active run") + } + if client.startMessageTask(run, nil) { + t.Fatal("stopped run admitted a new message worker") + } +} + +func TestMessageTaskWaitsForEventHandler(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + socket := dialLifecycleCandidate(t, gateway) + defer closeGatewayConn(t, socket) + serverConn := waitAcceptedGatewayConnection(t, gateway) + run, _ := activeRunAndSocket(socket, gateway.endpoint()) + defer run.cancel() + + started := make(chan struct{}) + release := make(chan struct{}) + client := NewClient("app-id", "app-secret", WithEventHandler( + dispatcher.NewEventDispatcher("", "").OnCustomizedEvent("test.event", func(context.Context, *larkevent.EventReq) error { + close(started) + <-release + return nil + }), + )) + client.run = run + + headers := Headers{} + headers.Add(HeaderType, string(MessageTypeEvent)) + headers.Add(HeaderMessageID, "message-1") + headers.Add(HeaderTraceID, "trace-1") + message, err := (&Frame{ + Method: int32(FrameTypeData), + Headers: headers, + Payload: []byte(`{"header":{"event_type":"test.event"}}`), + }).Marshal() + if err != nil { + t.Fatalf("marshal event frame: %v", err) + } + if !client.startMessageTask(run, message) { + t.Fatal("active run did not admit a message task") + } + waitLifecycleSignal(t, started, "event handler start") + + finished := make(chan struct{}) + go func() { + run.wg.Wait() + close(finished) + }() + select { + case <-finished: + t.Fatal("message task finished before its event handler returned") + case <-time.After(100 * time.Millisecond): + } + assertNoGatewayFrame(t, gateway, serverConn, 100*time.Millisecond) + + close(release) + waitLifecycleSignal(t, finished, "message task completion") + frame := waitGatewayFrame(t, gateway, "event response") + if frame.conn != serverConn { + t.Fatalf("event response used connection %p, want %p", frame.conn, serverConn) + } + responseFrame := &Frame{} + if err := responseFrame.Unmarshal(frame.payload); err != nil { + t.Fatalf("decode event response frame: %v", err) + } + if responseFrame.Method != int32(FrameTypeData) { + t.Fatalf("event response method = %d, want data frame", responseFrame.Method) + } +} + +func TestStoppedRunSkipsLifecycleCallbacks(t *testing.T) { + run, _ := activeRunAndConn() + defer run.cancel() + var callbacks int32 + client := NewClient("app-id", "app-secret", + WithOnReconnecting(func() { atomic.AddInt32(&callbacks, 1) }), + WithOnError(func(error) { atomic.AddInt32(&callbacks, 1) }), + ) + client.run = run + if !client.stopRun(run, runStopByClose, nil) { + t.Fatal("stopRun rejected the active run") + } + + client.invokeReconnectingCallback(run) + client.invokeRecoverableErrorCallback(run, errors.New("retry failed")) + if got := atomic.LoadInt32(&callbacks); got != 0 { + t.Fatalf("stopped run invoked %d queued lifecycle callbacks, want 0", got) + } +} diff --git a/ws/client_external_test.go b/ws/client_external_test.go new file mode 100644 index 00000000..afd31ccd --- /dev/null +++ b/ws/client_external_test.go @@ -0,0 +1,117 @@ +package ws_test + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" + + larkcore "github.com/larksuite/oapi-sdk-go/v3/core" + ws "github.com/larksuite/oapi-sdk-go/v3/ws" +) + +type failingAssertionProvider struct { + err error +} + +func (p failingAssertionProvider) RetrieveToken(context.Context, string) (*larkcore.Token, error) { + return nil, p.err +} + +func TestStartHTTPFailurePreservesServerError(t *testing.T) { + const serverMessage = "target service unavailable" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + if err := json.NewEncoder(w).Encode(map[string]interface{}{ + "code": 20050, + "msg": serverMessage, + }); err != nil { + t.Errorf("encode bootstrap error: %v", err) + } + })) + defer server.Close() + + callbackErr := make(chan error, 1) + client := ws.NewClient("app-id", "app-secret", + ws.WithDomain(server.URL), + ws.WithAutoReconnect(false), + ws.WithOnError(func(err error) { callbackErr <- err }), + ) + err := client.Start(context.Background()) + if err == nil { + t.Fatal("Start returned nil after bootstrap HTTP failure") + } + + serverErr, ok := err.(*ws.ServerError) + if !ok { + t.Fatalf("Start returned %T, want *ws.ServerError", err) + } + if serverErr.Code != http.StatusInternalServerError { + t.Fatalf("ServerError.Code = %d, want %d", serverErr.Code, http.StatusInternalServerError) + } + if serverErr.Msg != serverMessage { + t.Fatalf("ServerError.Msg = %q, want %q", serverErr.Msg, serverMessage) + } + select { + case callbackErr := <-callbackErr: + if _, ok := callbackErr.(*ws.ServerError); !ok { + t.Errorf("OnError received %T, want *ws.ServerError", callbackErr) + } + default: + t.Fatal("OnError was not invoked") + } +} + +func TestStartClientFailurePreservesClientError(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(map[string]interface{}{ + "code": 19001, + "msg": "invalid credential", + }); err != nil { + t.Errorf("encode bootstrap error: %v", err) + } + })) + defer server.Close() + + callbackErr := make(chan error, 1) + client := ws.NewClient("app-id", "app-secret", + ws.WithDomain(server.URL), + ws.WithOnError(func(err error) { callbackErr <- err }), + ) + err := client.Start(context.Background()) + if err == nil { + t.Fatal("Start returned nil after bootstrap client failure") + } + clientErr, ok := err.(*ws.ClientError) + if !ok { + t.Fatalf("Start returned %T, want *ws.ClientError", err) + } + if clientErr.Code != 19001 || clientErr.Msg != "invalid credential" { + t.Fatalf("ClientError = %#v, want code 19001 and original message", clientErr) + } + select { + case callbackErr := <-callbackErr: + if _, ok := callbackErr.(*ws.ClientError); !ok { + t.Errorf("OnError received %T, want *ws.ClientError", callbackErr) + } + default: + t.Fatal("OnError was not invoked") + } +} + +func TestStartPreservesAssertionProviderError(t *testing.T) { + providerErr := errors.New("assertion provider network failure") + client := ws.NewClient("app-id", "", + ws.WithClientAssertionProvider(failingAssertionProvider{err: providerErr}), + ws.WithAutoReconnect(false), + ) + + err := client.Start(context.Background()) + if err != providerErr { + t.Fatalf("Start error = %v, want original provider error %v", err, providerErr) + } +} diff --git a/ws/client_lifecycle.go b/ws/client_lifecycle.go new file mode 100644 index 00000000..1336f70a --- /dev/null +++ b/ws/client_lifecycle.go @@ -0,0 +1,333 @@ +package ws + +import ( + "context" + "fmt" + "math/rand" + "sync" + "time" +) + +type runStopReason uint8 + +const ( + runStopNone runStopReason = iota + runStopByContext + runStopByClose + runStopByFailure +) + +type clientRun struct { + ctx context.Context + cancel context.CancelFunc + done chan struct{} + + stopReason runStopReason + stopErr error + conn *clientConn + everConnected bool + + wg sync.WaitGroup +} + +func (c *Client) Start(callerCtx context.Context) error { + if callerCtx == nil { + return errNilContext + } + + run, err := c.beginRun(callerCtx) + if err != nil { + return err + } + if run.ctx.Err() == nil { + c.runCoordinator(run) + } + return c.finishRun(run) +} + +// Close requests that the active run stop and returns immediately. It is safe +// to call from lifecycle callbacks. Those callbacks run on the coordinator, so +// waiting here would make a callback that calls Close wait for itself. +// +// Call CloseAndWait from outside lifecycle callbacks when teardown must finish +// before the caller releases its own resources. +func (c *Client) Close() { + c.stateMu.Lock() + run := c.run + c.stateMu.Unlock() + if run != nil { + c.stopRun(run, runStopByClose, nil) + } +} + +// CloseAndWait requests that the active run stop and waits until its workers +// and OnDisconnected callback have finished. It returns the run's final result, +// or ctx.Err if the caller stops waiting first. +// +// CloseAndWait must not be called from lifecycle callbacks. Use Close there: +// the coordinator invokes those callbacks synchronously, so waiting for the +// same run would deadlock. +func (c *Client) CloseAndWait(ctx context.Context) error { + if ctx == nil { + return errNilContext + } + + c.stateMu.Lock() + run := c.run + c.stateMu.Unlock() + if run == nil { + return nil + } + + c.stopRun(run, runStopByClose, nil) + select { + case <-run.done: + c.stateMu.Lock() + err := run.stopErr + c.stateMu.Unlock() + return err + case <-ctx.Done(): + return ctx.Err() + } +} + +func (c *Client) beginRun(callerCtx context.Context) (*clientRun, error) { + c.stateMu.Lock() + if c.run != nil { + c.stateMu.Unlock() + return nil, errClientRunning + } + if c.terminal { + c.stateMu.Unlock() + return nil, errClientTerminal + } + + runCtx, cancel := context.WithCancel(callerCtx) + run := &clientRun{ctx: runCtx, cancel: cancel, done: make(chan struct{})} + c.run = run + c.stateMu.Unlock() + return run, nil +} + +func (c *Client) stopRun(run *clientRun, reason runStopReason, err error) (accepted bool) { + if reason != runStopByContext && run.ctx.Err() != nil { + return false + } + + c.stateMu.Lock() + if c.run != run || run.stopReason != runStopNone { + c.stateMu.Unlock() + return false + } + + run.stopReason = reason + run.stopErr = err + if reason == runStopByContext || reason == runStopByClose || + (reason == runStopByFailure && run.everConnected) { + c.terminal = true + } + c.stateMu.Unlock() + + run.cancel() + return true +} + +func (c *Client) finishRun(run *clientRun) error { + if contextErr := run.ctx.Err(); contextErr != nil { + c.stopRun(run, runStopByContext, contextErr) + } + run.cancel() + run.wg.Wait() + + c.stateMu.Lock() + err := run.stopErr + c.run = nil + c.stateMu.Unlock() + close(run.done) + return err +} + +// runCoordinator exposes the lifecycle in three steps: establish a physical +// connection, activate its Ping/Receive/Pong session, then stop or reconnect. +func (c *Client) runCoordinator(run *clientRun) { + conn, err := c.establishConnectionOnce(run) + reconnected := false + if err != nil { + if !c.isRunActive(run) { + return + } + c.logger.Warn(run.ctx, c.fmtLog("websocket initial connection failed")...) + if c.autoReconnect && isRetryableConnectionError(err) { + c.invokeRecoverableErrorCallback(run, err) + } + conn = c.reconnectAfterFailure(run, err) + reconnected = true + } + + for conn != nil { + activated := c.activateConnection(run, conn, reconnected) + if !activated { + return + } + exitErr := c.waitForConnectionExit(run, conn) + if exitErr == nil { + return + } + c.logger.Warn(run.ctx, c.fmtLog("websocket connection failed")...) + + conn = c.reconnectAfterFailure(run, exitErr) + reconnected = true + } +} + +// reconnectAfterFailure owns one reconnect sequence. The failed read that starts +// a reconnect is not reported as a recoverable dial error. An initial failed +// connection is reported by runCoordinator before this sequence +// begins; subsequent failed connection attempts are reported below. +func (c *Client) reconnectAfterFailure(run *clientRun, failure error) *clientConn { + if !c.autoReconnect || !isRetryableConnectionError(failure) { + c.stopRunWithError(run, failure) + return nil + } + c.invokeReconnectingCallback(run) + attempts := 0 + + for { + reconnectCount, reconnectInterval, reconnectNonce, _ := c.configSnapshot() + if reconnectCount >= 0 && attempts >= reconnectCount { + err := fmt.Errorf("unable to connect to server after %d retries", reconnectCount) + c.logger.Warn(run.ctx, c.fmtLog("websocket reconnect attempts exhausted after %d attempts", attempts)...) + c.stopRun(run, runStopByFailure, err) + return nil + } + + delay := reconnectInterval + if attempts == 0 { + delay = randomReconnectDelay(reconnectNonce) + } + if !c.waitRunDelay(run, delay) { + return nil + } + attempts++ + if reconnectCount >= 0 { + c.logger.Info(run.ctx, c.fmtLog("websocket reconnecting: attempt %d/%d", attempts, reconnectCount)...) + } else { + c.logger.Info(run.ctx, c.fmtLog("websocket reconnecting: attempt %d", attempts)...) + } + + conn, err := c.establishConnectionOnce(run) + if err == nil { + return conn + } + if !c.isRunActive(run) { + return nil + } + failure = err + c.logger.Warn(run.ctx, c.fmtLog("websocket reconnect attempt %d failed", attempts)...) + if !c.autoReconnect || !isRetryableConnectionError(failure) { + c.stopRunWithError(run, failure) + return nil + } + c.invokeRecoverableErrorCallback(run, failure) + } +} + +// waitForConnectionExit returns nil when the run has stopped. Otherwise, it +// returns the first read or write error that starts a reconnect sequence. +func (c *Client) waitForConnectionExit(run *clientRun, conn *clientConn) error { + var exitErr error + select { + case <-run.ctx.Done(): + case exitErr = <-conn.connectionResult: + } + + c.deactivateConnection(run) + if !c.isRunActive(run) { + return nil + } + return exitErr +} + +func (c *Client) stopRunWithError(run *clientRun, err error) { + if !c.stopRun(run, runStopByFailure, err) { + return + } + c.invokeTerminalErrorCallback(run, err) +} + +func (c *Client) isRunActive(run *clientRun) bool { + if run.ctx.Err() != nil { + return false + } + c.stateMu.Lock() + defer c.stateMu.Unlock() + return run.stopReason == runStopNone +} + +func (c *Client) waitRunDelay(run *clientRun, delay time.Duration) bool { + if delay <= 0 { + return c.isRunActive(run) + } + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-timer.C: + return c.isRunActive(run) + case <-run.ctx.Done(): + return false + } +} + +func (c *Client) invokeReconnectingCallback(run *clientRun) { + c.stateMu.Lock() + callback := c.onReconnecting + c.stateMu.Unlock() + if callback == nil || !c.isRunActive(run) { + return + } + defer c.recoverCallback(run.ctx, "lifecycle") + callback() +} + +func (c *Client) invokeRecoverableErrorCallback(run *clientRun, err error) { + c.stateMu.Lock() + callback := c.onError + c.stateMu.Unlock() + if callback == nil || !c.isRunActive(run) { + return + } + c.runErrorCallback(run.ctx, callback, err) +} + +func (c *Client) invokeTerminalErrorCallback(run *clientRun, err error) { + c.stateMu.Lock() + callback := c.onError + c.stateMu.Unlock() + if callback != nil { + c.runErrorCallback(run.ctx, callback, err) + } +} + +func (c *Client) runErrorCallback(ctx context.Context, callback func(error), err error) { + defer c.recoverCallback(ctx, "error") + callback(err) +} + +func (c *Client) recoverCallback(ctx context.Context, category string) { + if recover() != nil { + c.logger.Error(ctx, c.fmtLog("websocket %s callback panicked", category)...) + } +} + +func randomReconnectDelay(reconnectNonce int) time.Duration { + if reconnectNonce <= 0 { + return 0 + } + source := rand.New(rand.NewSource(time.Now().UnixNano())) + return time.Duration(source.Intn(reconnectNonce*1000)) * time.Millisecond +} + +func isRetryableConnectionError(err error) bool { + _, isClientError := err.(*ClientError) + return !isClientError +} diff --git a/ws/client_lifecycle_test.go b/ws/client_lifecycle_test.go new file mode 100644 index 00000000..53d183df --- /dev/null +++ b/ws/client_lifecycle_test.go @@ -0,0 +1,1882 @@ +package ws + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + websocket "github.com/gorilla/websocket" + larkcore "github.com/larksuite/oapi-sdk-go/v3/core" +) + +const lifecycleTestTimeout = 2 * time.Second +const lifecycleNoProgressTimeout = 100 * time.Millisecond + +type lifecycleGateway struct { + server *httptest.Server + accepted chan *websocket.Conn + requests chan lifecycleGatewayRequest + messages chan []byte + frames chan lifecycleGatewayFrame + + mu sync.Mutex + conns []*websocket.Conn +} + +type lifecycleGatewayFrame struct { + conn *websocket.Conn + payload []byte +} + +type lifecycleGatewayRequest struct { + path string + deviceID string + serviceID string + username string + password string +} + +type lifecycleAssertionProvider struct { + mu sync.Mutex + failures []error + token *larkcore.Token + calls int +} + +func (p *lifecycleAssertionProvider) RetrieveToken(context.Context, string) (*larkcore.Token, error) { + p.mu.Lock() + defer p.mu.Unlock() + p.calls++ + if index := p.calls - 1; index < len(p.failures) && p.failures[index] != nil { + return nil, p.failures[index] + } + return p.token, nil +} + +func (p *lifecycleAssertionProvider) callCount() int { + p.mu.Lock() + defer p.mu.Unlock() + return p.calls +} + +func newLifecycleGateway(t *testing.T) (*lifecycleGateway, func()) { + t.Helper() + + gateway := &lifecycleGateway{ + accepted: make(chan *websocket.Conn, 8), + requests: make(chan lifecycleGatewayRequest, 8), + messages: make(chan []byte, 8), + frames: make(chan lifecycleGatewayFrame, 16), + } + upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} + gateway.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + + username, password, _ := r.BasicAuth() + gateway.mu.Lock() + gateway.conns = append(gateway.conns, conn) + gateway.mu.Unlock() + + gateway.requests <- lifecycleGatewayRequest{ + path: r.URL.Path, + deviceID: r.URL.Query().Get(DeviceID), + serviceID: r.URL.Query().Get(ServiceID), + username: username, + password: password, + } + gateway.accepted <- conn + + for { + messageType, message, err := conn.ReadMessage() + if err != nil { + return + } + if messageType == websocket.BinaryMessage { + payload := append([]byte(nil), message...) + select { + case gateway.messages <- payload: + default: + } + select { + case gateway.frames <- lifecycleGatewayFrame{conn: conn, payload: payload}: + default: + } + } + } + })) + cleanup := func() { + gateway.mu.Lock() + conns := append([]*websocket.Conn(nil), gateway.conns...) + gateway.mu.Unlock() + for _, conn := range conns { + if err := conn.Close(); err != nil && !isClosedLifecycleConnectionError(err) { + t.Errorf("close test gateway connection: %v", err) + } + } + gateway.server.Close() + } + return gateway, cleanup +} + +func (g *lifecycleGateway) endpoint() string { + return "ws" + strings.TrimPrefix(g.server.URL, "http") + "/callback" +} + +func installLifecycleBootstrap(t *testing.T, endpoint string, requests *int32) (string, func()) { + t.Helper() + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(requests, 1) + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(&EndpointResp{ + Code: OK, + Data: &Endpoint{ + Url: endpoint, + ClientConfig: &ClientConfig{ + ReconnectCount: 0, + ReconnectInterval: 1, + PingInterval: 3600, + }, + }, + }); err != nil { + return + } + })) + cleanup := func() { + server.Close() + } + return server.URL, cleanup +} + +func installLifecycleBootstrapHandler(t *testing.T, handler http.Handler) (string, func()) { + t.Helper() + + server := httptest.NewServer(handler) + cleanup := func() { + server.Close() + } + return server.URL, cleanup +} + +func startLifecycleClient(client *Client, ctx context.Context) <-chan error { + result := make(chan error, 1) + go func() { + result <- client.Start(ctx) + }() + return result +} + +func waitLifecycleSignal(t *testing.T, signal <-chan struct{}, name string) { + t.Helper() + select { + case <-signal: + case <-time.After(lifecycleTestTimeout): + t.Fatalf("timed out waiting for %s", name) + } +} + +func waitLifecycleResult(result <-chan error) (error, bool) { + select { + case err := <-result: + return err, true + case <-time.After(lifecycleTestTimeout): + return nil, false + } +} + +func assertNoLifecycleSignal(t *testing.T, signal <-chan struct{}, name string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), lifecycleNoProgressTimeout) + defer cancel() + select { + case <-signal: + t.Fatalf("%s happened while it should have been blocked", name) + case <-ctx.Done(): + } +} + +func assertNoLifecycleResult(t *testing.T, result <-chan error, name string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), lifecycleNoProgressTimeout) + defer cancel() + select { + case err := <-result: + t.Fatalf("%s returned %v while it should have been blocked", name, err) + case <-ctx.Done(): + } +} + +func closeGatewayConn(t *testing.T, conn *websocket.Conn) { + t.Helper() + if err := conn.Close(); err != nil && !isClosedLifecycleConnectionError(err) { + t.Errorf("close gateway connection: %v", err) + } +} + +func isClosedLifecycleConnectionError(err error) bool { + if err == nil { + return false + } + message := strings.ToLower(err.Error()) + return strings.Contains(message, "use of closed network connection") || + strings.Contains(message, "closed network connection") || + strings.Contains(message, "connection already closed") +} + +func TestStartNilDoesNotConsumeLaterValidStart(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + var callbackCount int32 + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { + atomic.AddInt32(&callbackCount, 1) + ready <- struct{}{} + }), + WithOnError(func(error) { + atomic.AddInt32(&callbackCount, 1) + }), + ) + + if err := client.Start(nil); err == nil { + t.Fatal("Start(nil) returned nil, want a parameter error") + } + if got := atomic.LoadInt32(&bootstrapRequests); got != 0 { + t.Fatalf("Start(nil) made %d bootstrap requests, want 0", got) + } + if got := atomic.LoadInt32(&callbackCount); got != 0 { + t.Fatalf("Start(nil) invoked %d lifecycle callbacks, want 0", got) + } + + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "Ready after a valid Start") + client.Close() + if err, ok := waitLifecycleResult(result); !ok { + t.Error("valid Start did not return after Close") + } else if err != nil { + t.Errorf("valid Start returned %v after Close, want nil", err) + } +} + +func TestWithWebSocketDialerEstablishesConnection(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + dialer := *websocket.DefaultDialer + var proxyCalls int32 + dialer.Proxy = func(*http.Request) (*url.URL, error) { + atomic.AddInt32(&proxyCalls, 1) + return nil, nil + } + ready := make(chan struct{}, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithWebSocketDialer(&dialer), + WithOnReady(func() { ready <- struct{}{} }), + ) + + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "ready callback") + client.Close() + if err, completed := waitLifecycleResult(result); !completed || err != nil { + t.Fatalf("Start returned %v, completed=%v", err, completed) + } + if atomic.LoadInt32(&proxyCalls) != 1 { + t.Fatalf("expected injected websocket dialer once, got %d", proxyCalls) + } +} + +func TestInitialFailureThenReconnectUsesReconnectedCallback(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestNumber := atomic.AddInt32(&bootstrapRequests, 1) + endpoint := gateway.endpoint() + if requestNumber == 1 { + endpoint = "ws://127.0.0.1:1/unreachable" + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(&EndpointResp{ + Code: OK, + Data: &Endpoint{ + Url: endpoint, + ClientConfig: &ClientConfig{ + ReconnectCount: 1, + ReconnectInterval: 0, + ReconnectNonce: 0, + PingInterval: 3600, + }, + }, + }); err != nil { + t.Errorf("encode bootstrap response: %v", err) + } + })) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + callbackDone := make(chan struct{}, 1) + var callbackMu sync.Mutex + callbackOrder := make([]string, 0, 3) + recordCallback := func(name string) { + callbackMu.Lock() + callbackOrder = append(callbackOrder, name) + callbackMu.Unlock() + } + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithOnReady(func() { ready <- struct{}{} }), + WithOnError(func(error) { recordCallback("error") }), + WithOnReconnecting(func() { recordCallback("reconnecting") }), + WithOnReconnected(func() { + recordCallback("reconnected") + callbackDone <- struct{}{} + }), + ) + result := startLifecycleClient(client, context.Background()) + + waitLifecycleSignal(t, callbackDone, "ordered recovery callbacks after initial failure") + callbackMu.Lock() + callbackSequence := strings.Join(callbackOrder, ",") + callbackMu.Unlock() + if callbackSequence != "error,reconnecting,reconnected" { + t.Fatalf("recovery callback order = %q, want error,reconnecting,reconnected", callbackSequence) + } + select { + case <-ready: + t.Fatal("initial reconnect invoked Ready, want Reconnected only") + default: + } + if got := atomic.LoadInt32(&bootstrapRequests); got != 2 { + t.Fatalf("bootstrap requests = %d, want 2", got) + } + + client.Close() + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after Close") + } else if err != nil { + t.Fatalf("Start returned %v after Close, want nil", err) + } +} + +func TestRecoverableErrorBlocksReconnectUntilReturned(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + secondBootstrap := make(chan struct{}, 1) + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestNumber := atomic.AddInt32(&bootstrapRequests, 1) + if requestNumber == 2 { + secondBootstrap <- struct{}{} + } + endpoint := gateway.endpoint() + if requestNumber == 1 { + endpoint = "ws://127.0.0.1:1/unreachable" + } + if err := json.NewEncoder(w).Encode(&EndpointResp{Code: OK, Data: &Endpoint{ + Url: endpoint, + ClientConfig: &ClientConfig{ + ReconnectCount: 1, + ReconnectInterval: 0, + ReconnectNonce: 0, + PingInterval: 3600, + }, + }}); err != nil { + t.Errorf("encode bootstrap response: %v", err) + } + })) + defer cleanupBootstrap() + + errorEntered := make(chan struct{}, 1) + releaseError := make(chan struct{}) + reconnecting := make(chan struct{}, 1) + reconnected := make(chan struct{}, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithOnError(func(error) { + errorEntered <- struct{}{} + <-releaseError + }), + WithOnReconnecting(func() { reconnecting <- struct{}{} }), + WithOnReconnected(func() { reconnected <- struct{}{} }), + ) + defer client.Close() + result := startLifecycleClient(client, context.Background()) + + waitLifecycleSignal(t, errorEntered, "recoverable Error callback entry") + assertNoLifecycleSignal(t, reconnecting, "Reconnecting callback") + assertNoLifecycleSignal(t, secondBootstrap, "second bootstrap") + close(releaseError) + + waitLifecycleSignal(t, reconnecting, "Reconnecting after Error returned") + waitLifecycleSignal(t, secondBootstrap, "second bootstrap after Error returned") + waitLifecycleSignal(t, reconnected, "Reconnected after Error returned") + client.Close() + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after Close") + } else if err != nil { + t.Fatalf("Start returned %v after Close, want nil", err) + } +} + +func TestReconnectingBlocksDialUntilReturned(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + secondBootstrap := make(chan struct{}, 1) + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestNumber := atomic.AddInt32(&bootstrapRequests, 1) + if requestNumber == 2 { + secondBootstrap <- struct{}{} + } + endpoint := gateway.endpoint() + if requestNumber == 1 { + endpoint = "ws://127.0.0.1:1/unreachable" + } + if err := json.NewEncoder(w).Encode(&EndpointResp{Code: OK, Data: &Endpoint{ + Url: endpoint, + ClientConfig: &ClientConfig{ + ReconnectCount: 1, + ReconnectInterval: 0, + ReconnectNonce: 0, + PingInterval: 3600, + }, + }}); err != nil { + t.Errorf("encode bootstrap response: %v", err) + } + })) + defer cleanupBootstrap() + + reconnectingEntered := make(chan struct{}, 1) + releaseReconnecting := make(chan struct{}) + reconnected := make(chan struct{}, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithOnReconnecting(func() { + reconnectingEntered <- struct{}{} + <-releaseReconnecting + }), + WithOnReconnected(func() { reconnected <- struct{}{} }), + ) + defer client.Close() + result := startLifecycleClient(client, context.Background()) + + waitLifecycleSignal(t, reconnectingEntered, "Reconnecting callback entry") + assertNoLifecycleSignal(t, secondBootstrap, "second bootstrap") + close(releaseReconnecting) + + waitLifecycleSignal(t, secondBootstrap, "second bootstrap after Reconnecting returned") + waitLifecycleSignal(t, reconnected, "Reconnected after Reconnecting returned") + client.Close() + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after Close") + } else if err != nil { + t.Fatalf("Start returned %v after Close, want nil", err) + } +} + +func TestReconnectSequenceNotifiesReconnectingOnce(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestNumber := atomic.AddInt32(&bootstrapRequests, 1) + endpoint := gateway.endpoint() + if requestNumber < 3 { + endpoint = "ws://127.0.0.1:1/unreachable" + } + if err := json.NewEncoder(w).Encode(&EndpointResp{Code: OK, Data: &Endpoint{ + Url: endpoint, + ClientConfig: &ClientConfig{ + ReconnectCount: 2, + ReconnectInterval: 0, + ReconnectNonce: 0, + PingInterval: 3600, + }, + }}); err != nil { + t.Errorf("encode bootstrap response: %v", err) + } + })) + defer cleanupBootstrap() + + var callbackMu sync.Mutex + callbackOrder := make([]string, 0, 4) + record := func(name string) { + callbackMu.Lock() + callbackOrder = append(callbackOrder, name) + callbackMu.Unlock() + } + reconnected := make(chan struct{}, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithOnError(func(error) { record("error") }), + WithOnReconnecting(func() { record("reconnecting") }), + WithOnReconnected(func() { + record("reconnected") + reconnected <- struct{}{} + }), + ) + defer client.Close() + result := startLifecycleClient(client, context.Background()) + + waitLifecycleSignal(t, reconnected, "Reconnected after retry sequence") + callbackMu.Lock() + sequence := strings.Join(callbackOrder, ",") + callbackMu.Unlock() + if sequence != "error,reconnecting,error,reconnected" { + t.Fatalf("reconnect callback sequence = %q, want error,reconnecting,error,reconnected", sequence) + } + if got := atomic.LoadInt32(&bootstrapRequests); got != 3 { + t.Fatalf("bootstrap requests = %d, want 3", got) + } + + client.Close() + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after Close") + } else if err != nil { + t.Fatalf("Start returned %v after Close, want nil", err) + } +} + +func TestRetrieveTokenFailureRetriesWhenRecoverable(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + provider := &lifecycleAssertionProvider{ + failures: []error{errors.New("temporary assertion provider failure")}, + token: &larkcore.Token{Value: "assertion"}, + } + reconnected := make(chan struct{}, 1) + client := NewClient("app-id", "", WithDomain(domain), WithClientAssertionProvider(provider), WithOnReconnected(func() { + reconnected <- struct{}{} + })) + client.reconnectCount = 1 + client.reconnectInterval = 0 + client.reconnectNonce = 0 + result := startLifecycleClient(client, context.Background()) + + waitLifecycleSignal(t, reconnected, "Reconnected after assertion token retry") + if got := provider.callCount(); got != 2 { + t.Fatalf("RetrieveToken calls = %d, want 2", got) + } + if got := atomic.LoadInt32(&bootstrapRequests); got != 1 { + t.Fatalf("bootstrap requests = %d, want 1", got) + } + + client.Close() + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after Close") + } else if err != nil { + t.Fatalf("Start returned %v after Close, want nil", err) + } +} + +func TestRetrieveTokenClientErrorDoesNotRetry(t *testing.T) { + provider := &lifecycleAssertionProvider{ + failures: []error{NewClientError(19001, "invalid assertion")}, + } + client := NewClient("app-id", "", WithClientAssertionProvider(provider)) + + err := client.Start(context.Background()) + if err == nil { + t.Fatal("Start returned nil after ClientAssertionProvider ClientError") + } + clientErr, ok := err.(*ClientError) + if !ok { + t.Fatalf("Start returned %T, want *ClientError", err) + } + if clientErr.Code != 19001 || clientErr.Msg != "invalid assertion" { + t.Fatalf("ClientError = %#v, want original assertion provider error", clientErr) + } + if got := provider.callCount(); got != 1 { + t.Fatalf("RetrieveToken calls = %d, want 1", got) + } +} + +func TestConnectedSessionStartsPingAndAppliesPongConfig(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + logger := &lifecycleRecordingLogger{} + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithLogger(logger), + WithOnReady(func() { ready <- struct{}{} }), + ) + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "Ready") + + var serverConn *websocket.Conn + select { + case serverConn = <-gateway.accepted: + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for gateway connection") + } + + var pingPayload []byte + select { + case pingPayload = <-gateway.messages: + case <-time.After(lifecycleTestTimeout): + t.Fatal("connected session did not send Ping") + } + var ping Frame + if err := ping.Unmarshal(pingPayload); err != nil { + t.Fatalf("decode Ping: %v", err) + } + if FrameType(ping.Method) != FrameTypeControl || Headers(ping.Headers).GetString(HeaderType) != string(MessageTypePing) { + t.Fatalf("first session frame = method %d, type %q; want control Ping", ping.Method, Headers(ping.Headers).GetString(HeaderType)) + } + if logs := logger.String(); !strings.Contains(logs, "ping success") || strings.Contains(logs, "websocket ping succeeded") { + t.Fatalf("Ping logs = %q, want v3_main label ping success", logs) + } + + pongConfig, err := json.Marshal(&ClientConfig{PingInterval: 7}) + if err != nil { + t.Fatalf("encode Pong config: %v", err) + } + pongHeaders := Headers{} + pongHeaders.Add(HeaderType, string(MessageTypePong)) + pong := &Frame{Method: int32(FrameTypeControl), Headers: pongHeaders, Payload: pongConfig} + pongPayload, err := pong.Marshal() + if err != nil { + t.Fatalf("encode Pong: %v", err) + } + if err := serverConn.WriteMessage(websocket.BinaryMessage, pongPayload); err != nil { + t.Fatalf("send Pong: %v", err) + } + + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + timeout := time.NewTimer(lifecycleTestTimeout) + defer timeout.Stop() + for { + _, _, _, pingInterval := client.configSnapshot() + if pingInterval == 7*time.Second { + break + } + select { + case <-ticker.C: + case <-timeout.C: + t.Fatalf("Pong config was not applied; ping interval = %v", pingInterval) + } + } + if logs := logger.String(); !strings.Contains(logs, "receive pong") || strings.Contains(logs, "websocket pong received") { + t.Fatalf("Pong logs = %q, want v3_main label receive pong", logs) + } + + client.Close() + if startErr, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after Close") + } else if startErr != nil { + t.Fatalf("Start returned %v after Close, want nil", startErr) + } +} + +func TestConnectionTimesOutWithoutInboundFrame(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := json.NewEncoder(w).Encode(&EndpointResp{Code: OK, Data: &Endpoint{Url: gateway.endpoint()}}); err != nil { + t.Errorf("encode bootstrap response: %v", err) + } + })) + defer cleanupBootstrap() + + client := NewClient("app-id", "app-secret", WithDomain(domain), WithAutoReconnect(false)) + client.pingInterval = 10 * time.Millisecond + result := startLifecycleClient(client, context.Background()) + + waitAcceptedGatewayConnection(t, gateway) + pingFrame := waitGatewayFrame(t, gateway, "initial Ping") + var ping Frame + if err := ping.Unmarshal(pingFrame.payload); err != nil { + t.Fatalf("decode initial Ping: %v", err) + } + if FrameType(ping.Method) != FrameTypeControl || Headers(ping.Headers).GetString(HeaderType) != string(MessageTypePing) { + t.Fatalf("initial frame = method %d, type %q; want control Ping", ping.Method, Headers(ping.Headers).GetString(HeaderType)) + } + + select { + case err := <-result: + var timeoutErr net.Error + if !errors.As(err, &timeoutErr) || !timeoutErr.Timeout() { + t.Fatalf("Start returned %v, want read timeout after no inbound frame", err) + } + case <-time.After(pongWait(client.pingInterval) + 2*time.Second): + t.Fatal("Start did not return after the read deadline elapsed") + } +} + +func TestSDKPongRefreshesReadDeadline(t *testing.T) { + pongHeaders := Headers{} + pongHeaders.Add(HeaderType, string(MessageTypePong)) + testInboundFrameRefreshesReadDeadline(t, &Frame{Method: int32(FrameTypeControl), Headers: pongHeaders}, "Pong") +} + +func TestDataFrameRefreshesReadDeadline(t *testing.T) { + testInboundFrameRefreshesReadDeadline(t, &Frame{Method: int32(FrameTypeData)}, "Data frame") +} + +func testInboundFrameRefreshesReadDeadline(t *testing.T, frame *Frame, frameName string) { + t.Helper() + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := json.NewEncoder(w).Encode(&EndpointResp{Code: OK, Data: &Endpoint{Url: gateway.endpoint()}}); err != nil { + t.Errorf("encode bootstrap response: %v", err) + } + })) + defer cleanupBootstrap() + + client := NewClient("app-id", "app-secret", WithDomain(domain), WithAutoReconnect(false)) + client.pingInterval = 10 * time.Millisecond + result := startLifecycleClient(client, context.Background()) + + serverConn := waitAcceptedGatewayConnection(t, gateway) + waitGatewayFrame(t, gateway, "initial Ping") + + client.stateMu.Lock() + conn := client.run.conn + client.stateMu.Unlock() + if conn == nil { + t.Fatal("connected client has no current connection") + } + if err := conn.socket.SetReadDeadline(time.Now().Add(500 * time.Millisecond)); err != nil { + t.Fatalf("set short read deadline: %v", err) + } + + payload, err := frame.Marshal() + if err != nil { + t.Fatalf("encode %s: %v", frameName, err) + } + if err := serverConn.WriteMessage(websocket.BinaryMessage, payload); err != nil { + t.Fatalf("send %s: %v", frameName, err) + } + + select { + case err := <-result: + t.Fatalf("Start returned %v after a %s refreshed the read deadline", err, frameName) + case <-time.After(750 * time.Millisecond): + } + + client.Close() + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after Close") + } else if err != nil { + t.Fatalf("Start returned %v after Close, want nil", err) + } +} + +func TestReconnectKeepsOneRunPingUsingCurrentConnection(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestNumber := atomic.AddInt32(&bootstrapRequests, 1) + serviceID := 101 + if requestNumber > 1 { + serviceID = 202 + } + endpoint := fmt.Sprintf("%s?%s=%d", gateway.endpoint(), ServiceID, serviceID) + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(&EndpointResp{ + Code: OK, + Data: &Endpoint{ + Url: endpoint, + ClientConfig: &ClientConfig{ + ReconnectCount: 1, + ReconnectInterval: 1, + ReconnectNonce: 0, + PingInterval: 1, + }, + }, + }); err != nil { + t.Errorf("encode bootstrap response: %v", err) + } + })) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + reconnected := make(chan struct{}, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithOnReady(func() { ready <- struct{}{} }), + WithOnReconnected(func() { reconnected <- struct{}{} }), + ) + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "initial Ready") + firstServerConn := waitAcceptedGatewayConnection(t, gateway) + firstPing := waitGatewayFrame(t, gateway, "initial Ping") + assertGatewayPing(t, firstPing, firstServerConn, 101) + + closeGatewayConn(t, firstServerConn) + waitLifecycleSignal(t, reconnected, "Reconnected") + secondServerConn := waitAcceptedGatewayConnection(t, gateway) + + select { + case frame := <-gateway.frames: + t.Fatalf("replacement connection started a second immediate Ping worker: connection=%p payload=%q", frame.conn, frame.payload) + case <-time.After(200 * time.Millisecond): + } + secondPing := waitGatewayFrame(t, gateway, "scheduled Ping on replacement connection") + assertGatewayPing(t, secondPing, secondServerConn, 202) + + client.Close() + if startErr, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after Close") + } else if startErr != nil { + t.Fatalf("Start returned %v after Close, want nil", startErr) + } + select { + case frame := <-gateway.frames: + t.Fatalf("Ping worker wrote after Close: connection=%p payload=%q", frame.conn, frame.payload) + case <-time.After(200 * time.Millisecond): + } +} + +func assertGatewayPing(t *testing.T, frame lifecycleGatewayFrame, wantConn *websocket.Conn, wantService int32) { + t.Helper() + if frame.conn != wantConn { + t.Fatalf("Ping used connection %p, want %p", frame.conn, wantConn) + } + var ping Frame + if err := ping.Unmarshal(frame.payload); err != nil { + t.Fatalf("decode Ping: %v", err) + } + if FrameType(ping.Method) != FrameTypeControl || Headers(ping.Headers).GetString(HeaderType) != string(MessageTypePing) { + t.Fatalf("frame = method %d, type %q; want control Ping", ping.Method, Headers(ping.Headers).GetString(HeaderType)) + } + if ping.Service != wantService { + t.Fatalf("Ping service = %d, want %d", ping.Service, wantService) + } +} + +func TestPreCanceledStartIsTerminalWithoutNetworkOrErrorCallback(t *testing.T) { + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&bootstrapRequests, 1) + http.Error(w, "unexpected bootstrap", http.StatusServiceUnavailable) + })) + defer cleanupBootstrap() + + var errorCallbacks int32 + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnError(func(error) { atomic.AddInt32(&errorCallbacks, 1) }), + ) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + if err := client.Start(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("pre-canceled Start returned %v, want context.Canceled", err) + } + if got := atomic.LoadInt32(&bootstrapRequests); got != 0 { + t.Fatalf("pre-canceled Start made %d bootstrap requests, want 0", got) + } + if got := atomic.LoadInt32(&errorCallbacks); got != 0 { + t.Fatalf("pre-canceled Start invoked OnError %d times, want 0", got) + } + + if err := client.Start(context.Background()); err == nil { + t.Fatal("second Start returned nil after a pre-canceled Start, want lifecycle error") + } + if got := atomic.LoadInt32(&bootstrapRequests); got != 0 { + t.Fatalf("terminal Client made %d bootstrap requests, want 0", got) + } +} + +func TestConcurrentStartRejectsSecondCallerBeforeNetworkUnblocks(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + requestStarted := make(chan struct{}, 1) + releaseBootstrap := make(chan struct{}) + var releaseBootstrapOnce sync.Once + releaseBootstrapNow := func() { + releaseBootstrapOnce.Do(func() { close(releaseBootstrap) }) + } + defer releaseBootstrapNow() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&bootstrapRequests, 1) + requestStarted <- struct{}{} + select { + case <-releaseBootstrap: + case <-r.Context().Done(): + return + } + if err := json.NewEncoder(w).Encode(&EndpointResp{Code: OK, Data: &Endpoint{Url: gateway.endpoint()}}); err != nil { + return + } + })) + defer cleanupBootstrap() + + ready := make(chan struct{}, 2) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { ready <- struct{}{} }), + ) + first := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, requestStarted, "first bootstrap request") + second := startLifecycleClient(client, context.Background()) + + select { + case err := <-second: + if err == nil { + t.Error("concurrent Start returned nil, want lifecycle error") + } + case <-time.After(300 * time.Millisecond): + t.Error("concurrent Start blocked behind the active lifecycle") + } + + releaseBootstrapNow() + waitLifecycleSignal(t, ready, "first Ready callback") + client.Close() + if err, ok := waitLifecycleResult(first); !ok { + t.Error("first Start did not return after Close") + } else if err != nil { + t.Errorf("first Start returned %v after Close, want nil", err) + } + if got := atomic.LoadInt32(&bootstrapRequests); got != 1 { + t.Errorf("concurrent Starts made %d bootstrap requests, want 1", got) + } +} + +func TestContextCancellationWinsOverReadFailure(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + disconnected := make(chan struct{}, 1) + var errorCallbacks int32 + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { ready <- struct{}{} }), + WithOnDisconnected(func() { disconnected <- struct{}{} }), + WithOnError(func(error) { atomic.AddInt32(&errorCallbacks, 1) }), + ) + ctx, cancel := context.WithCancel(context.Background()) + result := startLifecycleClient(client, ctx) + waitLifecycleSignal(t, ready, "Ready") + + cancel() + err, ok := waitLifecycleResult(result) + if !ok { + t.Error("Start did not return after caller context cancellation") + client.Close() + } else if !errors.Is(err, context.Canceled) { + t.Errorf("Start returned %v, want context.Canceled", err) + } + waitLifecycleSignal(t, disconnected, "Disconnected after context cancellation") + if got := atomic.LoadInt32(&errorCallbacks); got != 0 { + t.Errorf("normal context cancellation invoked OnError %d times, want 0", got) + } +} + +func TestCloseWinsOverReadFailureAndIsIdempotent(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + disconnected := make(chan struct{}, 8) + var errorCallbacks int32 + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { ready <- struct{}{} }), + WithOnDisconnected(func() { disconnected <- struct{}{} }), + WithOnError(func(error) { atomic.AddInt32(&errorCallbacks, 1) }), + ) + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "Ready") + + var closeWG sync.WaitGroup + for i := 0; i < 8; i++ { + closeWG.Add(1) + go func() { + defer closeWG.Done() + client.Close() + }() + } + closeDone := make(chan struct{}) + go func() { + closeWG.Wait() + close(closeDone) + }() + waitLifecycleSignal(t, closeDone, "concurrent Close calls") + + if err, ok := waitLifecycleResult(result); !ok { + t.Error("Start did not return after Close") + } else if err != nil { + t.Errorf("Start returned %v after Close, want nil", err) + } + waitLifecycleSignal(t, disconnected, "Disconnected after Close") + select { + case <-disconnected: + t.Error("Disconnected ran more than once for one connection") + default: + } + if got := atomic.LoadInt32(&errorCallbacks); got != 0 { + t.Errorf("normal Close invoked OnError %d times, want 0", got) + } +} + +func TestStartWaitsForDisconnectedCallback(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + disconnectedEntered := make(chan struct{}, 1) + releaseDisconnected := make(chan struct{}) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { ready <- struct{}{} }), + WithOnDisconnected(func() { + disconnectedEntered <- struct{}{} + <-releaseDisconnected + }), + ) + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "Ready") + + client.Close() + waitLifecycleSignal(t, disconnectedEntered, "Disconnected callback entry") + assertNoLifecycleResult(t, result, "Start") + + close(releaseDisconnected) + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after Disconnected callback returned") + } else if err != nil { + t.Fatalf("Start returned %v after Close, want nil", err) + } +} + +func TestCloseAndWaitWaitsForDisconnectedCallback(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + disconnectedEntered := make(chan struct{}, 1) + releaseDisconnected := make(chan struct{}) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { ready <- struct{}{} }), + WithOnDisconnected(func() { + disconnectedEntered <- struct{}{} + <-releaseDisconnected + }), + ) + startResult := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "Ready") + + closeResult := make(chan error, 1) + go func() { + closeResult <- client.CloseAndWait(context.Background()) + }() + waitLifecycleSignal(t, disconnectedEntered, "Disconnected callback entry") + assertNoLifecycleResult(t, closeResult, "CloseAndWait") + + close(releaseDisconnected) + if err, completed := waitLifecycleResult(closeResult); !completed || err != nil { + t.Fatalf("CloseAndWait returned %v, completed=%v", err, completed) + } + if err, completed := waitLifecycleResult(startResult); !completed || err != nil { + t.Fatalf("Start returned %v, completed=%v", err, completed) + } +} + +func TestCloseAndWaitContextCanCancel(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + disconnectedEntered := make(chan struct{}, 1) + releaseDisconnected := make(chan struct{}) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { ready <- struct{}{} }), + WithOnDisconnected(func() { + disconnectedEntered <- struct{}{} + <-releaseDisconnected + }), + ) + startResult := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "Ready") + + waitCtx, cancel := context.WithTimeout(context.Background(), lifecycleNoProgressTimeout) + defer cancel() + closeResult := make(chan error, 1) + go func() { + closeResult <- client.CloseAndWait(waitCtx) + }() + waitLifecycleSignal(t, disconnectedEntered, "Disconnected callback entry") + if err, completed := waitLifecycleResult(closeResult); !completed || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("CloseAndWait returned %v, completed=%v", err, completed) + } + + close(releaseDisconnected) + if err, completed := waitLifecycleResult(startResult); !completed || err != nil { + t.Fatalf("Start returned %v, completed=%v", err, completed) + } +} + +func TestReadyCallbackPanicIsRedacted(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + const panicMarker = "ready-callback-sensitive-panic" + readyEntered := make(chan struct{}, 1) + logger := &lifecycleRecordingLogger{} + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithLogger(logger), + WithOnReady(func() { + readyEntered <- struct{}{} + panic(panicMarker) + }), + ) + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, readyEntered, "Ready callback entry") + + client.Close() + if _, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after Close") + } + assertLifecycleTextDoesNotContain(t, logger.String(), panicMarker) +} + +func TestReconnectFailureReportsEachAttemptOnce(t *testing.T) { + const serverMessage = "bootstrap-server-sensitive-marker" + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&bootstrapRequests, 1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + if err := json.NewEncoder(w).Encode(&EndpointResp{Code: InternalError, Msg: serverMessage}); err != nil { + t.Errorf("encode bootstrap error: %v", err) + } + })) + defer cleanupBootstrap() + + logger := &lifecycleRecordingLogger{} + callbackErrs := make(chan error, 3) + client := NewClient("app-id", "app-secret", WithDomain(domain), WithLogger(logger)) + client.SetOnError(func(err error) { callbackErrs <- err }) + client.reconnectCount = 1 + client.reconnectInterval = 0 + client.reconnectNonce = 0 + + err := client.Start(context.Background()) + if err == nil { + t.Fatal("Start returned nil after reconnect attempts were exhausted") + } + if err.Error() != "unable to connect to server after 1 retries" { + t.Fatalf("Start error = %q, want reconnect exhaustion error", err) + } + if got := atomic.LoadInt32(&bootstrapRequests); got != 2 { + t.Fatalf("bootstrap requests = %d, want 2", got) + } + if got := len(callbackErrs); got != 2 { + t.Fatalf("OnError calls = %d, want 2 for the initial and retried connection failures", got) + } + for index := 0; index < 2; index++ { + if callbackErr := <-callbackErrs; callbackErr == nil { + t.Errorf("OnError call %d received nil", index+1) + } else if _, ok := callbackErr.(*ServerError); !ok { + t.Errorf("OnError call %d received %T, want *ServerError", index+1, callbackErr) + } + } + + logs := logger.String() + for _, message := range []string{ + "websocket initial connection failed", + "websocket reconnecting: attempt 1/1", + "websocket reconnect attempt 1 failed", + "websocket reconnect attempts exhausted after 1 attempts", + } { + if !strings.Contains(logs, message) { + t.Errorf("lifecycle logs missing %q: %s", message, logs) + } + } + assertLifecycleTextDoesNotContain(t, logs, serverMessage) +} + +func TestReconnectExhaustionWithNoAttemptsDoesNotRepeatOnError(t *testing.T) { + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&bootstrapRequests, 1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusServiceUnavailable) + if err := json.NewEncoder(w).Encode(&EndpointResp{Code: InternalError, Msg: "temporarily unavailable"}); err != nil { + t.Errorf("encode bootstrap error: %v", err) + } + })) + defer cleanupBootstrap() + + callbackErrs := make(chan error, 2) + client := NewClient("app-id", "app-secret", WithDomain(domain), WithOnError(func(err error) { + callbackErrs <- err + })) + client.reconnectCount = 0 + + if err := client.Start(context.Background()); err == nil { + t.Fatal("Start returned nil after reconnect attempts were exhausted") + } + if got := atomic.LoadInt32(&bootstrapRequests); got != 1 { + t.Fatalf("bootstrap requests = %d, want 1", got) + } + if got := len(callbackErrs); got != 1 { + t.Fatalf("OnError calls = %d, want 1 for the initial connection failure", got) + } +} + +func TestRuntimeDeadlineClosesConnectionAndReturnsDeadline(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + disconnected := make(chan struct{}, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { ready <- struct{}{} }), + WithOnDisconnected(func() { disconnected <- struct{}{} }), + ) + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + result := startLifecycleClient(client, ctx) + waitLifecycleSignal(t, ready, "Ready before deadline") + + err, ok := waitLifecycleResult(result) + if !ok { + t.Error("Start did not return after its running context deadline") + client.Close() + } else if !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("Start returned %v, want context.DeadlineExceeded", err) + } + waitLifecycleSignal(t, disconnected, "Disconnected after deadline") + if got := atomic.LoadInt32(&bootstrapRequests); got != 1 { + t.Errorf("deadline triggered %d bootstrap requests, want 1", got) + } +} + +func TestTerminalReadFailureWinsOverReentrantClose(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + errorCallback := make(chan error, 2) + var client *Client + client = NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { ready <- struct{}{} }), + WithOnError(func(err error) { + errorCallback <- err + client.Close() + }), + ) + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "Ready") + + var serverConn *websocket.Conn + select { + case serverConn = <-gateway.accepted: + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for gateway connection") + } + closeGatewayConn(t, serverConn) + + var callbackErr error + select { + case callbackErr = <-errorCallback: + case <-time.After(lifecycleTestTimeout): + t.Error("terminal read failure did not invoke OnError") + } + startErr, ok := waitLifecycleResult(result) + if !ok { + t.Error("terminal read failure did not end Start") + client.Close() + } else if startErr == nil { + t.Error("terminal read failure followed by Close returned nil, want failure") + } + if callbackErr != nil && startErr != nil && callbackErr.Error() != startErr.Error() { + t.Errorf("OnError received %q, Start returned %q", callbackErr, startErr) + } + select { + case extra := <-errorCallback: + t.Errorf("OnError ran more than once, extra error: %v", extra) + default: + } +} + +func TestDisconnectedWaitsForReadyCallback(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + readyEntered := make(chan struct{}, 1) + releaseReady := make(chan struct{}) + disconnected := make(chan struct{}, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { + readyEntered <- struct{}{} + <-releaseReady + }), + WithOnDisconnected(func() { disconnected <- struct{}{} }), + ) + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, readyEntered, "Ready callback entry") + + var serverConn *websocket.Conn + select { + case serverConn = <-gateway.accepted: + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for gateway connection") + } + closeGatewayConn(t, serverConn) + + if startErr, startReturned := waitLifecycleResult(result); startReturned { + t.Fatalf("Start returned %v while Ready callback was blocked", startErr) + } + close(releaseReady) + + waitLifecycleSignal(t, disconnected, "Disconnected after Ready callback returned") + startErr, startReturned := waitLifecycleResult(result) + if !startReturned { + t.Error("Start did not return after Ready callback returned") + client.Close() + } else if startErr == nil { + t.Error("server disconnect returned nil, want terminal failure") + } +} + +func TestDisconnectedWaitsForReconnectedCallback(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + thirdBootstrap := make(chan struct{}, 1) + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestNumber := atomic.AddInt32(&bootstrapRequests, 1) + if requestNumber == 3 { + thirdBootstrap <- struct{}{} + } + reconnectInterval := 0 + if requestNumber == 2 { + reconnectInterval = 1 + } + if err := json.NewEncoder(w).Encode(&EndpointResp{Code: OK, Data: &Endpoint{ + Url: gateway.endpoint(), + ClientConfig: &ClientConfig{ + ReconnectCount: 2, + ReconnectInterval: reconnectInterval, + ReconnectNonce: 0, + PingInterval: 3600, + }, + }}); err != nil { + t.Errorf("encode bootstrap response: %v", err) + } + })) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + reconnecting := make(chan struct{}, 2) + reconnectedEntered := make(chan struct{}, 1) + releaseReconnected := make(chan struct{}) + disconnected := make(chan struct{}, 2) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithOnReady(func() { ready <- struct{}{} }), + WithOnReconnecting(func() { reconnecting <- struct{}{} }), + WithOnReconnected(func() { + reconnectedEntered <- struct{}{} + <-releaseReconnected + }), + WithOnDisconnected(func() { disconnected <- struct{}{} }), + ) + defer client.Close() + result := startLifecycleClient(client, context.Background()) + + waitLifecycleSignal(t, ready, "initial Ready") + firstServerConn := waitAcceptedGatewayConnection(t, gateway) + closeGatewayConn(t, firstServerConn) + waitLifecycleSignal(t, reconnecting, "first Reconnecting") + secondServerConn := waitAcceptedGatewayConnection(t, gateway) + waitLifecycleSignal(t, reconnectedEntered, "Reconnected callback entry") + waitLifecycleSignal(t, disconnected, "first Disconnected") + + closeGatewayConn(t, secondServerConn) + assertNoLifecycleSignal(t, disconnected, "second Disconnected") + assertNoLifecycleResult(t, result, "Start") + assertNoLifecycleSignal(t, thirdBootstrap, "third bootstrap") + close(releaseReconnected) + + waitLifecycleSignal(t, disconnected, "second Disconnected after Reconnected returned") + client.Close() + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after Close") + } else if err != nil { + t.Fatalf("Start returned %v after Close, want nil", err) + } +} + +func TestLifecycleCallbacksCanCloseClient(t *testing.T) { + for _, stage := range []string{"ready", "recoverable_error", "reconnecting", "reconnected"} { + stage := stage + t.Run(stage, func(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestNumber := atomic.AddInt32(&bootstrapRequests, 1) + endpoint := gateway.endpoint() + if stage != "ready" && requestNumber == 1 { + endpoint = "ws://127.0.0.1:1/unreachable" + } + if err := json.NewEncoder(w).Encode(&EndpointResp{Code: OK, Data: &Endpoint{ + Url: endpoint, + ClientConfig: &ClientConfig{ + ReconnectCount: 1, + ReconnectInterval: 0, + ReconnectNonce: 0, + PingInterval: 3600, + }, + }}); err != nil { + t.Errorf("encode bootstrap response: %v", err) + } + })) + defer cleanupBootstrap() + + callbackReturned := make(chan struct{}, 1) + var client *Client + closeFromCallback := func() { + client.Close() + callbackReturned <- struct{}{} + } + options := []ClientOption{WithDomain(domain)} + switch stage { + case "ready": + options = append(options, WithOnReady(closeFromCallback)) + case "recoverable_error": + options = append(options, WithOnError(func(error) { closeFromCallback() })) + case "reconnecting": + options = append(options, WithOnReconnecting(closeFromCallback)) + case "reconnected": + options = append(options, WithOnReconnected(closeFromCallback)) + } + client = NewClient("app-id", "app-secret", options...) + defer client.Close() + result := startLifecycleClient(client, context.Background()) + + waitLifecycleSignal(t, callbackReturned, stage+" callback Close return") + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after callback Close") + } else if err != nil { + t.Fatalf("Start returned %v after callback Close, want nil", err) + } + }) + } +} + +func TestNilReadyCallbackDoesNotBlockDisconnected(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &bootstrapRequests) + defer cleanupBootstrap() + + disconnected := make(chan struct{}, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnDisconnected(func() { disconnected <- struct{}{} }), + ) + result := startLifecycleClient(client, context.Background()) + + var serverConn *websocket.Conn + select { + case serverConn = <-gateway.accepted: + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for gateway connection") + } + closeGatewayConn(t, serverConn) + waitLifecycleSignal(t, disconnected, "Disconnected with nil Ready callback") + if err, ok := waitLifecycleResult(result); !ok { + t.Error("nil Ready callback left Start blocked after disconnect") + client.Close() + } else if err == nil { + t.Error("server disconnect returned nil, want terminal failure") + } +} + +func TestCloseCancelsBlockedBootstrapAndReturnsNil(t *testing.T) { + requestStarted := make(chan struct{}, 1) + requestCanceled := make(chan struct{}, 1) + releaseHandler := make(chan struct{}) + var releaseHandlerOnce sync.Once + releaseHandlerNow := func() { + releaseHandlerOnce.Do(func() { close(releaseHandler) }) + } + defer releaseHandlerNow() + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var request BootstrapRequest + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + t.Errorf("decode blocked bootstrap request: %v", err) + return + } + requestStarted <- struct{}{} + select { + case <-r.Context().Done(): + requestCanceled <- struct{}{} + case <-releaseHandler: + http.Error(w, "released by test", http.StatusServiceUnavailable) + } + })) + defer cleanupBootstrap() + + client := NewClient("app-id", "app-secret", WithDomain(domain), WithAutoReconnect(false)) + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, requestStarted, "bootstrap request") + + closeReturned := make(chan struct{}) + go func() { + client.Close() + close(closeReturned) + }() + select { + case <-closeReturned: + case <-time.After(300 * time.Millisecond): + t.Error("Close blocked while bootstrap was in flight") + releaseHandlerNow() + waitLifecycleSignal(t, closeReturned, "Close after releasing bootstrap") + } + + select { + case <-requestCanceled: + case <-time.After(300 * time.Millisecond): + t.Error("Close did not cancel the in-flight bootstrap request") + } + if err, ok := waitLifecycleResult(result); !ok { + t.Error("Start did not return after Close canceled bootstrap") + } else if err != nil { + t.Errorf("Start returned %v after Close, want nil", err) + } +} + +func TestStartupFailureCanRetryButSuccessfulRunIsTerminal(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var requests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestNumber := atomic.AddInt32(&requests, 1) + if requestNumber == 1 || requestNumber > 2 { + http.Error(w, fmt.Sprintf("bootstrap failure %d", requestNumber), http.StatusServiceUnavailable) + return + } + if err := json.NewEncoder(w).Encode(&EndpointResp{Code: OK, Data: &Endpoint{Url: gateway.endpoint()}}); err != nil { + return + } + })) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { ready <- struct{}{} }), + ) + if err := client.Start(context.Background()); err == nil { + t.Fatal("bootstrap failure returned nil") + } + + second := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "Ready after retry") + client.Close() + if err, ok := waitLifecycleResult(second); !ok { + t.Error("successful retry did not return after Close") + } else if err != nil { + t.Errorf("successful retry returned %v after Close, want nil", err) + } + + third := startLifecycleClient(client, context.Background()) + if err, ok := waitLifecycleResult(third); !ok { + t.Error("Start after a successful run did not immediately return a lifecycle error") + client.Close() + } else if err == nil { + t.Error("Start after a successful run returned nil, want lifecycle error") + } + if got := atomic.LoadInt32(&requests); got != 2 { + t.Errorf("terminal Client made %d bootstrap requests, want 2 total", got) + } +} + +func TestContextCancellationStopsReconnectInterval(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + requestNumbers := make(chan int32, 4) + var requests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestNumber := atomic.AddInt32(&requests, 1) + requestNumbers <- requestNumber + endpoint := gateway.endpoint() + if requestNumber > 1 { + endpoint = "ws://127.0.0.1:1/unreachable" + } + if err := json.NewEncoder(w).Encode(&EndpointResp{ + Code: OK, + Data: &Endpoint{ + Url: endpoint, + ClientConfig: &ClientConfig{ + ReconnectCount: 3, + ReconnectInterval: 30, + PingInterval: 3600, + }, + }, + }); err != nil { + return + } + })) + defer cleanupBootstrap() + + ready := make(chan struct{}, 1) + reconnecting := make(chan struct{}, 1) + retryError := make(chan error, 2) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithOnReady(func() { ready <- struct{}{} }), + WithOnReconnecting(func() { reconnecting <- struct{}{} }), + WithOnError(func(err error) { retryError <- err }), + ) + ctx, cancel := context.WithCancel(context.Background()) + result := startLifecycleClient(client, ctx) + waitLifecycleSignal(t, ready, "Ready before reconnect") + + var serverConn *websocket.Conn + select { + case serverConn = <-gateway.accepted: + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for initial gateway connection") + } + closeGatewayConn(t, serverConn) + waitLifecycleSignal(t, reconnecting, "Reconnecting") + + for { + select { + case requestNumber := <-requestNumbers: + if requestNumber >= 2 { + goto retryStarted + } + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for reconnect bootstrap") + } + } + +retryStarted: + select { + case <-retryError: + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for failed reconnect attempt") + } + cancel() + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after canceling reconnect wait") + } else if !errors.Is(err, context.Canceled) { + t.Fatalf("Start returned %v, want context.Canceled", err) + } + if got := atomic.LoadInt32(&requests); got != 2 { + t.Fatalf("canceled reconnect made %d bootstrap requests, want 2", got) + } +} + +func TestReconnectPublishesOneReplacementConnection(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var requests int32 + domain, cleanupBootstrap := installLifecycleBootstrapHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&requests, 1) + if err := json.NewEncoder(w).Encode(&EndpointResp{ + Code: OK, + Data: &Endpoint{ + Url: gateway.endpoint(), + ClientConfig: &ClientConfig{ + ReconnectCount: 1, + ReconnectInterval: 1, + PingInterval: 3600, + }, + }, + }); err != nil { + return + } + })) + defer cleanupBootstrap() + + ready := make(chan struct{}, 2) + reconnecting := make(chan struct{}, 2) + reconnected := make(chan struct{}, 2) + disconnected := make(chan struct{}, 3) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithOnReady(func() { ready <- struct{}{} }), + WithOnReconnecting(func() { reconnecting <- struct{}{} }), + WithOnReconnected(func() { reconnected <- struct{}{} }), + WithOnDisconnected(func() { disconnected <- struct{}{} }), + ) + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "initial Ready") + + var firstServerConn *websocket.Conn + select { + case firstServerConn = <-gateway.accepted: + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for initial gateway connection") + } + closeGatewayConn(t, firstServerConn) + waitLifecycleSignal(t, reconnecting, "Reconnecting") + waitLifecycleSignal(t, reconnected, "Reconnected") + waitLifecycleSignal(t, disconnected, "first Disconnected") + + select { + case <-gateway.accepted: + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for replacement gateway connection") + } + client.Close() + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return after closing reconnected Client") + } else if err != nil { + t.Fatalf("Start returned %v after Close, want nil", err) + } + waitLifecycleSignal(t, disconnected, "replacement Disconnected") + select { + case <-ready: + t.Fatal("reconnect invoked Ready again") + default: + } + select { + case <-reconnecting: + t.Fatal("reconnect invoked Reconnecting more than once") + default: + } + select { + case <-reconnected: + t.Fatal("reconnect invoked Reconnected more than once") + default: + } + if got := atomic.LoadInt32(&requests); got != 2 { + t.Fatalf("reconnect made %d bootstrap requests, want 2", got) + } +} + +func TestLifecycleSettersRaceWithClose(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + var requests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, gateway.endpoint(), &requests) + defer cleanupBootstrap() + ready := make(chan struct{}, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithOnReady(func() { ready <- struct{}{} }), + ) + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "Ready") + + const workers = 8 + const iterations = 100 + var setters sync.WaitGroup + for worker := 0; worker < workers; worker++ { + setters.Add(1) + go func() { + defer setters.Done() + for i := 0; i < iterations; i++ { + client.SetOnReady(func() {}) + client.SetOnError(func(error) {}) + client.SetOnReconnecting(func() {}) + client.SetOnReconnected(func() {}) + client.SetOnDisconnected(func() {}) + } + }() + } + client.Close() + setters.Wait() + if err, ok := waitLifecycleResult(result); !ok { + t.Fatal("Start did not return while callback setters raced with Close") + } else if err != nil { + t.Fatalf("Start returned %v after Close, want nil", err) + } +} diff --git a/ws/client_message.go b/ws/client_message.go new file mode 100644 index 00000000..df81c637 --- /dev/null +++ b/ws/client_message.go @@ -0,0 +1,167 @@ +package ws + +import ( + "encoding/json" + "net/http" + "strconv" + "time" + + ws "github.com/gorilla/websocket" +) + +type eventMessage struct { + frame Frame + headers Headers + messageType string + messageID string + traceID string + payload []byte + startedAt int64 +} + +// startMessageTask atomically admits one SDK-owned message task. Once a stop +// wins, the same run cannot add more tracked work. +func (c *Client) startMessageTask(run *clientRun, msg []byte) bool { + if run.ctx.Err() != nil { + return false + } + c.stateMu.Lock() + defer c.stateMu.Unlock() + if run.stopReason != runStopNone { + return false + } + run.wg.Add(1) + go c.handleMessageTask(run, msg) + return true +} + +func (c *Client) handleMessageTask(run *clientRun, msg []byte) { + defer run.wg.Done() + defer func() { + if recover() != nil { + c.logger.Error(run.ctx, c.fmtLog("websocket message handler panicked")...) + } + }() + + var frame Frame + if err := frame.Unmarshal(msg); err != nil { + c.logger.Error(run.ctx, c.fmtLog("websocket message decode failed")...) + return + } + + switch FrameType(frame.Method) { + case FrameTypeControl: + c.handleControlFrame(run, frame) + case FrameTypeData: + c.handleDataFrame(run, frame) + default: + } +} + +func (c *Client) handleDataFrame(run *clientRun, frame Frame) { + hs := Headers(frame.Headers) + sum := hs.GetInt(HeaderSum) + seq := hs.GetInt(HeaderSeq) + msgID := hs.GetString(HeaderMessageID) + traceID := hs.GetString(HeaderTraceID) + messageType := hs.GetString(HeaderType) + + payload := frame.Payload + if sum > 1 { + payload = c.combine(msgID, sum, seq, payload) + if payload == nil { + return + } + } + + c.logger.Debug(run.ctx, c.fmtLog("receive message, message_type: %s, message_id: %s, trace_id: %s, payload: %s", + messageType, msgID, traceID, payload)) + if MessageType(messageType) != MessageTypeEvent || c.eventHandler == nil { + return + } + + startedAt := time.Now().UnixNano() / int64(time.Millisecond) // 兼容 go < 1.17 + handler := c.eventHandler + event := eventMessage{ + frame: frame, + headers: hs, + messageType: messageType, + messageID: msgID, + traceID: traceID, + payload: payload, + startedAt: startedAt, + } + response, err := handler.Do(run.ctx, event.payload) + c.writeEventResponse(run, event, response, err) +} + +func (c *Client) writeEventResponse( + run *clientRun, + event eventMessage, + response interface{}, + handlerErr error, +) { + endedAt := time.Now().UnixNano() / int64(time.Millisecond) + event.headers.Add(HeaderBizRt, strconv.FormatInt(endedAt-event.startedAt, 10)) + + resp := NewResponseByCode(http.StatusOK) + if handlerErr != nil { + c.logger.Error(run.ctx, c.fmtLog("handle message failed, message_type: %s, message_id: %s, trace_id: %s, err: %v", + event.messageType, event.messageID, event.traceID, handlerErr)...) + resp = NewResponseByCode(http.StatusInternalServerError) + } else if response != nil { + data, err := json.Marshal(response) + if err != nil { + c.logger.Error(run.ctx, c.fmtLog("handle message failed, message_type: %s, message_id: %s, trace_id: %s, err: %v", + event.messageType, event.messageID, event.traceID, err)...) + resp = NewResponseByCode(http.StatusInternalServerError) + } else { + resp.Data = data + } + } + + payload, err := json.Marshal(resp) + if err != nil { + c.logger.Error(run.ctx, c.fmtLog("response message encode failed")...) + return + } + event.frame.Payload = payload + event.frame.Headers = event.headers + message, err := event.frame.Marshal() + if err != nil { + c.logger.Error(run.ctx, c.fmtLog("response frame encode failed")...) + return + } + + if err := c.writeMessage(run, ws.BinaryMessage, message); err != nil { + c.logger.Error(run.ctx, c.fmtLog("response message failed, type: %s, message_id: %s, trace_id: %s", event.messageType, event.messageID, event.traceID)...) + } +} + +func (c *Client) combine(msgID string, sum, seq int, bs []byte) []byte { + val := c.cache.Get(msgID) + if val == nil { + buf := make([][]byte, sum) + buf[seq] = bs + c.cache.Set(msgID, buf, 5*time.Second) + return nil + } + + buf := val.([][]byte) + buf[seq] = bs + capacity := 0 + for _, v := range buf { + if len(v) == 0 { + c.cache.Set(msgID, buf, 5*time.Second) + return nil + } + capacity += len(v) + } + + payload := make([]byte, 0, capacity) + for _, v := range buf { + payload = append(payload, v...) + } + + return payload +} diff --git a/ws/client_publish_test.go b/ws/client_publish_test.go new file mode 100644 index 00000000..84ca5494 --- /dev/null +++ b/ws/client_publish_test.go @@ -0,0 +1,80 @@ +package ws + +import ( + "context" + "net/http" + "sync/atomic" + "testing" + "time" + + websocket "github.com/gorilla/websocket" +) + +func dialLifecycleCandidate(t *testing.T, gateway *lifecycleGateway) *websocket.Conn { + t.Helper() + conn, resp, err := websocket.DefaultDialer.Dial(gateway.endpoint(), nil) + if resp != nil && resp.Body != nil { + defer func() { + if closeErr := resp.Body.Close(); closeErr != nil { + t.Errorf("close candidate response body: %v", closeErr) + } + }() + } + if err != nil { + t.Fatalf("dial candidate: %v", err) + } + if resp == nil || resp.StatusCode != http.StatusSwitchingProtocols { + t.Fatalf("candidate handshake status = %v, want %d", resp, http.StatusSwitchingProtocols) + } + return conn +} + +func TestActivateConnectionRejectsStoppedRun(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + socket := dialLifecycleCandidate(t, gateway) + runCtx, runCancel := context.WithCancel(context.Background()) + run := &clientRun{ctx: runCtx, cancel: runCancel} + conn := &clientConn{ + socket: socket, + connectionResult: make(chan error, 1), + safeEndpoint: safeEndpoint(gateway.endpoint()), + } + var readyCount int32 + var disconnectedCount int32 + client := NewClient("app-id", "app-secret", + WithOnReady(func() { atomic.AddInt32(&readyCount, 1) }), + WithOnDisconnected(func() { atomic.AddInt32(&disconnectedCount, 1) }), + ) + client.run = run + + if !client.stopRun(run, runStopByClose, nil) { + t.Fatal("stopRun rejected the active run") + } + if client.activateConnection(run, conn, false) { + t.Fatal("activateConnection accepted a stopped run") + } + if run.conn != nil { + t.Fatal("activateConnection stored a candidate on a stopped run") + } + if err := socket.WriteMessage(websocket.BinaryMessage, []byte("probe")); err == nil { + t.Fatal("rejected candidate socket remained writable") + } + if got := atomic.LoadInt32(&readyCount); got != 0 { + t.Errorf("rejected activation invoked Ready %d times, want 0", got) + } + if got := atomic.LoadInt32(&disconnectedCount); got != 0 { + t.Errorf("rejected activation invoked Disconnected %d times, want 0", got) + } + + waitDone := make(chan struct{}) + go func() { + run.wg.Wait() + close(waitDone) + }() + select { + case <-waitDone: + case <-time.After(time.Second): + t.Fatal("rejected activation registered workers") + } +} diff --git a/ws/client_race_test.go b/ws/client_race_test.go index d7f1b181..8e9d5764 100644 --- a/ws/client_race_test.go +++ b/ws/client_race_test.go @@ -1,28 +1,21 @@ package ws import ( + "context" "sync" "testing" "time" ) // These tests exercise the concurrent read/write paths on the connection-control -// fields (reconnectCount / reconnectInterval / reconnectNonce / pingInterval / -// conn / serviceID). They are meant to be run under `go test -race`; the data +// fields and the active run/connection identity. They are meant to be run under +// `go test -race`; the data // race only surfaces under the race detector, so a plain run passing is not // sufficient evidence the bug is fixed. // -// The reader side goes through two locked snapshot accessors that the fix -// introduces: configSnapshot() for the four config fields and connState() for -// conn/serviceID. The writer side is configure(), which must take c.mu. - -// setServiceIDLocked writes serviceID under c.mu, standing in for connect()'s -// in-lock write so the read-path synchronization (connState) is what gets raced. -func (c *Client) setServiceIDLocked(id string) { - c.mu.Lock() - defer c.mu.Unlock() - c.serviceID = id -} +// The reader side goes through configSnapshot, currentConnection and exact +// connection checks. The writer side uses configure/applyConfig and connection +// replacement, which share stateMu with lifecycle identity. // newRaceClient builds an in-memory Client without establishing a connection. // conn stays nil on purpose: these tests cover the field-synchronization paths, @@ -99,16 +92,26 @@ func TestConfigureAndConfigSnapshotNoRace(t *testing.T) { wg.Wait() } -// configure racing connState (reader of conn/serviceID, as pingLoop and -// receiveMessageLoop do) must not data-race. serviceID is written under c.mu in -// production (inside connect); here a locked white-box helper stands in for that -// writer so the read path's synchronization is what gets exercised. +// Run-level config updates and current-connection snapshots racing connection +// replacement must not data-race. func TestConfigureAndConnStateNoRace(t *testing.T) { c := newRaceClient() + runCtx, runCancel := context.WithCancel(context.Background()) + defer runCancel() + run := &clientRun{ctx: runCtx, cancel: runCancel} + conn := &clientConn{ + connectionResult: make(chan error, 1), + serviceID: "42", + } + replacement := &clientConn{ + connectionResult: make(chan error, 1), + serviceID: "84", + } + c.run = run + run.conn = conn const goroutines = 8 const iterations = 200 - serviceIDs := []string{"1", "42", "1024", "65535"} var wg sync.WaitGroup // config writers @@ -122,24 +125,49 @@ func TestConfigureAndConnStateNoRace(t *testing.T) { }(w) } - // serviceID writers, mutating under the same lock connect() uses + // Active-run config writers are independent of which physical connection + // supplied a Pong frame. for w := 0; w < goroutines; w++ { wg.Add(1) go func(w int) { defer wg.Done() for i := 0; i < iterations; i++ { - c.setServiceIDLocked(serviceIDs[(w+i)%len(serviceIDs)]) + if !c.applyConfig(run, validConfigPayloads[(w+i)%len(validConfigPayloads)]) { + t.Errorf("active run rejected config update") + return + } } }(w) } - // conn/serviceID readers + // Replace the current connection while readers snapshot it. + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < iterations; i++ { + c.stateMu.Lock() + if run.conn == conn { + run.conn = replacement + } else { + run.conn = conn + } + c.stateMu.Unlock() + } + }() + + // Snapshot readers accept either fully published connection and also exercise + // the exact physical-connection check used by receive cleanup. for r := 0; r < goroutines; r++ { wg.Add(1) go func() { defer wg.Done() for i := 0; i < iterations; i++ { - _, _ = c.connState() + current, ok := c.currentConnection(run) + if !ok || (current != conn && current != replacement) { + t.Errorf("currentConnection returned (%p, %v)", current, ok) + return + } + c.isConnectionActive(run, current) } }() } diff --git a/ws/client_security_test.go b/ws/client_security_test.go new file mode 100644 index 00000000..26e9156d --- /dev/null +++ b/ws/client_security_test.go @@ -0,0 +1,234 @@ +package ws + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +type lifecycleRecordingLogger struct { + mu sync.Mutex + entries []string +} + +func (l *lifecycleRecordingLogger) Debug(_ context.Context, args ...interface{}) { + l.record(args...) +} + +func (l *lifecycleRecordingLogger) Info(_ context.Context, args ...interface{}) { + l.record(args...) +} + +func (l *lifecycleRecordingLogger) Warn(_ context.Context, args ...interface{}) { + l.record(args...) +} + +func (l *lifecycleRecordingLogger) Error(_ context.Context, args ...interface{}) { + l.record(args...) +} + +func (l *lifecycleRecordingLogger) record(args ...interface{}) { + l.mu.Lock() + l.entries = append(l.entries, fmt.Sprint(args...)) + l.mu.Unlock() +} + +func (l *lifecycleRecordingLogger) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return strings.Join(l.entries, "\n") +} + +func assertLifecycleTextDoesNotContain(t *testing.T, text string, markers ...string) { + t.Helper() + for _, marker := range markers { + if strings.Contains(text, marker) { + t.Errorf("lifecycle output contains sensitive marker %q: %s", marker, text) + } + } +} + +func TestConnectedEndpointKeepsHandshakeQueryButRedactsLifecycleOutput(t *testing.T) { + const ( + appSecretMarker = "app-secret-sensitive-marker" + pathMarker = "endpoint-path-sensitive-marker" + deviceIDMarker = "device-id-sensitive-marker" + serviceIDMarker = "424242" + ) + + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + parsedEndpoint, err := url.Parse(gateway.endpoint()) + if err != nil { + t.Fatalf("parse gateway endpoint: %v", err) + } + parsedEndpoint.Path = "/" + pathMarker + query := parsedEndpoint.Query() + query.Set(DeviceID, deviceIDMarker) + query.Set(ServiceID, serviceIDMarker) + parsedEndpoint.RawQuery = query.Encode() + endpoint := parsedEndpoint.String() + + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, endpoint, &bootstrapRequests) + defer cleanupBootstrap() + logger := &lifecycleRecordingLogger{} + ready := make(chan struct{}, 1) + client := NewClient("app-id", appSecretMarker, + WithDomain(domain), + WithAutoReconnect(false), + WithLogger(logger), + WithOnReady(func() { ready <- struct{}{} }), + ) + result := startLifecycleClient(client, context.Background()) + waitLifecycleSignal(t, ready, "Ready") + + var request lifecycleGatewayRequest + select { + case request = <-gateway.requests: + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for gateway handshake request") + } + if request.deviceID != deviceIDMarker { + t.Errorf("gateway received device_id %q, want %q", request.deviceID, deviceIDMarker) + } + if request.serviceID != serviceIDMarker { + t.Errorf("gateway received service_id %q, want %q", request.serviceID, serviceIDMarker) + } + if request.path != "/"+pathMarker { + t.Errorf("gateway received path %q, want %q", request.path, "/"+pathMarker) + } + + client.Close() + startErr, ok := waitLifecycleResult(result) + if !ok { + t.Error("Start did not return after Close") + } else if startErr != nil { + t.Errorf("Start returned %v after Close, want nil", startErr) + } + logs := logger.String() + if !strings.Contains(logs, "[conn_id="+deviceIDMarker+"]") { + t.Errorf("lifecycle output did not include conn_id marker: %s", logs) + } + assertLifecycleTextDoesNotContain(t, logs, + appSecretMarker, + pathMarker, + serviceIDMarker, + ) +} + +func TestHandshakeFailurePreservesPublicErrorAndRedactsLogs(t *testing.T) { + const ( + deviceIDMarker = "handshake-device-sensitive-marker" + serviceIDMarker = "515151" + serverMsgMarker = "handshake-server-sensitive-marker" + ) + + receivedDeviceID := make(chan string, 1) + gateway := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + receivedDeviceID <- r.URL.Query().Get(DeviceID) + w.Header().Set(HeaderHandshakeStatus, fmt.Sprint(Forbidden)) + w.Header().Set(HeaderHandshakeMsg, serverMsgMarker) + w.WriteHeader(http.StatusForbidden) + })) + defer gateway.Close() + endpoint := "ws" + strings.TrimPrefix(gateway.URL, "http") + "/handshake-sensitive-path?" + + DeviceID + "=" + url.QueryEscape(deviceIDMarker) + "&" + ServiceID + "=" + url.QueryEscape(serviceIDMarker) + + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, endpoint, &bootstrapRequests) + defer cleanupBootstrap() + logger := &lifecycleRecordingLogger{} + errorCallback := make(chan error, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithLogger(logger), + WithOnError(func(err error) { errorCallback <- err }), + ) + + startErr := client.Start(context.Background()) + if startErr == nil { + t.Fatal("handshake rejection returned nil") + } + var callbackErr error + select { + case callbackErr = <-errorCallback: + case <-time.After(lifecycleTestTimeout): + t.Fatal("handshake rejection did not invoke OnError") + } + var handshakeDeviceID string + select { + case handshakeDeviceID = <-receivedDeviceID: + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for rejected handshake request") + } + if handshakeDeviceID != deviceIDMarker { + t.Errorf("gateway received device_id %q, want %q", handshakeDeviceID, deviceIDMarker) + } + + clientErr, ok := startErr.(*ClientError) + if !ok { + t.Fatalf("handshake rejection returned %T, want *ClientError", startErr) + } + if clientErr.Msg != serverMsgMarker { + t.Errorf("Start ClientError.Msg = %q, want %q", clientErr.Msg, serverMsgMarker) + } + if _, ok := callbackErr.(*ClientError); !ok { + t.Errorf("OnError received %T, want *ClientError", callbackErr) + } + assertLifecycleTextDoesNotContain(t, logger.String(), deviceIDMarker, serviceIDMarker, serverMsgMarker) +} + +func TestMalformedEndpointPreservesParseErrorAndRedactsLogs(t *testing.T) { + const ( + usernameMarker = "endpoint-user-sensitive-marker" + passwordMarker = "endpoint-password-sensitive-marker" + deviceIDMarker = "parse-device-sensitive-marker" + fragmentMarker = "parse-fragment-sensitive-marker" + ) + rawEndpoint := "ws://" + usernameMarker + ":" + passwordMarker + "@%zz/private?" + + DeviceID + "=" + deviceIDMarker + "#" + fragmentMarker + + var bootstrapRequests int32 + domain, cleanupBootstrap := installLifecycleBootstrap(t, rawEndpoint, &bootstrapRequests) + defer cleanupBootstrap() + logger := &lifecycleRecordingLogger{} + errorCallback := make(chan error, 1) + client := NewClient("app-id", "app-secret", + WithDomain(domain), + WithAutoReconnect(false), + WithLogger(logger), + WithOnError(func(err error) { errorCallback <- err }), + ) + + startErr := client.Start(context.Background()) + if startErr == nil { + t.Fatal("malformed endpoint returned nil") + } + var callbackErr error + select { + case callbackErr = <-errorCallback: + case <-time.After(lifecycleTestTimeout): + t.Fatal("malformed endpoint did not invoke OnError") + } + if callbackErr != startErr { + t.Errorf("OnError received %v, want Start error %v", callbackErr, startErr) + } + assertLifecycleTextDoesNotContain(t, logger.String(), + usernameMarker, + passwordMarker, + deviceIDMarker, + fragmentMarker, + ) + if got := atomic.LoadInt32(&bootstrapRequests); got != 1 { + t.Errorf("malformed endpoint made %d bootstrap requests, want 1", got) + } +} diff --git a/ws/client_session.go b/ws/client_session.go new file mode 100644 index 00000000..8e44a12b --- /dev/null +++ b/ws/client_session.go @@ -0,0 +1,271 @@ +package ws + +import ( + "context" + "encoding/json" + "errors" + "strconv" + "sync" + "time" + + ws "github.com/gorilla/websocket" +) + +// clientConn represents one physical websocket connection within a clientRun. +// A reconnect replaces run.conn with a new clientConn instead of mutating this +// value in place. +type clientConn struct { + socket *ws.Conn + + connectionResult chan error + writeMu sync.Mutex + + connID string + serviceID string + safeEndpoint string +} + +const pongGracePeriod = 5 * time.Second + +func pongWait(pingInterval time.Duration) time.Duration { + return 2*pingInterval + pongGracePeriod +} + +func (c *Client) fmtConnLog(conn *clientConn, format string, args ...interface{}) []interface{} { + log := c.fmtLog(format, args...) + if conn != nil && conn.connID != "" { + log = append(log, "[conn_id="+conn.connID+"]") + } + return log +} + +// activateConnection atomically publishes a physical connection and admits +// its receive worker before a concurrent stop can win. Ping belongs to the +// run and starts only with the first published connection. +func (c *Client) activateConnection(run *clientRun, conn *clientConn, reconnected bool) (activated bool) { + c.stateMu.Lock() + if run.stopReason != runStopNone || run.ctx.Err() != nil { + c.stateMu.Unlock() + c.closeSocket(run.ctx, conn.socket, conn.safeEndpoint, "reject connection candidate") + return false + } + + firstConnection := !run.everConnected + run.conn = conn + run.everConnected = true + run.wg.Add(1) + if firstConnection { + run.wg.Add(1) + } + callback := c.onReady + if reconnected { + callback = c.onReconnected + } + go c.receiveMessageLoop(run, conn) + if firstConnection { + go c.pingLoop(run) + } + c.stateMu.Unlock() + + c.logger.Info(run.ctx, c.fmtConnLog(conn, "connected to %s", conn.safeEndpoint)...) + activated = true + if callback == nil || !c.isConnectionActive(run, conn) { + return activated + } + defer c.recoverCallback(run.ctx, "ready") + callback() + return activated +} + +// deactivateConnection removes and closes run's current physical connection. +// The run coordinator calls it before beginning a reconnect attempt. +func (c *Client) deactivateConnection(run *clientRun) { + c.stateMu.Lock() + conn := run.conn + run.conn = nil + callback := c.onDisconnected + c.stateMu.Unlock() + + c.closeSocket(run.ctx, conn.socket, conn.safeEndpoint, "close connection") + c.logger.Info(run.ctx, c.fmtConnLog(conn, "disconnected to %s", conn.safeEndpoint)...) + defer c.recoverCallback(run.ctx, "disconnected") + if callback != nil { + callback() + } +} + +func (c *Client) closeSocket(ctx context.Context, socket *ws.Conn, endpoint, operation string) { + if err := socket.Close(); err != nil { + c.logger.Warn(ctx, c.fmtLog("websocket %s failed at %s", operation, endpoint)...) + } +} + +// pingLoop sends an immediate Ping and then uses the latest server-provided +// interval. Each iteration resolves the run's current physical connection. +func (c *Client) pingLoop(run *clientRun) { + defer run.wg.Done() + + for { + c.sendPing(run) + + _, _, _, pingInterval := c.configSnapshot() + if !c.waitRunDelay(run, pingInterval) { + return + } + } +} + +func (c *Client) sendPing(run *clientRun) { + defer func() { + if recover() != nil { + c.logger.Warn(run.ctx, c.fmtLog("websocket ping failed")...) + } + }() + + conn, ok := c.currentConnection(run) + if !ok { + return + } + + var serviceID int64 + if conn.serviceID != "" { + parsedServiceID, err := strconv.ParseInt(conn.serviceID, 10, 32) + if err != nil { + c.logger.Warn(run.ctx, c.fmtConnLog(conn, "websocket ping failed")...) + return + } + serviceID = parsedServiceID + } + + frame := NewPingFrame(int32(serviceID)) + payload, err := frame.Marshal() + if err != nil { + c.logger.Warn(run.ctx, c.fmtConnLog(conn, "websocket ping failed")...) + return + } + if err := c.writeConnection(run, conn, ws.BinaryMessage, payload); err != nil { + c.logger.Warn(run.ctx, c.fmtConnLog(conn, "websocket ping failed")...) + return + } + c.logger.Debug(run.ctx, c.fmtConnLog(conn, "ping success")...) +} + +func (c *Client) receiveMessageLoop(run *clientRun, conn *clientConn) { + defer run.wg.Done() + defer func() { + if recover() != nil { + c.reportConnectionError(run, conn, errors.New("websocket receive loop panicked")) + } + }() + + for { + messageType, msg, err := conn.socket.ReadMessage() + if err != nil { + c.reportConnectionError(run, conn, err) + return + } + if err := c.setReadDeadline(conn); err != nil { + c.reportConnectionError(run, conn, err) + return + } + if messageType != ws.BinaryMessage { + c.logger.Warn(run.ctx, c.fmtConnLog(conn, "websocket received unsupported message type %d", messageType)...) + continue + } + c.startMessageTask(run, msg) + } +} + +func (c *Client) handleControlFrame(run *clientRun, frame Frame) { + hs := Headers(frame.Headers) + t := hs.GetString(HeaderType) + + switch MessageType(t) { + case MessageTypePong: + conn, _ := c.currentConnection(run) + c.logger.Debug(run.ctx, c.fmtConnLog(conn, "receive pong")...) + if len(frame.Payload) == 0 { + return + } + conf := &ClientConfig{} + if err := json.Unmarshal(frame.Payload, conf); err != nil { + c.logger.Warn(run.ctx, c.fmtConnLog(conn, "websocket client config decode failed")...) + return + } + c.applyConfig(run, conf) + default: + } +} + +// setReadDeadline bounds how long this physical connection may stay silent. +// +// A peer can disappear without a TCP FIN/RST, for example after device sleep, +// network changes, or NAT state loss. In that case ReadMessage may otherwise +// block forever, and a successful outbound Ping does not prove that the peer +// or the inbound path is still alive. The deadline is armed after dialing and +// renewed after every inbound frame; expiry makes ReadMessage return so the +// existing reconnect flow can recover the connection. +func (c *Client) setReadDeadline(conn *clientConn) error { + _, _, _, pingInterval := c.configSnapshot() + return conn.socket.SetReadDeadline(time.Now().Add(pongWait(pingInterval))) +} + +// reportConnectionError hands the first I/O failure of conn to the run +// coordinator. Read and write paths can fail concurrently, so later errors +// must not block after the first one has started connection teardown. +func (c *Client) reportConnectionError(run *clientRun, conn *clientConn, err error) { + if !c.isConnectionActive(run, conn) { + return + } + select { + case conn.connectionResult <- err: + default: + } +} + +func (c *Client) isConnectionActive(run *clientRun, conn *clientConn) bool { + if run.ctx.Err() != nil { + return false + } + c.stateMu.Lock() + defer c.stateMu.Unlock() + return run.stopReason == runStopNone && run.conn == conn +} + +func (c *Client) currentConnection(run *clientRun) (*clientConn, bool) { + if run.ctx.Err() != nil { + return nil, false + } + c.stateMu.Lock() + defer c.stateMu.Unlock() + if run.stopReason != runStopNone || run.conn == nil { + return nil, false + } + return run.conn, true +} + +func (c *Client) writeMessage(run *clientRun, messageType int, data []byte) error { + conn, ok := c.currentConnection(run) + if !ok { + return errConnectionClosed + } + return c.writeConnection(run, conn, messageType, data) +} + +func (c *Client) writeConnection(run *clientRun, conn *clientConn, messageType int, data []byte) error { + conn.writeMu.Lock() + defer conn.writeMu.Unlock() + + if !c.isConnectionActive(run, conn) { + return errConnectionClosed + } + if err := conn.socket.SetWriteDeadline(time.Now().Add(c.writeTimeout)); err != nil { + c.reportConnectionError(run, conn, err) + return err + } + if err := conn.socket.WriteMessage(messageType, data); err != nil { + c.reportConnectionError(run, conn, err) + return err + } + return nil +} diff --git a/ws/client_session_test.go b/ws/client_session_test.go new file mode 100644 index 00000000..8e93e15b --- /dev/null +++ b/ws/client_session_test.go @@ -0,0 +1,243 @@ +package ws + +import ( + "bufio" + "context" + "crypto/sha1" + "encoding/base64" + "errors" + "fmt" + "net" + "net/http" + "net/url" + "testing" + "time" + + websocket "github.com/gorilla/websocket" +) + +func newSocketClientConn(socket *websocket.Conn, endpoint string) *clientConn { + return &clientConn{ + socket: socket, + connectionResult: make(chan error, 1), + safeEndpoint: safeEndpoint(endpoint), + } +} + +// newWriteBlockingSocket completes a websocket handshake and then leaves the +// server side unread. net.Pipe has no write buffer, so client writes block +// until their deadline expires. +func newWriteBlockingSocket(t *testing.T) (*websocket.Conn, func()) { + t.Helper() + + clientNet, serverNet := net.Pipe() + releaseServer := make(chan struct{}) + serverErr := make(chan error, 1) + serverDone := make(chan struct{}) + go func() { + defer close(serverDone) + defer serverNet.Close() + + request, err := http.ReadRequest(bufio.NewReader(serverNet)) + if err != nil { + serverErr <- fmt.Errorf("read websocket handshake: %w", err) + return + } + key := request.Header.Get("Sec-WebSocket-Key") + if key == "" { + serverErr <- errors.New("websocket handshake key is missing") + return + } + + sum := sha1.Sum([]byte(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")) + accept := base64.StdEncoding.EncodeToString(sum[:]) + if _, err := fmt.Fprintf(serverNet, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n", accept); err != nil { + serverErr <- fmt.Errorf("write websocket handshake: %w", err) + return + } + + <-releaseServer + }() + + endpoint := &url.URL{Scheme: "ws", Host: "example.test", Path: "/callback"} + socket, _, err := websocket.NewClient(clientNet, endpoint, nil, 1024, 1024) + if err != nil { + _ = clientNet.Close() + close(releaseServer) + <-serverDone + select { + case serverErr := <-serverErr: + t.Fatalf("create websocket client: %v (server: %v)", err, serverErr) + default: + t.Fatalf("create websocket client: %v", err) + } + } + + cleanup := func() { + _ = socket.Close() + close(releaseServer) + <-serverDone + } + return socket, cleanup +} + +func activeRunAndSocket(socket *websocket.Conn, endpoint string) (*clientRun, *clientConn) { + runCtx, runCancel := context.WithCancel(context.Background()) + run := &clientRun{ctx: runCtx, cancel: runCancel, everConnected: true} + conn := newSocketClientConn(socket, endpoint) + run.conn = conn + return run, conn +} + +func waitAcceptedGatewayConnection(t *testing.T, gateway *lifecycleGateway) *websocket.Conn { + t.Helper() + select { + case conn := <-gateway.accepted: + return conn + case <-time.After(lifecycleTestTimeout): + t.Fatal("timed out waiting for accepted gateway connection") + return nil + } +} + +func waitGatewayFrame(t *testing.T, gateway *lifecycleGateway, name string) lifecycleGatewayFrame { + t.Helper() + select { + case frame := <-gateway.frames: + return frame + case <-time.After(lifecycleTestTimeout): + t.Fatalf("timed out waiting for %s", name) + return lifecycleGatewayFrame{} + } +} + +func assertNoGatewayFrame(t *testing.T, gateway *lifecycleGateway, target *websocket.Conn, timeout time.Duration) { + t.Helper() + select { + case frame := <-gateway.frames: + if frame.conn == target { + t.Fatalf("connection %p unexpectedly received payload %q", target, frame.payload) + } + t.Fatalf("unexpected payload %q on connection %p", frame.payload, frame.conn) + case <-time.After(timeout): + } +} + +func TestWriteConnectionRejectsReplacedSnapshot(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + firstSocket := dialLifecycleCandidate(t, gateway) + defer closeGatewayConn(t, firstSocket) + firstServerConn := waitAcceptedGatewayConnection(t, gateway) + secondSocket := dialLifecycleCandidate(t, gateway) + defer closeGatewayConn(t, secondSocket) + secondServerConn := waitAcceptedGatewayConnection(t, gateway) + + run, firstConn := activeRunAndSocket(firstSocket, gateway.endpoint()) + defer run.cancel() + secondConn := newSocketClientConn(secondSocket, gateway.endpoint()) + client := NewClient("app-id", "app-secret") + client.run = run + + snapshot, ok := client.currentConnection(run) + if !ok || snapshot != firstConn { + t.Fatalf("currentConnection = (%p, %v), want first connection", snapshot, ok) + } + client.stateMu.Lock() + run.conn = secondConn + client.stateMu.Unlock() + + if current, currentOK := client.currentConnection(run); !currentOK || current != secondConn { + t.Fatalf("currentConnection = (%p, %v), want replacement", current, currentOK) + } + if err := client.writeConnection(run, snapshot, websocket.BinaryMessage, []byte("stale payload")); !errors.Is(err, errConnectionClosed) { + t.Fatalf("writeConnection with replaced snapshot returned %v, want errConnectionClosed", err) + } + assertNoGatewayFrame(t, gateway, firstServerConn, 100*time.Millisecond) + assertNoGatewayFrame(t, gateway, secondServerConn, 100*time.Millisecond) +} + +func TestWriteConnectionTimeoutReportsConnectionError(t *testing.T) { + socket, cleanupSocket := newWriteBlockingSocket(t) + defer cleanupSocket() + + run, conn := activeRunAndSocket(socket, "ws://example.test/callback") + defer run.cancel() + client := NewClient("app-id", "app-secret", WithWriteTimeout(20*time.Millisecond)) + client.run = run + + err := client.writeConnection(run, conn, websocket.BinaryMessage, []byte("blocked payload")) + var timeoutErr net.Error + if !errors.As(err, &timeoutErr) || !timeoutErr.Timeout() { + t.Fatalf("writeConnection returned %v, want write timeout", err) + } + + select { + case reported := <-conn.connectionResult: + if reported != err { + t.Fatalf("connectionResult = %v, want write error %v", reported, err) + } + case <-time.After(lifecycleTestTimeout): + t.Fatal("write timeout was not reported to the connection coordinator") + } +} + +func TestStopAndDetachDoNotWaitForWriter(t *testing.T) { + gateway, cleanupGateway := newLifecycleGateway(t) + defer cleanupGateway() + + socket := dialLifecycleCandidate(t, gateway) + defer closeGatewayConn(t, socket) + waitAcceptedGatewayConnection(t, gateway) + run, conn := activeRunAndSocket(socket, gateway.endpoint()) + defer run.cancel() + client := NewClient("app-id", "app-secret") + client.run = run + + conn.writeMu.Lock() + writerEntered := make(chan struct{}) + writeResult := make(chan error, 1) + go func() { + close(writerEntered) + writeResult <- client.writeConnection(run, conn, websocket.BinaryMessage, []byte("blocked payload")) + }() + waitLifecycleSignal(t, writerEntered, "writer entry") + + stopResult := make(chan bool, 1) + go func() { + stopResult <- client.stopRun(run, runStopByClose, nil) + }() + select { + case accepted := <-stopResult: + if !accepted { + conn.writeMu.Unlock() + t.Fatal("stopRun rejected the active run") + } + case <-time.After(300 * time.Millisecond): + conn.writeMu.Unlock() + t.Fatal("stopRun waited for the connection writer") + } + + detachDone := make(chan struct{}) + go func() { + client.deactivateConnection(run) + close(detachDone) + }() + select { + case <-detachDone: + case <-time.After(300 * time.Millisecond): + conn.writeMu.Unlock() + t.Fatal("deactivateConnection waited for the connection writer") + } + + conn.writeMu.Unlock() + select { + case err := <-writeResult: + if !errors.Is(err, errConnectionClosed) { + t.Fatalf("old writer returned %v after detach, want errConnectionClosed", err) + } + case <-time.After(lifecycleTestTimeout): + t.Fatal("old writer remained blocked after releasing writeMu") + } +} diff --git a/ws/client_test.go b/ws/client_test.go index 29bb732d..4ec75712 100644 --- a/ws/client_test.go +++ b/ws/client_test.go @@ -3,6 +3,7 @@ package ws import ( "context" "encoding/json" + "io" "net/http" "net/http/httptest" "strings" @@ -32,10 +33,13 @@ func (p *wsMockClientAssertionProvider) RetrieveToken(ctx context.Context, aud s return token, nil } -func TestGetConnURLWithAppSecret(t *testing.T) { - originalClient := bootstrapHTTPClient - defer func() { bootstrapHTTPClient = originalClient }() +type wsRoundTripperFunc func(*http.Request) (*http.Response, error) +func (f wsRoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +func TestFetchEndpointWithAppSecret(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != GenEndpointUri { t.Fatalf("unexpected path: %s", r.URL.Path) @@ -51,9 +55,8 @@ func TestGetConnURLWithAppSecret(t *testing.T) { })) defer server.Close() - bootstrapHTTPClient = server.Client() - client := NewClient("app-id", "app-secret", WithDomain(server.URL)) - connURL, err := client.getConnURL(context.Background()) + client := NewClient("app-id", "app-secret", WithDomain(server.URL), WithHttpClient(server.Client())) + connURL, _, err := client.fetchEndpoint(context.Background()) if err != nil { t.Fatalf("get conn url failed: %v", err) } @@ -62,10 +65,7 @@ func TestGetConnURLWithAppSecret(t *testing.T) { } } -func TestGetConnURLWithCustomHeadersAndUserAgent(t *testing.T) { - originalClient := bootstrapHTTPClient - defer func() { bootstrapHTTPClient = originalClient }() - +func TestFetchEndpointWithCustomHeadersAndUserAgent(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("X-Tt-Env") != "ppe_test" { t.Fatalf("missing X-Tt-Env header: %s", r.Header.Get("X-Tt-Env")) @@ -88,21 +88,18 @@ func TestGetConnURLWithCustomHeadersAndUserAgent(t *testing.T) { headers.Set("X-Tt-Env", "ppe_test") headers.Set("X-Use-Ppe", "1") - bootstrapHTTPClient = server.Client() client := NewClient("app-id", "app-secret", WithDomain(server.URL), + WithHttpClient(server.Client()), WithHeaders(headers), WithSource("ws-test"), ) - if _, err := client.getConnURL(context.Background()); err != nil { + if _, _, err := client.fetchEndpoint(context.Background()); err != nil { t.Fatalf("get conn url failed: %v", err) } } -func TestGetConnURLWithClientAssertionProxy(t *testing.T) { - originalClient := bootstrapHTTPClient - defer func() { bootstrapHTTPClient = originalClient }() - +func TestFetchEndpointWithClientAssertionProxy(t *testing.T) { proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/proxy"+GenEndpointUri { t.Fatalf("unexpected path: %s", r.URL.Path) @@ -121,18 +118,14 @@ func TestGetConnURLWithClientAssertionProxy(t *testing.T) { })) defer proxyServer.Close() - bootstrapHTTPClient = proxyServer.Client() provider := &wsMockClientAssertionProvider{tokens: []*larkcore.Token{{Value: "assertion", TargetInfo: &larkcore.TargetInfo{TargetService: proxyServer.URL, TargetPrefix: "/proxy"}}}} - client := NewClient("app-id", "", WithDomain("https://open.feishu.cn"), WithClientAssertionProvider(provider)) - if _, err := client.getConnURL(context.Background()); err != nil { + client := NewClient("app-id", "", WithDomain("https://open.feishu.cn"), WithHttpClient(proxyServer.Client()), WithClientAssertionProvider(provider)) + if _, _, err := client.fetchEndpoint(context.Background()); err != nil { t.Fatalf("get conn url failed: %v", err) } } -func TestGetConnURLWithClientAssertionProxyHTTPErrorMsg(t *testing.T) { - originalClient := bootstrapHTTPClient - defer func() { bootstrapHTTPClient = originalClient }() - +func TestFetchEndpointWithClientAssertionProxyHTTPErrorMsg(t *testing.T) { proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) _ = json.NewEncoder(w).Encode(struct { @@ -145,10 +138,9 @@ func TestGetConnURLWithClientAssertionProxyHTTPErrorMsg(t *testing.T) { })) defer proxyServer.Close() - bootstrapHTTPClient = proxyServer.Client() provider := &wsMockClientAssertionProvider{tokens: []*larkcore.Token{{Value: "assertion", TargetInfo: &larkcore.TargetInfo{TargetService: proxyServer.URL, TargetPrefix: "/proxy"}}}} - client := NewClient("app-id", "", WithDomain("https://open.feishu.cn"), WithClientAssertionProvider(provider)) - _, err := client.getConnURL(context.Background()) + client := NewClient("app-id", "", WithDomain("https://open.feishu.cn"), WithHttpClient(proxyServer.Client()), WithClientAssertionProvider(provider)) + _, _, err := client.fetchEndpoint(context.Background()) if err == nil { t.Fatal("expected error, got nil") } @@ -158,17 +150,14 @@ func TestGetConnURLWithClientAssertionProxyHTTPErrorMsg(t *testing.T) { t.Fatalf("unexpected error type: %#v", err) } if serverErr.Code != http.StatusInternalServerError { - t.Fatalf("unexpected server error code: %d", serverErr.Code) + t.Fatalf("unexpected status code: %d", serverErr.Code) } if serverErr.Msg != "target service unavailable" { - t.Fatalf("unexpected server error msg: %s", serverErr.Msg) + t.Fatalf("unexpected server error message: %q", serverErr.Msg) } } -func TestGetConnURLRetrieveTokenEachTime(t *testing.T) { - originalClient := bootstrapHTTPClient - defer func() { bootstrapHTTPClient = originalClient }() - +func TestFetchEndpointRetrieveTokenEachTime(t *testing.T) { bodyAssertions := make([]string, 0, 2) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req BootstrapRequest @@ -180,13 +169,12 @@ func TestGetConnURLRetrieveTokenEachTime(t *testing.T) { })) defer server.Close() - bootstrapHTTPClient = server.Client() provider := &wsMockClientAssertionProvider{tokens: []*larkcore.Token{{Value: "assertion-1"}, {Value: "assertion-2"}}} - client := NewClient("app-id", "", WithDomain(server.URL), WithClientAssertionProvider(provider)) - if _, err := client.getConnURL(context.Background()); err != nil { + client := NewClient("app-id", "", WithDomain(server.URL), WithHttpClient(server.Client()), WithClientAssertionProvider(provider)) + if _, _, err := client.fetchEndpoint(context.Background()); err != nil { t.Fatalf("first get conn url failed: %v", err) } - if _, err := client.getConnURL(context.Background()); err != nil { + if _, _, err := client.fetchEndpoint(context.Background()); err != nil { t.Fatalf("second get conn url failed: %v", err) } if provider.calls != 2 { @@ -197,6 +185,35 @@ func TestGetConnURLRetrieveTokenEachTime(t *testing.T) { } } +func TestWithHttpClientFetchesEndpoint(t *testing.T) { + var requests int + client := NewClient("app-id", "app-secret", + WithDomain("https://bootstrap.example"), + WithHttpClient(&http.Client{Transport: wsRoundTripperFunc(func(req *http.Request) (*http.Response, error) { + requests++ + if req.URL.String() != "https://bootstrap.example"+GenEndpointUri { + t.Fatalf("unexpected request URL: %s", req.URL) + } + return &http.Response{ + StatusCode: http.StatusOK, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(`{"code":0,"data":{"url":"wss://example.com/ws"}}`)), + }, nil + })}), + ) + + endpoint, _, err := client.fetchEndpoint(context.Background()) + if err != nil { + t.Fatalf("fetch endpoint: %v", err) + } + if endpoint != "wss://example.com/ws" { + t.Fatalf("unexpected endpoint: %s", endpoint) + } + if requests != 1 { + t.Fatalf("expected one injected HTTP request, got %d", requests) + } +} + func TestBuildWSProxyURL(t *testing.T) { testCases := map[string]string{ "proxy.example.com": "https://proxy.example.com/v1" + GenEndpointUri, diff --git a/ws/client_transport.go b/ws/client_transport.go new file mode 100644 index 00000000..1e476f26 --- /dev/null +++ b/ws/client_transport.go @@ -0,0 +1,223 @@ +package ws + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "strconv" + "strings" + + larkcore "github.com/larksuite/oapi-sdk-go/v3/core" +) + +// establishConnectionOnce performs exactly one bootstrap and websocket dial. +// Retry policy belongs to the lifecycle coordinator, not the transport layer. +func (c *Client) establishConnectionOnce(run *clientRun) (*clientConn, error) { + rawEndpoint, conf, err := c.fetchEndpoint(run.ctx) + if err != nil { + return nil, err + } + if !c.applyConfig(run, conf) { + return nil, errConnectionClosed + } + + u, err := url.Parse(rawEndpoint) + if err != nil { + return nil, err + } + if u.Scheme == "" || u.Host == "" { + return nil, errors.New("websocket endpoint is invalid") + } + + socket, resp, dialErr := c.websocketDialer.DialContext(run.ctx, rawEndpoint, nil) + if resp != nil && resp.Body != nil { + defer func() { + if closeErr := resp.Body.Close(); closeErr != nil { + c.logger.Warn(run.ctx, "websocket handshake response close failed") + } + }() + } + if dialErr != nil { + if socket != nil { + c.closeSocket(run.ctx, socket, safeEndpoint(rawEndpoint), "discard dial candidate") + } + if resp != nil && resp.StatusCode != http.StatusSwitchingProtocols { + return nil, parseHandshakeError(resp) + } + return nil, dialErr + } + if socket == nil || resp == nil || resp.StatusCode != http.StatusSwitchingProtocols { + if socket != nil { + c.closeSocket(run.ctx, socket, safeEndpoint(rawEndpoint), "discard handshake candidate") + } + if resp != nil { + return nil, parseHandshakeError(resp) + } + return nil, errors.New("websocket handshake response is invalid") + } + + conn := &clientConn{ + socket: socket, + connectionResult: make(chan error, 1), + connID: u.Query().Get(DeviceID), + serviceID: u.Query().Get(ServiceID), + safeEndpoint: safeEndpoint(rawEndpoint), + } + if err := c.setReadDeadline(conn); err != nil { + c.closeSocket(run.ctx, socket, conn.safeEndpoint, "initialize read deadline") + return nil, err + } + return conn, nil +} + +func (c *Client) fetchEndpoint(ctx context.Context) (endpointURL string, conf *ClientConfig, err error) { + requestURL := strings.TrimRight(c.domain, "/") + GenEndpointUri + body := &BootstrapRequest{AppID: c.appID} + headers := make(http.Header) + + if c.clientAssertionProvider == nil && c.appSecret == "" { + return "", nil, NewClientError(larkcore.ErrCodeAppSecretAndClientAssertionEmpty, "appSecret and clientAssertionProvider cannot be nil") + } + + if c.clientAssertionProvider != nil { + aud, extractErr := extractAudFromWSURL(c.domain) + if extractErr != nil { + return "", nil, extractErr + } + clientAssertionToken, retrieveErr := c.clientAssertionProvider.RetrieveToken(ctx, aud) + if retrieveErr != nil { + return "", nil, retrieveErr + } + if clientAssertionToken == nil || clientAssertionToken.Value == "" { + return "", nil, NewClientError(larkcore.ErrCodeClientAssertionTokenEmpty, "client assertion token is empty") + } + body.ClientAssertion = clientAssertionToken.Value + body.AppSecret = "" + if clientAssertionToken.TargetInfo != nil { + requestURL = buildWSProxyURL(clientAssertionToken.TargetInfo.TargetService, clientAssertionToken.TargetInfo.TargetPrefix, GenEndpointUri) + headers.Set(larkcore.HeaderXTargetService, aud) + } + } else { + body.AppSecret = c.appSecret + } + + bs, marshalErr := json.Marshal(body) + if marshalErr != nil { + return "", nil, marshalErr + } + + req, requestErr := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, bytes.NewBuffer(bs)) + if requestErr != nil { + return "", nil, requestErr + } + + req.Header.Add("locale", "zh") + req.Header.Add("Content-Type", "application/json") + for k, values := range c.headers { + for _, value := range values { + req.Header.Add(k, value) + } + } + for k, values := range headers { + req.Header.Del(k) + for _, value := range values { + req.Header.Add(k, value) + } + } + req.Header.Set("User-Agent", larkcore.UserAgent(c.source)) + resp, requestErr := c.httpClient.Do(req) + if requestErr != nil { + return "", nil, requestErr + } + defer func() { + if closeErr := resp.Body.Close(); closeErr != nil { + c.logger.Warn(ctx, "websocket bootstrap response close failed") + } + }() + respBody, readErr := ioutil.ReadAll(resp.Body) + if readErr != nil { + return "", nil, readErr + } + if resp.StatusCode != http.StatusOK { + message := "system busy" + bootstrapResponse := &EndpointResp{} + if err := json.Unmarshal(respBody, bootstrapResponse); err == nil && bootstrapResponse.Msg != "" { + message = bootstrapResponse.Msg + } + return "", nil, NewServerError(resp.StatusCode, message) + } + + endpointResp := &EndpointResp{} + if unmarshalErr := json.Unmarshal(respBody, endpointResp); unmarshalErr != nil { + return "", nil, unmarshalErr + } + + switch endpointResp.Code { + case OK: + case SystemBusy: + return "", nil, NewServerError(endpointResp.Code, "system busy") + case InternalError: + return "", nil, NewServerError(endpointResp.Code, endpointResp.Msg) + default: + return "", nil, NewClientError(endpointResp.Code, endpointResp.Msg) + } + + endpoint := endpointResp.Data + if endpoint == nil || endpoint.Url == "" { + return "", nil, NewServerError(http.StatusInternalServerError, "endpoint is null") + } + + return endpoint.Url, endpoint.ClientConfig, nil +} + +func extractAudFromWSURL(rawURL string) (string, error) { + if !strings.Contains(rawURL, "://") { + rawURL = "https://" + rawURL + } + parsedURL, err := url.Parse(rawURL) + if err != nil { + return "", err + } + if parsedURL.Host != "" { + return parsedURL.Host, nil + } + return "", fmt.Errorf("invalid url: %s", rawURL) +} + +func buildWSProxyURL(targetService, targetPrefix, apiPath string) string { + if !strings.Contains(targetService, "://") { + targetService = "https://" + targetService + } + return targetService + targetPrefix + apiPath +} + +func parseHandshakeError(resp *http.Response) error { + if resp == nil { + return errors.New("websocket handshake response is invalid") + } + code, parseErr := strconv.Atoi(resp.Header.Get(HeaderHandshakeStatus)) + if parseErr != nil || code == 0 { + code = resp.StatusCode + } + message := resp.Header.Get(HeaderHandshakeMsg) + switch code { + case AuthFailed: + authCode, authErr := strconv.Atoi(resp.Header.Get(HeaderHandshakeAuthErrCode)) + if authErr != nil { + authCode = 0 + } + if authCode == ExceedConnLimit { + return NewClientError(code, message) + } + return NewServerError(code, message) + case Forbidden: + return NewClientError(code, message) + default: + return NewServerError(code, message) + } +} diff --git a/ws/error.go b/ws/error.go index 65d0331d..952fc74d 100644 --- a/ws/error.go +++ b/ws/error.go @@ -1,6 +1,17 @@ package ws -import "fmt" +import ( + "errors" + "fmt" + "net/url" +) + +var ( + errNilContext = errors.New("websocket start context is nil") + errClientRunning = errors.New("websocket client is already running") + errClientTerminal = errors.New("websocket client cannot be restarted") + errConnectionClosed = errors.New("websocket connection is closed") +) type ClientError struct { Code int @@ -33,3 +44,11 @@ func NewServerError(code int, msg string) *ServerError { msg, } } + +func safeEndpoint(rawURL string) string { + u, err := url.Parse(rawURL) + if err != nil || u.Scheme == "" || u.Host == "" { + return "websocket endpoint" + } + return (&url.URL{Scheme: u.Scheme, Host: u.Host}).String() +}