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:
jfengandClaude Opus 5.5 committed 2026-11-09 12:04:18 -03:00
1 parent 74389cc8de
commit 4998ab3d45
2 files changed
+97 -8

No files matched your search

+52 -1
View File
@@ -27,7 +27,10 @@
// library — so anything can use it. // library — so anything can use it.
package safemap package safemap
import "sync" import (
"sync"
"time"
)
// Map is a map[string]T guarded by a read/write mutex. // Map is a map[string]T guarded by a read/write mutex.
// //
@@ -97,3 +100,51 @@ func (s *Map[T]) Snapshot() map[string]T {
} }
return out return out
} }
// TrySend delivers v on ch and reports whether it was delivered.
//
// The kill channels are closed when an instance is deleted, and a goroutine
// that still holds a reference (QR timeout, Disconnected handler) used to
// panic with "send on closed channel", taking the whole process down
// (upstream issue #222). A nil channel (instance already removed from the map)
// would block forever, so it is reported as not delivered instead.
func TrySend[T any](ch chan T, v T) (ok bool) {
if ch == nil {
return false
}
defer func() {
if recover() != nil {
ok = false
}
}()
ch <- v
return true
}
// TrySendTimeout is TrySend bounded by d. A d of zero makes it non-blocking.
func TrySendTimeout[T any](ch chan T, v T, d time.Duration) (ok bool) {
if ch == nil {
return false
}
defer func() {
if recover() != nil {
ok = false
}
}()
if d <= 0 {
select {
case ch <- v:
return true
default:
return false
}
}
timer := time.NewTimer(d)
defer timer.Stop()
select {
case ch <- v:
return true
case <-timer.C:
return false
}
}
+45 -7
View File
@@ -182,11 +182,22 @@ type ProxyConfig struct {
Username string `json:"username"` 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 { 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) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Starting reconnection process - simulating restart", instanceId)
// Passo 1: Limpar conexão existente se houver // 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) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Disconnecting existing client", instanceId)
// Desconectar o cliente WebSocket // Desconectar o cliente WebSocket
@@ -209,11 +220,8 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
// Enviar sinal de kill se o canal existir // Enviar sinal de kill se o canal existir
if killChan, exists := w.killChannel.Lookup(instanceId); exists { if killChan, exists := w.killChannel.Lookup(instanceId); exists {
select { if safemap.TrySendTimeout(killChan, true, 0) {
case killChan <- true:
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill signal sent", instanceId) 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() 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) { 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) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Starting websocket connection to Whatsapp for user '%s'", cd.Instance.Id)
var deviceStore *store.Device var deviceStore *store.Device
@@ -555,6 +580,9 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
client := whatsmeow.NewClient(deviceStore, clientLog) client := whatsmeow.NewClient(deviceStore, clientLog)
w.clientPointer.Set(cd.Instance.Id, client) 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 { if cd.IsProxy {
var proxyConfig ProxyConfig var proxyConfig ProxyConfig
@@ -766,6 +794,14 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID) 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 // restart client
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Restarting client", cd.Instance.Id) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Restarting client", cd.Instance.Id)
w.StartClient(cd) 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. // the original timeout branch so the signal is never dropped.
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] QR timeout — signaling kill channel", instanceID) mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] QR timeout — signaling kill channel", instanceID)
if killChan, exists := mycli.killChannel.Lookup(instanceID); exists { 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 // 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: case *events.ChatPresence:
doWebhook = true doWebhook = true
postMap["event"] = "ChatPresence" postMap["event"] = "ChatPresence"