fix(concurrency): guard the three shared maps with a mutex
clientPointer, myClientPointer and killChannel are created once at startup and
passed by reference into eleven packages. All of them read and wrote those plain
Go maps from different goroutines, with no synchronisation.
Go does not tolerate that: the runtime kills the process with
fatal error: concurrent map writes
and a fatal error is not recoverable — a deferred recover() does not catch it.
Measured in production: the process died inside StartClient while five instances
were connecting at once. The orchestrator restarted it within seconds, but every
number was offline in the meantime, and it repeats on any restart that brings up
more than a couple of instances together.
The three maps become safemap.Map[T], a generic wrapper over a RWMutex. It lives
in its own package because MyClient is defined in pkg/whatsmeow/service, and
putting the type there would create an import cycle with the ten packages that
receive the maps.
98 call sites changed across 12 files, with the compiler as the judge: anything
missed is a build error, not a silent bug.
Tests: with -race, a plain map running the same exercise reports DATA RACE and
fails, while safemap.Map passes. Both halves verified.
(cherry picked from commit 3860fa278dc2b901705ffbddbed5cf59d70a85e4)
This commit is contained in:
1 parent
a5f7e1c98a
commit
0c4ac7d9a9
14 files changed
+311
-129
No files matched your search
@@ -1,6 +1,7 @@
|
||||
package whatsmeow_service
|
||||
|
||||
import (
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
@@ -83,10 +84,10 @@ type whatsmeowService struct {
|
||||
labelRepository label_repository.LabelRepository
|
||||
pollService poll_service.PollService // NOVO: Serviço de enquetes
|
||||
config *config.Config
|
||||
killChannel map[string](chan bool)
|
||||
killChannel *safemap.Map[chan bool]
|
||||
userInfoCache *cache.Cache
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
myClientPointer map[string]*MyClient
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
myClientPointer *safemap.Map[*MyClient]
|
||||
rabbitmqProducer producer_interfaces.Producer
|
||||
webhookProducer producer_interfaces.Producer
|
||||
websocketProducer producer_interfaces.Producer
|
||||
@@ -115,9 +116,9 @@ type MyClient struct {
|
||||
messageRepository message_repository.MessageRepository
|
||||
labelRepository label_repository.LabelRepository
|
||||
pollService poll_service.PollService // NOVO: Serviço de enquetes
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
myClientPointer map[string]*MyClient
|
||||
killChannel map[string](chan bool)
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
myClientPointer *safemap.Map[*MyClient]
|
||||
killChannel *safemap.Map[chan bool]
|
||||
userInfoCache *cache.Cache
|
||||
config *config.Config
|
||||
historySyncID int32
|
||||
@@ -175,7 +176,7 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
|
||||
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[instanceId]; exists {
|
||||
if client, exists := w.clientPointer.Lookup(instanceId); exists {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Disconnecting existing client", instanceId)
|
||||
|
||||
// Desconectar o cliente WebSocket
|
||||
@@ -185,7 +186,7 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
|
||||
}
|
||||
|
||||
// Remover event handler se existir
|
||||
if mycli, ok := w.myClientPointer[instanceId]; ok {
|
||||
if mycli, ok := w.myClientPointer.Lookup(instanceId); ok {
|
||||
if mycli.eventHandlerID != 0 {
|
||||
client.RemoveEventHandler(mycli.eventHandlerID)
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Event handler removed", instanceId)
|
||||
@@ -197,7 +198,7 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Cleaning up resources", instanceId)
|
||||
|
||||
// Enviar sinal de kill se o canal existir
|
||||
if killChan, exists := w.killChannel[instanceId]; exists {
|
||||
if killChan, exists := w.killChannel.Lookup(instanceId); exists {
|
||||
select {
|
||||
case killChan <- true:
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill signal sent", instanceId)
|
||||
@@ -207,9 +208,9 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
|
||||
}
|
||||
|
||||
// Remover das estruturas
|
||||
delete(w.clientPointer, instanceId)
|
||||
delete(w.myClientPointer, instanceId)
|
||||
delete(w.killChannel, instanceId)
|
||||
w.clientPointer.Delete(instanceId)
|
||||
w.myClientPointer.Delete(instanceId)
|
||||
w.killChannel.Delete(instanceId)
|
||||
|
||||
// Limpar cache de userInfo para esta instância
|
||||
if instance, err := w.instanceRepository.GetInstanceByID(instanceId); err == nil {
|
||||
@@ -308,8 +309,8 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
|
||||
var deviceStore *store.Device
|
||||
var err error
|
||||
|
||||
if w.clientPointer[cd.Instance.Id] != nil {
|
||||
if w.clientPointer[cd.Instance.Id].IsConnected() {
|
||||
if w.clientPointer.Get(cd.Instance.Id) != nil {
|
||||
if w.clientPointer.Get(cd.Instance.Id).IsConnected() {
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -416,7 +417,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
|
||||
clientLog := waLog.Stdout("Client", minLevel, true)
|
||||
client := whatsmeow.NewClient(deviceStore, clientLog)
|
||||
|
||||
w.clientPointer[cd.Instance.Id] = client
|
||||
w.clientPointer.Set(cd.Instance.Id, client)
|
||||
|
||||
if cd.IsProxy {
|
||||
var proxyConfig ProxyConfig
|
||||
@@ -504,7 +505,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
|
||||
mycli.eventHandlerID = mycli.WAClient.AddEventHandler(mycli.myEventHandler)
|
||||
|
||||
// Armazena o MyClient no map para permitir atualizações posteriores
|
||||
w.myClientPointer[cd.Instance.Id] = mycli
|
||||
w.myClientPointer.Set(cd.Instance.Id, mycli)
|
||||
|
||||
if client.Store.ID != nil {
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Already logged in with JID: %s", cd.Instance.Id, client.Store.ID.String())
|
||||
@@ -578,12 +579,12 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-w.killChannel[cd.Instance.Id]:
|
||||
case <-w.killChannel.Get(cd.Instance.Id):
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Received kill signal for user '%s'", cd.Instance.Id)
|
||||
client.Disconnect()
|
||||
|
||||
delete(w.clientPointer, cd.Instance.Id)
|
||||
delete(w.myClientPointer, cd.Instance.Id)
|
||||
w.clientPointer.Delete(cd.Instance.Id)
|
||||
w.myClientPointer.Delete(cd.Instance.Id)
|
||||
|
||||
// Limpar cache de userInfo para esta instância
|
||||
w.userInfoCache.Delete(cd.Instance.Token)
|
||||
@@ -658,7 +659,7 @@ func schedulePresenceUpdates(mycli *MyClient) {
|
||||
randomInterval := time.Duration(1+rand.Intn(3)) * time.Hour
|
||||
ticker = time.NewTicker(randomInterval)
|
||||
|
||||
case <-mycli.killChannel[mycli.userID]:
|
||||
case <-mycli.killChannel.Get(mycli.userID):
|
||||
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Received kill signal, stopping presence updates", mycli.userID)
|
||||
return // Encerra a goroutine quando receber sinal de kill
|
||||
}
|
||||
@@ -852,7 +853,7 @@ func (mycli *MyClient) teardownQR(reason string, forceLogout bool) {
|
||||
// maps (it is the single writer for this instance). Blocking send mirrors
|
||||
// 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[instanceID]; exists {
|
||||
if killChan, exists := mycli.killChannel.Lookup(instanceID); exists {
|
||||
killChan <- true
|
||||
}
|
||||
}
|
||||
@@ -911,7 +912,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
|
||||
|
||||
// jid, ok := utils.ParseJID(mycli.WAClient.Store.ID.ToNonAD().User)
|
||||
// if ok {
|
||||
// profilePicUrl, err := mycli.clientPointer[mycli.userID].GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{
|
||||
// profilePicUrl, err := mycli.clientPointer.Get(mycli.userID).GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{
|
||||
// Preview: false,
|
||||
// })
|
||||
// if err != nil {
|
||||
@@ -1281,7 +1282,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
|
||||
fmt.Printf("[POLL DEBUG] ✅ mycli.WAClient is initialized: %s\n", mycli.WAClient.Store.ID)
|
||||
}
|
||||
|
||||
decrypted, err := mycli.clientPointer[mycli.userID].DecryptPollVote(context.Background(), evt)
|
||||
decrypted, err := mycli.clientPointer.Get(mycli.userID).DecryptPollVote(context.Background(), evt)
|
||||
if err != nil {
|
||||
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decrypt vote: %v", mycli.userID, err)
|
||||
} else {
|
||||
@@ -1922,7 +1923,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
|
||||
}
|
||||
|
||||
// Agora mata o canal DEPOIS de enviar o evento
|
||||
mycli.killChannel[mycli.userID] <- true
|
||||
mycli.killChannel.Get(mycli.userID) <- true
|
||||
case *events.ChatPresence:
|
||||
doWebhook = true
|
||||
postMap["event"] = "ChatPresence"
|
||||
@@ -2407,7 +2408,7 @@ func (w whatsmeowService) StartInstance(instanceId string) error {
|
||||
}
|
||||
}
|
||||
|
||||
w.killChannel[instance.Id] = make(chan bool)
|
||||
w.killChannel.Set(instance.Id, make(chan bool))
|
||||
|
||||
clientData := &ClientData{
|
||||
Instance: instance,
|
||||
@@ -2715,7 +2716,7 @@ func (w whatsmeowService) UpdateInstanceSettings(instanceId string) error {
|
||||
}
|
||||
|
||||
// Verifica se o MyClient existe
|
||||
myClient, exists := w.myClientPointer[instanceId]
|
||||
myClient, exists := w.myClientPointer.Lookup(instanceId)
|
||||
if !exists {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId)
|
||||
return fmt.Errorf("instance %s not found in runtime", instanceId)
|
||||
@@ -2774,7 +2775,7 @@ func (w whatsmeowService) UpdateInstanceAdvancedSettings(instanceId string) erro
|
||||
}
|
||||
|
||||
// Verifica se o MyClient existe
|
||||
myClient, exists := w.myClientPointer[instanceId]
|
||||
myClient, exists := w.myClientPointer.Lookup(instanceId)
|
||||
if !exists {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId)
|
||||
return fmt.Errorf("instance %s not found in runtime", instanceId)
|
||||
@@ -2794,19 +2795,19 @@ func (w whatsmeowService) ClearInstanceCache(instanceId string, token string) er
|
||||
w.userInfoCache.Delete(token)
|
||||
|
||||
// Limpar myClientPointer se existir
|
||||
if _, exists := w.myClientPointer[instanceId]; exists {
|
||||
delete(w.myClientPointer, instanceId)
|
||||
if _, exists := w.myClientPointer.Lookup(instanceId); exists {
|
||||
w.myClientPointer.Delete(instanceId)
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] MyClient pointer cleared", instanceId)
|
||||
}
|
||||
|
||||
// Limpar clientPointer se existir
|
||||
if _, exists := w.clientPointer[instanceId]; exists {
|
||||
delete(w.clientPointer, instanceId)
|
||||
if _, exists := w.clientPointer.Lookup(instanceId); exists {
|
||||
w.clientPointer.Delete(instanceId)
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client pointer cleared", instanceId)
|
||||
}
|
||||
|
||||
// Limpar killChannel se existir
|
||||
if killChan, exists := w.killChannel[instanceId]; exists {
|
||||
if killChan, exists := w.killChannel.Lookup(instanceId); exists {
|
||||
select {
|
||||
case killChan <- true:
|
||||
// Canal recebeu o sinal
|
||||
@@ -2814,7 +2815,7 @@ func (w whatsmeowService) ClearInstanceCache(instanceId string, token string) er
|
||||
// Canal pode estar bloqueado, apenas fecha
|
||||
}
|
||||
close(killChan)
|
||||
delete(w.killChannel, instanceId)
|
||||
w.killChannel.Delete(instanceId)
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill channel cleared", instanceId)
|
||||
}
|
||||
|
||||
@@ -2828,8 +2829,8 @@ func NewWhatsmeowService(
|
||||
messageRepository message_repository.MessageRepository,
|
||||
labelRepository label_repository.LabelRepository,
|
||||
config *config.Config,
|
||||
killChannel map[string](chan bool),
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
killChannel *safemap.Map[chan bool],
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
rabbitmqProducer producer_interfaces.Producer,
|
||||
webhookProducer producer_interfaces.Producer,
|
||||
websocketProducer producer_interfaces.Producer,
|
||||
@@ -2852,7 +2853,7 @@ func NewWhatsmeowService(
|
||||
killChannel: killChannel,
|
||||
userInfoCache: cache.New(5*time.Minute, 10*time.Minute),
|
||||
clientPointer: clientPointer,
|
||||
myClientPointer: make(map[string]*MyClient),
|
||||
myClientPointer: safemap.New[*MyClient](),
|
||||
rabbitmqProducer: rabbitmqProducer,
|
||||
webhookProducer: webhookProducer,
|
||||
websocketProducer: websocketProducer,
|
||||
@@ -2880,7 +2881,7 @@ func (w *whatsmeowService) PasskeyCeremonyStore() *ceremony.Store {
|
||||
// SubmitPasskeyResponse forwards the browser's WebAuthn assertion to WhatsApp
|
||||
// for the given instance. Called by POST /passkey-ceremony/{token}/response.
|
||||
func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.WebAuthnResponse) error {
|
||||
client, ok := w.clientPointer[instanceId]
|
||||
client, ok := w.clientPointer.Lookup(instanceId)
|
||||
if !ok || client == nil {
|
||||
return fmt.Errorf("no active client for instance %s", instanceId)
|
||||
}
|
||||
@@ -2899,7 +2900,7 @@ func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.
|
||||
// ConfirmPasskey finishes the pairing after the user verified the code.
|
||||
// Called by POST /passkey-ceremony/{token}/confirm.
|
||||
func (w *whatsmeowService) ConfirmPasskey(instanceId string) error {
|
||||
client, ok := w.clientPointer[instanceId]
|
||||
client, ok := w.clientPointer.Lookup(instanceId)
|
||||
if !ok || client == nil {
|
||||
return fmt.Errorf("no active client for instance %s", instanceId)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user