Files
EvoGO/pkg/community/service/community_service.go
T
EcoosUP 0c4ac7d9a9 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)
2026-11-09 12:01:08 -03:00

171 lines
5.6 KiB
Go

package community_service
import (
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"context"
"errors"
"time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/evolution-foundation/evolution-go/pkg/utils"
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
"github.com/gin-gonic/gin"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
)
type CommunityService interface {
CreateCommunity(data *CreateCommunityStruct, instance *instance_model.Instance) (*types.GroupInfo, error)
CommunityAdd(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error)
CommunityRemove(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error)
}
type communityService struct {
clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
type CreateCommunityStruct struct {
CommunityName string `json:"communityName"`
}
type AddParticipantStruct struct {
CommunityJID string `json:"communityJid"`
GroupJID []string `json:"groupJid"`
}
func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)
err := c.whatsmeowService.StartInstance(instanceId)
if err != nil {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)
return nil, errors.New("no active session found")
}
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
if client == nil || !client.IsConnected() {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",
instanceId,
client != nil,
client != nil && client.IsConnected())
return nil, errors.New("no active session found")
}
} else if !client.IsConnected() {
c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",
instanceId,
client.IsConnected())
return nil, errors.New("client disconnected")
}
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())
return client, nil
}
func (c *communityService) CreateCommunity(data *CreateCommunityStruct, instance *instance_model.Instance) (*types.GroupInfo, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
resp, err := client.CreateGroup(context.Background(), whatsmeow.ReqCreateGroup{
Name: data.CommunityName,
GroupParent: types.GroupParent{
IsParent: true,
},
})
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create community: %v", instance.Id, err)
return nil, err
}
return resp, nil
}
func (c *communityService) CommunityAdd(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
communityJID, ok := utils.ParseJID(data.CommunityJID)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
return nil, errors.New("error parse community jid")
}
var successList []string
var failedList []string
for _, participant := range data.GroupJID {
groupJID, _ := utils.ParseJID(participant)
err := client.LinkGroup(context.Background(), communityJID, groupJID)
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error link group: %v", instance.Id, err)
failedList = append(failedList, groupJID.String())
}
successList = append(failedList, groupJID.String())
}
return gin.H{
"success": successList,
"failed": failedList,
}, nil
}
func (c *communityService) CommunityRemove(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error) {
client, err := c.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
}
communityJID, ok := utils.ParseJID(data.CommunityJID)
if !ok {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)
return nil, errors.New("error parse community jid")
}
var successList []string
var failedList []string
for _, participant := range data.GroupJID {
groupJID, _ := utils.ParseJID(participant)
err := client.UnlinkGroup(context.Background(), communityJID, groupJID)
if err != nil {
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error link group: %v", instance.Id, err)
failedList = append(failedList, groupJID.String())
}
successList = append(failedList, groupJID.String())
}
return gin.H{
"success": successList,
"failed": failedList,
}, nil
}
func NewCommunityService(
clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) CommunityService {
return &communityService{
clientPointer: clientPointer,
whatsmeowService: whatsmeowService,
loggerWrapper: loggerWrapper,
}
}