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 instance_service
|
||||
|
||||
import (
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
@@ -50,8 +51,8 @@ type InstanceService interface {
|
||||
type instances struct {
|
||||
instanceRepository instance_repository.InstanceRepository
|
||||
config *config.Config
|
||||
killChannel map[string](chan bool)
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
killChannel *safemap.Map[chan bool]
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
@@ -124,7 +125,7 @@ type ForceReconnectStruct struct {
|
||||
|
||||
func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
logger := i.loggerWrapper.GetLogger(instanceId)
|
||||
client := i.clientPointer[instanceId]
|
||||
client := i.clientPointer.Get(instanceId)
|
||||
logger.LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
|
||||
|
||||
if client == nil {
|
||||
@@ -138,7 +139,7 @@ func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client,
|
||||
logger.LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = i.clientPointer[instanceId]
|
||||
client = i.clientPointer.Get(instanceId)
|
||||
logger.LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
@@ -242,7 +243,7 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
|
||||
}
|
||||
|
||||
// Verifica se a instância já está rodando
|
||||
isInstanceRunning := i.clientPointer[instance.Id] != nil
|
||||
isInstanceRunning := i.clientPointer.Get(instance.Id) != nil
|
||||
|
||||
// Sincroniza as configurações na instância em execução (se já estiver conectada)
|
||||
err = i.whatsmeowService.UpdateInstanceSettings(instance.Id)
|
||||
@@ -258,7 +259,7 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
|
||||
if !isInstanceRunning {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting new client instance", instance.Id)
|
||||
|
||||
i.killChannel[instance.Id] = make(chan bool)
|
||||
i.killChannel.Set(instance.Id, make(chan bool))
|
||||
|
||||
clientData := &whatsmeow_service.ClientData{
|
||||
Instance: instance,
|
||||
@@ -288,8 +289,8 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
|
||||
// logger.LogInfo("Waiting 1 seconds")
|
||||
// time.Sleep(1000 * time.Millisecond)
|
||||
|
||||
// if i.clientPointer[instance.Id] != nil {
|
||||
// if !i.clientPointer[instance.Id].IsConnected() {
|
||||
// if i.clientPointer.Get(instance.Id) != nil {
|
||||
// if !i.clientPointer.Get(instance.Id).IsConnected() {
|
||||
// return instance, "", "", fmt.Errorf("failed to connect")
|
||||
// }
|
||||
// } else {
|
||||
@@ -317,7 +318,7 @@ func (i instances) Disconnect(instance *instance_model.Instance) (*instance_mode
|
||||
if client.IsConnected() {
|
||||
if client.IsLoggedIn() {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
|
||||
i.killChannel[instance.Id] <- true
|
||||
i.killChannel.Get(instance.Id) <- true
|
||||
|
||||
instance.Events = ""
|
||||
|
||||
@@ -353,12 +354,12 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
|
||||
}
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case i.killChannel.Get(instance.Id) <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
i.clientPointer.Delete(instance.Id)
|
||||
i.killChannel.Delete(instance.Id)
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Logout successful", instance.Id)
|
||||
return instance, nil
|
||||
@@ -368,12 +369,12 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
|
||||
client.Disconnect()
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case i.killChannel.Get(instance.Id) <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
i.clientPointer.Delete(instance.Id)
|
||||
i.killChannel.Delete(instance.Id)
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
|
||||
return instance, nil
|
||||
@@ -384,7 +385,7 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
|
||||
}
|
||||
|
||||
func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, error) {
|
||||
client := i.clientPointer[instance.Id]
|
||||
client := i.clientPointer.Get(instance.Id)
|
||||
|
||||
if client == nil {
|
||||
return &StatusStruct{
|
||||
@@ -413,7 +414,7 @@ func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, err
|
||||
|
||||
func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, error) {
|
||||
logger := i.loggerWrapper.GetLogger(instance.Id)
|
||||
client := i.clientPointer[instance.Id]
|
||||
client := i.clientPointer.Get(instance.Id)
|
||||
|
||||
// Se não há cliente ou o cliente está logado, precisamos iniciar um novo cliente
|
||||
if client == nil || client.IsLoggedIn() {
|
||||
@@ -435,7 +436,7 @@ func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, erro
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
// Verificar novamente se há cliente
|
||||
client = i.clientPointer[instance.Id]
|
||||
client = i.clientPointer.Get(instance.Id)
|
||||
if client != nil && client.IsLoggedIn() {
|
||||
return nil, fmt.Errorf("session already logged in")
|
||||
}
|
||||
@@ -511,7 +512,7 @@ func buildPasskeyOpenURL(token string) string {
|
||||
|
||||
func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error) {
|
||||
logger := i.loggerWrapper.GetLogger(instance.Id)
|
||||
client := i.clientPointer[instance.Id]
|
||||
client := i.clientPointer.Get(instance.Id)
|
||||
|
||||
if client == nil || !client.IsConnected() {
|
||||
if client != nil && client.IsLoggedIn() {
|
||||
@@ -525,7 +526,7 @@ func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*P
|
||||
// Wait for the WA websocket connection and initial QR generation to establish.
|
||||
// PairPhone must be called after the QR event is received per whatsmeow docs.
|
||||
time.Sleep(3 * time.Second)
|
||||
client = i.clientPointer[instance.Id]
|
||||
client = i.clientPointer.Get(instance.Id)
|
||||
if client == nil {
|
||||
return nil, fmt.Errorf("failed to initialize client for pairing")
|
||||
}
|
||||
@@ -551,7 +552,7 @@ func (i instances) GetAll() ([]*instance_model.Instance, error) {
|
||||
}
|
||||
|
||||
for _, instance := range instances {
|
||||
if client := i.clientPointer[instance.Id]; client != nil {
|
||||
if client := i.clientPointer.Get(instance.Id); client != nil {
|
||||
instance.Connected = client.IsLoggedIn()
|
||||
} else {
|
||||
instance.Connected = false
|
||||
@@ -570,7 +571,7 @@ func (i instances) Info(instanceId string) (*instance_model.Instance, error) {
|
||||
}
|
||||
|
||||
// Atualiza o status connected com base no estado real do cliente
|
||||
if client := i.clientPointer[instance.Id]; client != nil {
|
||||
if client := i.clientPointer.Get(instance.Id); client != nil {
|
||||
instance.Connected = client.IsLoggedIn()
|
||||
} else {
|
||||
instance.Connected = false
|
||||
@@ -587,18 +588,18 @@ func (i instances) Delete(id string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if i.clientPointer[instance.Id] != nil && i.clientPointer[instance.Id].IsConnected() {
|
||||
if i.clientPointer[instance.Id].IsLoggedIn() {
|
||||
i.clientPointer[instance.Id].Logout(context.Background())
|
||||
if i.clientPointer.Get(instance.Id) != nil && i.clientPointer.Get(instance.Id).IsConnected() {
|
||||
if i.clientPointer.Get(instance.Id).IsLoggedIn() {
|
||||
i.clientPointer.Get(instance.Id).Logout(context.Background())
|
||||
}
|
||||
i.clientPointer[instance.Id].Disconnect()
|
||||
i.clientPointer.Get(instance.Id).Disconnect()
|
||||
}
|
||||
|
||||
// Limpar todos os recursos da instância antes de deletar
|
||||
delete(i.clientPointer, instance.Id)
|
||||
if i.killChannel[instance.Id] != nil {
|
||||
close(i.killChannel[instance.Id])
|
||||
delete(i.killChannel, instance.Id)
|
||||
i.clientPointer.Delete(instance.Id)
|
||||
if i.killChannel.Get(instance.Id) != nil {
|
||||
close(i.killChannel.Get(instance.Id))
|
||||
i.killChannel.Delete(instance.Id)
|
||||
}
|
||||
|
||||
// Limpar cache via whatsmeow service
|
||||
@@ -697,7 +698,7 @@ func (i instances) RemoveProxy(id string) error {
|
||||
}
|
||||
|
||||
func (i instances) ForceReconnect(instanceId string, number string) error {
|
||||
if i.clientPointer[instanceId].IsConnected() && i.clientPointer[instanceId].IsLoggedIn() {
|
||||
if i.clientPointer.Get(instanceId).IsConnected() && i.clientPointer.Get(instanceId).IsLoggedIn() {
|
||||
return fmt.Errorf("client already connected")
|
||||
}
|
||||
|
||||
@@ -713,7 +714,7 @@ func (i instances) ForceReconnect(instanceId string, number string) error {
|
||||
|
||||
subscribedEvents := strings.Split(instance.Events, ",")
|
||||
|
||||
i.killChannel[instance.Id] = make(chan bool)
|
||||
i.killChannel.Set(instance.Id, make(chan bool))
|
||||
|
||||
clientData := &whatsmeow_service.ClientData{
|
||||
Instance: instance,
|
||||
@@ -735,29 +736,29 @@ func (i instances) ForceReconnect(instanceId string, number string) error {
|
||||
}
|
||||
}
|
||||
|
||||
if i.clientPointer[instance.Id] != nil {
|
||||
client := i.clientPointer[instance.Id]
|
||||
if i.clientPointer.Get(instance.Id) != nil {
|
||||
client := i.clientPointer.Get(instance.Id)
|
||||
client.Disconnect()
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case i.killChannel.Get(instance.Id) <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
i.clientPointer.Delete(instance.Id)
|
||||
i.killChannel.Delete(instance.Id)
|
||||
}
|
||||
|
||||
go i.whatsmeowService.StartClient(clientData)
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
if i.clientPointer[instance.Id] != nil {
|
||||
if !i.clientPointer[instance.Id].IsConnected() {
|
||||
if i.clientPointer.Get(instance.Id) != nil {
|
||||
if !i.clientPointer.Get(instance.Id).IsConnected() {
|
||||
return fmt.Errorf("failed to connect")
|
||||
}
|
||||
|
||||
if !i.clientPointer[instance.Id].IsLoggedIn() {
|
||||
if !i.clientPointer.Get(instance.Id).IsLoggedIn() {
|
||||
return fmt.Errorf("failed to login")
|
||||
}
|
||||
} else {
|
||||
@@ -912,8 +913,8 @@ func (i instances) UpdateAdvancedSettings(instanceId string, settings *instance_
|
||||
|
||||
func NewInstanceService(
|
||||
instanceRepository instance_repository.InstanceRepository,
|
||||
killChannel map[string](chan bool),
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
killChannel *safemap.Map[chan bool],
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
config *config.Config,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
|
||||
Reference in new issue
Block a user