fix(im): prevent DingTalk stream connection from going stale

DingTalk websocket (Stream) channels stopped delivering @-mentions after
a day or two and only recovered when the IM channel was toggled off/on.
The factory fired the SDK's Start once and relied entirely on the SDK's
internal auto-reconnect, with no liveness supervision on WeKnora's side.
On long-running connections the SDK can enter a zombie state where the
connection object stays alive but no longer receives messages, leaving no
way to recover automatically. The cancel func was also ineffective because
the SDK ignores the context after the initial dial, so stopping a channel
leaked the old connection.

Add a reusable RunSupervised helper that keeps a long connection alive and
proactively recycles it every 6h on top of the SDK's own reconnect, which
bounds the worst-case outage and clears stuck connections. Wire DingTalk to
it, add LongConnClient.Close (disables AutoReconnect before closing so the
SDK does not resurrect the connection), and make the cancel func actually
tear the connection down. Drop the now-unused stream client reference from
the adapter, which only sends replies via sessionWebhook or OpenAPI.
This commit is contained in:
wizardchen
2026-06-22 15:00:16 +08:00
committed by lyingbug
parent 10e63b2227
commit 01819b5bc2
4 changed files with 126 additions and 28 deletions
+6 -6
View File
@@ -41,8 +41,7 @@ var (
type Adapter struct {
clientID string
clientSecret string
cardTemplateID string // optional: enables AI card streaming when set
client *LongConnClient // nil for webhook mode
cardTemplateID string // optional: enables AI card streaming when set
// accessToken cache
tokenMu sync.RWMutex
@@ -60,14 +59,15 @@ func NewWebhookAdapter(clientID, clientSecret, cardTemplateID string) *Adapter {
}
}
// NewAdapter creates a DingTalk adapter backed by a stream client.
func NewAdapter(client *LongConnClient, clientID, clientSecret, cardTemplateID string) *Adapter {
// NewAdapter creates a DingTalk adapter for stream (websocket) mode.
// The stream connection itself is managed separately by the supervisor; the
// adapter only sends replies (via sessionWebhook or OpenAPI).
func NewAdapter(clientID, clientSecret, cardTemplateID string) *Adapter {
startStreamReaper()
return &Adapter{
clientID: clientID,
clientSecret: clientSecret,
cardTemplateID: cardTemplateID,
client: client,
}
}
@@ -457,7 +457,7 @@ const (
var (
streamsMu sync.Mutex
dStreams = map[string]*streamState{}
dStreams = map[string]*streamState{}
startReaperOnce sync.Once
reaperStopCh = make(chan struct{})
)
+12 -9
View File
@@ -5,7 +5,6 @@ import (
"fmt"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
)
// NewFactory returns an im.AdapterFactory for DingTalk channels.
@@ -29,16 +28,20 @@ func NewFactory() im.AdapterFactory {
return adapter, nil, nil
case "websocket":
client := NewLongConnClient(clientID, clientSecret, msgHandler)
wsCtx, wsCancel := context.WithCancel(context.Background())
go func() {
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
logger.Errorf(context.Background(), "[IM] DingTalk stream stopped for channel %s: %v", channel.ID, err)
}
}()
go im.RunSupervised(wsCtx, im.SupervisorConfig{
Name: fmt.Sprintf("DingTalk channel %s", channel.ID),
Connect: func(ctx context.Context) (func(), error) {
client := NewLongConnClient(clientID, clientSecret, msgHandler)
if err := client.Start(ctx); err != nil {
client.Close()
return nil, err
}
return client.Close, nil
},
})
adapter := NewAdapter(client, clientID, clientSecret, cardTemplateID)
adapter := NewAdapter(clientID, clientSecret, cardTemplateID)
return adapter, wsCancel, nil
default:
+11 -13
View File
@@ -4,8 +4,8 @@ import (
"context"
"strings"
dtsdk "github.com/open-dingtalk/dingtalk-stream-sdk-go/client"
"github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot"
dtsdk "github.com/open-dingtalk/dingtalk-stream-sdk-go/client"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
@@ -43,21 +43,19 @@ func NewLongConnClient(clientID, clientSecret string, handler MessageHandler) *L
return c
}
// Start begins the stream connection. It blocks until ctx is cancelled.
// Start establishes the stream connection. The underlying SDK's Start is
// non-blocking: it dials the websocket, spawns its internal read/reconnect
// loops, and returns once the connection is established (or the attempt fails).
func (c *LongConnClient) Start(ctx context.Context) error {
logger.Infof(ctx, "[IM] DingTalk Stream connecting...")
return c.streamClient.Start(ctx)
}
errCh := make(chan error, 1)
go func() {
errCh <- c.streamClient.Start(ctx)
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errCh:
return err
}
// Close tears down the stream connection. AutoReconnect is disabled first so
// that closing the connection does not trigger the SDK's internal reconnect.
func (c *LongConnClient) Close() {
c.streamClient.AutoReconnect = false
c.streamClient.Close()
}
func (c *LongConnClient) onChatBotMessage(ctx context.Context, data *chatbot.BotCallbackDataModel) ([]byte, error) {