baada32cb6
Deleting or disabling a Feishu channel left its WebSocket long connection
alive: the Lark SDK's Start blocks on a bare select{} and never observes
ctx, and v3.6.1 exposed no public Close(), so the wsCancel() cleanup was a
no-op. The socket stayed open, the SDK kept auto-reconnecting, and Feishu
kept pushing messages — causing cross-environment message duplication when
the same bot was bound elsewhere.
Fix in three layers:
1. Connection teardown
- Upgrade oapi-sdk-go v3.6.1 -> v3.9.7 (adds Client.Close()).
- Add LongConnClient.Close() wrapping wsClient.Close(); factory's cleanup
now calls Close() first, then wsCancel() as a belt-and-braces fallback.
2. Multi-instance coordination
- wsLeaderRetryLoop: after acquiring leadership, re-check the DB before
starting; abort if the channel was deleted/disabled while waiting.
- wsLeaderRenewLoop: on each renewal, re-check the DB; step down if the
channel was deleted/disabled on another instance (HTTP request may have
been served elsewhere), so the leader doesn't keep the connection open
until process restart.
3. Robustness
- DB checks distinguish gorm.ErrRecordNotFound (channel truly gone ->
stop/abort) from transient DB errors (skip this round, retry next tick)
so a DB hiccup can't cause a spurious stop or permanent leader-abort.
- startChannelInternal now stops any existing channelState for the same
ID before overwriting, making it idempotent against concurrent start
paths and preventing adapter/long-connection leaks.
No interface changes; webhook and long-poll modes unaffected.
Co-Authored-By: Claude <noreply@anthropic.com>
61 lines
2.0 KiB
Go
61 lines
2.0 KiB
Go
package feishu
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/Tencent/WeKnora/internal/im"
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
|
)
|
|
|
|
// NewFactory returns an im.AdapterFactory for Feishu (Lark) channels.
|
|
// The HTTP adapter is always created (needed for SendReply in both modes);
|
|
// "websocket" mode additionally runs a long-connection event stream.
|
|
func NewFactory() im.AdapterFactory {
|
|
return func(factoryCtx context.Context, channel *im.IMChannel, msgHandler func(context.Context, *im.IncomingMessage) error) (im.Adapter, context.CancelFunc, error) {
|
|
creds, err := im.ParseCredentials(channel.Credentials)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("parse feishu credentials: %w", err)
|
|
}
|
|
|
|
appID := im.GetString(creds, "app_id")
|
|
appSecret := im.GetString(creds, "app_secret")
|
|
verificationToken := im.GetString(creds, "verification_token")
|
|
encryptKey := im.GetString(creds, "encrypt_key")
|
|
|
|
// Always create the HTTP adapter (needed for SendReply in both modes)
|
|
adapter := NewAdapter(appID, appSecret, verificationToken, encryptKey)
|
|
|
|
mode := im.ResolveMode(channel, "websocket")
|
|
|
|
switch mode {
|
|
case "webhook":
|
|
return adapter, nil, nil
|
|
|
|
case "websocket":
|
|
client := NewLongConnClient(appID, appSecret, msgHandler)
|
|
|
|
wsCtx, wsCancel := context.WithCancel(context.Background())
|
|
go func() {
|
|
if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil {
|
|
logger.Errorf(context.Background(), "[IM] Feishu long connection stopped for channel %s: %v", channel.ID, err)
|
|
}
|
|
}()
|
|
|
|
// stop tears down the connection for real. wsCancel alone is a
|
|
// no-op: the Feishu SDK's Start blocks on select{} and never
|
|
// observes ctx, so we must call Close() to actually close the
|
|
// socket and disable auto-reconnect. wsCancel is kept as a
|
|
// belt-and-braces fallback for the start goroutine.
|
|
stop := func() {
|
|
client.Close()
|
|
wsCancel()
|
|
}
|
|
return adapter, stop, nil
|
|
|
|
default:
|
|
return nil, nil, fmt.Errorf("unknown Feishu mode: %s", mode)
|
|
}
|
|
}
|
|
}
|