Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(lark): apply pong heartbeat updates and close failed sessions (MUL-8394) (#9708)
Jiahao799f5614a7ed
diff --git a/server/internal/integrations/lark/ws_connector.go b/server/internal/integrations/lark/ws_connector.goindex 0eb8e6ba69..9590d37a15 100644--- a/server/internal/integrations/lark/ws_connector.go+++ b/server/internal/integrations/lark/ws_connector.go@@ -2,6 +2,7 @@ package larkimport ("context"+ "encoding/json""errors""fmt""log/slog"@@ -74,7 +75,7 @@ type WSConnectorConfig struct {// PingInterval is the fallback cadence for the app-layer ping.// In production it is overridden per-installation by the- // PingInterval Lark returns in the bootstrap ClientConfig.+ // PingInterval Lark returns in the bootstrap ClientConfig or a pong.// Zero defaults to 2 minutes (matches the SDK default in// `larksuite/oapi-sdk-go/v3/ws/client.go`).PingInterval time.Duration@@ -83,7 +84,9 @@ type WSConnectorConfig struct {// each read; expiry yields a transient read error which the// connector logs and uses to exit, deferring to the Hub's// reconnect backoff. Zero defaults to 6 minutes so a healthy- // connection with the 2-minute default ping never trips it.+ // connection with the 2-minute default ping never trips it. The+ // effective deadline is raised to 3x the active ping interval when+ // Lark asks for a longer cadence.ReadDeadline time.Duration// WriteTimeout bounds a single WriteMessage. Zero defaults to 10s.@@ -226,7 +229,8 @@ func (c *WSLongConnConnector) Run(ctx context.Context, inst Installation, emit E// Ping loop: app-layer binary ping frames at the server's PingInterval.pingDone := make(chan struct{})- go c.pingLoop(runCtx, conn, &writeMu, endpoint.ServiceID, pingInterval, log, pingDone)+ pingUpdates := make(chan time.Duration)+ go c.pingLoop(runCtx, conn, &writeMu, endpoint.ServiceID, pingInterval, pingUpdates, closeConn, log, pingDone)defer func() {runCancel()@@ -243,7 +247,7 @@ func (c *WSLongConnConnector) Run(ctx context.Context, inst Installation, emit Efor {// Re-arm the read deadline before every Read so a stalled// connection eventually unblocks the syscall.- if err := conn.SetReadDeadline(c.cfg.Now().Add(c.cfg.ReadDeadline)); err != nil {+ if err := conn.SetReadDeadline(c.cfg.Now().Add(readDeadlineFor(c.cfg.ReadDeadline, pingInterval))); err != nil {if ctx.Err() != nil {return nil}@@ -283,14 +287,42 @@ func (c *WSLongConnConnector) Run(ctx context.Context, inst Installation, emit Econtinue}- // Control frames carry ping / pong / config updates. We- // only have to act on pings (reply with a pong); pongs and- // config payloads are accepted silently.+ // Lark sends updated ClientConfig JSON in application-level pongs.if frame.Method == FrameMethodControl {- if frame.HeaderValue(FrameHeaderTypeKey) == FrameHeaderTypePing {+ switch frame.HeaderValue(FrameHeaderTypeKey) {+ case FrameHeaderTypePing:if werr := c.writeFrame(&writeMu, conn, NewPongFrame(endpoint.ServiceID)); werr != nil {log.Warn("lark ws connector: pong write failed", "err", werr.Error())}+ case FrameHeaderTypePong:+ if len(frame.Payload) == 0 {+ break+ }+ var config struct {+ PingInterval int64 `json:"PingInterval"`+ }+ if err := json.Unmarshal(frame.Payload, &config); err != nil {+ log.Warn("lark ws connector: pong config decode failed", "err", err.Error())+ break+ }+ // Seconds must fit in a positive time.Duration before conversion.+ if config.PingInterval <= 0 || config.PingInterval > int64((1<<63-1)/time.Second) {+ break+ }+ updated := time.Duration(config.PingInterval) * time.Second+ if updated != pingInterval {+ select {+ case pingUpdates <- updated:+ pingInterval = updated+ case <-pingDone:+ if ctx.Err() != nil {+ return nil+ }+ return errors.New("ping loop stopped during config update")+ case <-runCtx.Done():+ return nil+ }+ }}continue}@@ -413,29 +445,60 @@ func (c *WSLongConnConnector) writeFrame(mu *sync.Mutex, conn WSConn, f *Frame)return conn.WriteMessage(websocket.BinaryMessage, payload)}+// readDeadlineFor keeps the read deadline above the ping cadence.+// Pongs are the only guaranteed inbound traffic on an idle session, so+// a deadline shorter than two ping intervals would drop healthy+// connections whenever Lark asks for a long cadence.+func readDeadlineFor(base, pingInterval time.Duration) time.Duration {+ const maxDuration = time.Duration(1<<63 - 1)+ if pingInterval <= 0 {+ return base+ }+ if pingInterval > maxDuration/3 {+ return maxDuration+ }+ if min := 3 * pingInterval; min > base {+ return min+ }+ return base+}+// pingLoop sends a periodic app-layer ping frame on the cadence Lark// asked for. The previous implementation used WebSocket protocol PING// (WriteControl), which the SDK source confirms Lark ignores.-func (c *WSLongConnConnector) pingLoop(ctx context.Context, conn WSConn, writeMu *sync.Mutex, serviceID int32, interval time.Duration, log *slog.Logger, done chan<- struct{}) {+func (c *WSLongConnConnector) pingLoop(ctx context.Context, conn WSConn, writeMu *sync.Mutex, serviceID int32, interval time.Duration, updates <-chan time.Duration, closeConn func(), log *slog.Logger, done chan<- struct{}) {defer close(done)- if interval <= 0 {- // A zero / negative interval would tick infinitely; bail out- // quietly. We logged the chosen interval at connect time.- <-ctx.Done()- return+ // A zero / negative interval would tick infinitely, so the ticker+ // stays unarmed until a positive update arrives. Updates are still+ // received in that state so Run never blocks delivering one.+ var t *time.Ticker+ var tick <-chan time.Time+ if interval > 0 {+ t = time.NewTicker(interval)+ tick = t.C}- t := time.NewTicker(interval)- defer t.Stop()+ defer func() {+ if t != nil {+ t.Stop()+ }+ }()for {select {case <-ctx.Done():return- case <-t.C:+ case interval = <-updates:+ if t == nil {+ t = time.NewTicker(interval)+ tick = t.C+ } else {+ t.Reset(interval)+ }+ case <-tick:if err := c.writeFrame(writeMu, conn, NewPingFrame(serviceID)); err != nil {log.Warn("lark ws connector: ping write failed", "err", err.Error())- // Don't tear down here — the read loop will exit on- // its own when the conn dies. Closing here would race- // with the read loop's own cleanup.+ // Closing unblocks ReadMessage so Run returns to Hub backoff.+ // closeConn is shared with cleanup and guarded by sync.Once.+ closeConn()return}}diff --git a/server/internal/integrations/lark/ws_connector_test.go b/server/internal/integrations/lark/ws_connector_test.goindex 44637a9f45..6d59aa6ed3 100644--- a/server/internal/integrations/lark/ws_connector_test.go+++ b/server/internal/integrations/lark/ws_connector_test.go@@ -14,6 +14,7 @@ import ("sync""sync/atomic""testing"+ "testing/synctest""time""github.com/gorilla/websocket"@@ -879,3 +880,147 @@ func TestGorillaDialerProxyURLApplied(t *testing.T) {// The error should be about the proxy connection (refused / timeout),// not about the URL parsing.}++func TestWSConnectorPongUpdatesPingInterval(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ conn := newFakeWSConn()+ c := quietConnector(t, conn, FrameDecoderFunc(func([]byte, Installation) (InboundMessage, bool, error) { return InboundMessage{}, false, nil }), 10*time.Second)+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() { done <- c.Run(ctx, Installation{}, nil) }()+ synctest.Wait()+ pushPong := func(payload string) {+ f := NewPongFrame(7)+ f.Payload = []byte(payload)+ conn.Push(f.Marshal())+ synctest.Wait()+ }+ checkPings := func(wait time.Duration, want int) {+ time.Sleep(wait)+ synctest.Wait()+ if got := len(conn.snapshot()); got != want {+ t.Errorf("pings after %s = %d, want %d", wait, got, want)+ }+ }+ pushPong(`{"PingInterval":2}`)+ checkPings(2*time.Second, 1)+ for _, payload := range []string{"", `{`, `{}`, `null`, `{"PingInterval":0}`, `{"PingInterval":-1}`, `{"PingInterval":"2"}`, `{"PingInterval":9223372036854775807}`} {+ pushPong(payload)+ }+ checkPings(time.Second, 1)+ // Unchanged configuration must not postpone the next heartbeat.+ pushPong(`{"PingInterval":2}`)+ checkPings(time.Second, 2)+ pushPong(`{"PingInterval":5}`)+ checkPings(4*time.Second, 2)+ checkPings(time.Second, 3)+ for _, raw := range conn.snapshot() {+ f, err := UnmarshalFrame(raw)+ if err != nil || f.Method != FrameMethodControl || f.HeaderValue(FrameHeaderTypeKey) != FrameHeaderTypePing || f.Service != 7 {+ t.Errorf("unexpected heartbeat: frame=%+v err=%v", f, err)+ }+ }+ cancel()+ if err := <-done; err != nil {+ t.Errorf("Run on cancel: %v", err)+ }+ checkPings(time.Minute, 3)+ })+}++func TestWSConnectorPingFailureUnblocksRead(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ conn := newFakeWSConn()+ conn.writeErr = errors.New("injected ping failure")+ c := quietConnector(t, conn, FrameDecoderFunc(func([]byte, Installation) (InboundMessage, bool, error) { return InboundMessage{}, false, nil }), time.Second)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ done := make(chan error, 1)+ go func() { done <- c.Run(ctx, Installation{}, nil) }()+ synctest.Wait()+ time.Sleep(time.Second)+ synctest.Wait()+ select {+ case err := <-done:+ if err == nil {+ t.Error("ping failure must return an error to Hub backoff")+ }+ default:+ t.Error("Run stayed blocked after ping failure")+ cancel()+ <-done+ }+ select {+ case <-conn.closed:+ default:+ t.Error("failed socket was not closed")+ }+ // The supervisor retries Connect after backoff; the same connector+ // must start a fresh session without a surviving failed ping loop.+ replacement := newFakeWSConn()+ c.cfg.Dialer = &fakeWSDialer{conn: replacement}+ go func() { done <- c.Run(ctx, Installation{}, nil) }()+ synctest.Wait()+ time.Sleep(time.Second)+ synctest.Wait()+ if got := len(replacement.snapshot()); got != 1 {+ t.Errorf("replacement session pings = %d, want 1", got)+ }+ cancel()+ if err := <-done; err != nil {+ t.Errorf("replacement Run on cancel: %v", err)+ }+ })+}++func TestWSConnectorPongArmsUnarmedPingLoop(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ conn := newFakeWSConn()+ // A non-positive fallback leaves the ticker unarmed; a later pong+ // must still be accepted and start heartbeats.+ c := quietConnector(t, conn, FrameDecoderFunc(func([]byte, Installation) (InboundMessage, bool, error) { return InboundMessage{}, false, nil }), -time.Second)+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() { done <- c.Run(ctx, Installation{}, nil) }()+ synctest.Wait()+ time.Sleep(time.Minute)+ synctest.Wait()+ if got := len(conn.snapshot()); got != 0 {+ t.Fatalf("pings before update = %d, want 0", got)+ }+ f := NewPongFrame(7)+ f.Payload = []byte(`{"PingInterval":2}`)+ conn.Push(f.Marshal())+ synctest.Wait()+ time.Sleep(2 * time.Second)+ synctest.Wait()+ if got := len(conn.snapshot()); got != 1 {+ t.Errorf("pings after update = %d, want 1", got)+ }+ cancel()+ if err := <-done; err != nil {+ t.Errorf("Run on cancel: %v", err)+ }+ })+}++func TestReadDeadlineForPingInterval(t *testing.T) {+ t.Parallel()+ const maxDuration = time.Duration(1<<63 - 1)+ cases := []struct {+ name string+ base, ping time.Duration+ want time.Duration+ }{+ {"default cadence keeps base", 6 * time.Minute, 2 * time.Minute, 6 * time.Minute},+ {"short cadence keeps base", 6 * time.Minute, 2 * time.Second, 6 * time.Minute},+ {"long cadence raises deadline", 6 * time.Minute, 5 * time.Minute, 15 * time.Minute},+ {"non-positive cadence keeps base", 6 * time.Minute, -time.Second, 6 * time.Minute},+ {"overflow saturates", 6 * time.Minute, maxDuration / 2, maxDuration},+ }+ for _, tc := range cases {+ if got := readDeadlineFor(tc.base, tc.ping); got != tc.want {+ t.Errorf("%s: readDeadlineFor(%s, %s) = %s, want %s", tc.name, tc.base, tc.ping, got, tc.want)+ }+ }+}