From 4998ab3d45c7f1abd47a47d80e980586135b52ec Mon Sep 17 00:00:00 2001 From: Jorge Fernando dos Santos Date: Mon, 9 Nov 2026 12:04:18 -0300 Subject: [PATCH] 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 --- pkg/safemap/safemap.go | 53 +++++++++++++++++++++++++++++- pkg/whatsmeow/service/whatsmeow.go | 52 +++++++++++++++++++++++++---- 2 files changed, 97 insertions(+), 8 deletions(-) diff --git a/pkg/safemap/safemap.go b/pkg/safemap/safemap.go index 7920999..4e0f0c4 100644 --- a/pkg/safemap/safemap.go +++ b/pkg/safemap/safemap.go @@ -27,7 +27,10 @@ // library — so anything can use it. package safemap -import "sync" +import ( + "sync" + "time" +) // 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 } + +// 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 + } +} diff --git a/pkg/whatsmeow/service/whatsmeow.go b/pkg/whatsmeow/service/whatsmeow.go index 6f88146..e09d82f 100644 --- a/pkg/whatsmeow/service/whatsmeow.go +++ b/pkg/whatsmeow/service/whatsmeow.go @@ -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"