fix(whatsmeow): harden client lifecycle against duplicate starts and races
- Skip a second StartClient while one is starting (adapted from upstream PR #239). - Do not restart a client without a paired device; it would cycle QR codes forever (adapted from upstream PR #240). - Serialize ReconnectClient per instance and nil-check the client: two Disconnected events in the same second dereferenced a removed client and killed the whole process (upstream issue #188). - safemap.TrySend / TrySendTimeout: kill-channel sends no longer panic with "send on closed channel" when the instance is deleted during QR handling (upstream issue #222). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
74389cc8de
commit
4998ab3d45
2 files changed
+97
-8
No files matched your search
@@ -182,11 +182,22 @@ type ProxyConfig struct {
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// reconnectsInProgress holds the instance IDs with a ReconnectClient running. Two Disconnected events for
|
||||
// the same instance in the same second used to run two reconnects concurrently and dereference a client the
|
||||
// other one had just removed, killing the whole process (upstream issue #188).
|
||||
var reconnectsInProgress sync.Map
|
||||
|
||||
func (w whatsmeowService) ReconnectClient(instanceId string) error {
|
||||
if _, running := reconnectsInProgress.LoadOrStore(instanceId, struct{}{}); running {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Reconnection already in progress, skipping duplicate request", instanceId)
|
||||
return nil
|
||||
}
|
||||
defer reconnectsInProgress.Delete(instanceId)
|
||||
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Starting reconnection process - simulating restart", instanceId)
|
||||
|
||||
// Passo 1: Limpar conexão existente se houver
|
||||
if client, exists := w.clientPointer.Lookup(instanceId); exists {
|
||||
if client, exists := w.clientPointer.Lookup(instanceId); exists && client != nil {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Disconnecting existing client", instanceId)
|
||||
|
||||
// Desconectar o cliente WebSocket
|
||||
@@ -209,11 +220,8 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
|
||||
|
||||
// Enviar sinal de kill se o canal existir
|
||||
if killChan, exists := w.killChannel.Lookup(instanceId); exists {
|
||||
select {
|
||||
case killChan <- true:
|
||||
if safemap.TrySendTimeout(killChan, true, 0) {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill signal sent", instanceId)
|
||||
default:
|
||||
// Canal pode estar bloqueado, continua
|
||||
}
|
||||
}
|
||||
|
||||
@@ -457,8 +465,25 @@ func reconnectSucceeded(instanceID string) {
|
||||
reconnectMu.Unlock()
|
||||
}
|
||||
|
||||
// clientsStarting holds the instance IDs whose StartClient is between entry and registering the new client in
|
||||
// clientPointer. Without it, a second StartClient in that window (e.g. GET /instance/qr right after
|
||||
// POST /instance/connect, which starts the client in a goroutine) sees no client and starts another one
|
||||
// (upstream PR #239).
|
||||
var clientsStarting sync.Map
|
||||
|
||||
func (w whatsmeowService) StartClient(cd *ClientData) {
|
||||
|
||||
if _, starting := clientsStarting.LoadOrStore(cd.Instance.Id, struct{}{}); starting {
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Client start already in progress, skipping duplicate start", cd.Instance.Id)
|
||||
return
|
||||
}
|
||||
registered := false
|
||||
defer func() {
|
||||
if !registered {
|
||||
clientsStarting.Delete(cd.Instance.Id)
|
||||
}
|
||||
}()
|
||||
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Starting websocket connection to Whatsapp for user '%s'", cd.Instance.Id)
|
||||
|
||||
var deviceStore *store.Device
|
||||
@@ -555,6 +580,9 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
|
||||
client := whatsmeow.NewClient(deviceStore, clientLog)
|
||||
|
||||
w.clientPointer.Set(cd.Instance.Id, client)
|
||||
// Registered: later callers see this client, and the restart below (which re-enters StartClient) must not be blocked.
|
||||
clientsStarting.Delete(cd.Instance.Id)
|
||||
registered = true
|
||||
|
||||
if cd.IsProxy {
|
||||
var proxyConfig ProxyConfig
|
||||
@@ -766,6 +794,14 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
|
||||
go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)
|
||||
}
|
||||
|
||||
// Without a paired device (QR timed out, logged out, or the phone removed this device) a restart would
|
||||
// only create a new device and cycle QR codes forever. Stop here; the next /instance/connect or
|
||||
// /instance/qr starts a fresh client (upstream PR #240).
|
||||
if client.Store.ID == nil {
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] No paired device; not restarting client", cd.Instance.Id)
|
||||
return
|
||||
}
|
||||
|
||||
// restart client
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Restarting client", cd.Instance.Id)
|
||||
w.StartClient(cd)
|
||||
@@ -991,7 +1027,9 @@ func (mycli *MyClient) teardownQR(reason string, forceLogout bool) {
|
||||
// the original timeout branch so the signal is never dropped.
|
||||
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] QR timeout — signaling kill channel", instanceID)
|
||||
if killChan, exists := mycli.killChannel.Lookup(instanceID); exists {
|
||||
killChan <- true
|
||||
if !safemap.TrySend(killChan, true) {
|
||||
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] Kill channel already closed (instance deleted)", instanceID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2063,7 +2101,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
|
||||
}
|
||||
|
||||
// Agora mata o canal DEPOIS de enviar o evento
|
||||
mycli.killChannel.Get(mycli.userID) <- true
|
||||
safemap.TrySend(mycli.killChannel.Get(mycli.userID), true)
|
||||
case *events.ChatPresence:
|
||||
doWebhook = true
|
||||
postMap["event"] = "ChatPresence"
|
||||
|
||||
Reference in new issue
Block a user