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)
258 lines
8.3 KiB
Go
258 lines
8.3 KiB
Go
package chat_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"
|
|
"go.mau.fi/whatsmeow"
|
|
"go.mau.fi/whatsmeow/appstate"
|
|
"go.mau.fi/whatsmeow/types"
|
|
)
|
|
|
|
type ChatService interface {
|
|
ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
|
ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
|
ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
|
ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
|
ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
|
ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error)
|
|
HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error)
|
|
}
|
|
|
|
type chatService struct {
|
|
clientPointer *safemap.Map[*whatsmeow.Client]
|
|
whatsmeowService whatsmeow_service.WhatsmeowService
|
|
loggerWrapper *logger_wrapper.LoggerManager
|
|
}
|
|
|
|
type BodyStruct struct {
|
|
Chat string `json:"chat"`
|
|
}
|
|
|
|
type HistorySyncRequestStruct struct {
|
|
MessageInfo *types.MessageInfo `json:"messageInfo"`
|
|
Count int `json:"count"`
|
|
}
|
|
|
|
func (c *chatService) 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 *chatService) ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
|
client, err := c.ensureClientConnected(instance.Id)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
var ts time.Time
|
|
|
|
recipient, ok := utils.ParseJID(data.Chat)
|
|
if !ok {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
|
return "", errors.New("invalid phone number")
|
|
}
|
|
|
|
err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, true))
|
|
if err != nil {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error pin chat: %v", instance.Id, err)
|
|
return "", err
|
|
}
|
|
|
|
return ts.String(), nil
|
|
}
|
|
|
|
func (c *chatService) ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
|
client, err := c.ensureClientConnected(instance.Id)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
var ts time.Time
|
|
|
|
recipient, ok := utils.ParseJID(data.Chat)
|
|
if !ok {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
|
return "", errors.New("invalid phone number")
|
|
}
|
|
|
|
err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, false))
|
|
if err != nil {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unpin chat: %v", instance.Id, err)
|
|
return "", err
|
|
}
|
|
|
|
return ts.String(), nil
|
|
}
|
|
|
|
func (c *chatService) ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
|
client, err := c.ensureClientConnected(instance.Id)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
var ts time.Time
|
|
|
|
recipient, ok := utils.ParseJID(data.Chat)
|
|
if !ok {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
|
return "", errors.New("invalid phone number")
|
|
}
|
|
|
|
err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, true, time.Time{}, nil))
|
|
if err != nil {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error archive chat: %v", instance.Id, err)
|
|
return "", err
|
|
}
|
|
|
|
return ts.String(), nil
|
|
}
|
|
|
|
func (c *chatService) ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
|
client, err := c.ensureClientConnected(instance.Id)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
var ts time.Time
|
|
|
|
recipient, ok := utils.ParseJID(data.Chat)
|
|
if !ok {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
|
return "", errors.New("invalid phone number")
|
|
}
|
|
|
|
err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, false, time.Time{}, nil))
|
|
if err != nil {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unarchive chat: %v", instance.Id, err)
|
|
return "", err
|
|
}
|
|
|
|
return ts.String(), nil
|
|
}
|
|
|
|
func (c *chatService) ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
|
client, err := c.ensureClientConnected(instance.Id)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
var ts time.Time
|
|
|
|
recipient, ok := utils.ParseJID(data.Chat)
|
|
if !ok {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
|
return "", errors.New("invalid phone number")
|
|
}
|
|
|
|
err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, true, 1*time.Hour))
|
|
if err != nil {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)
|
|
return "", err
|
|
}
|
|
|
|
return ts.String(), nil
|
|
}
|
|
|
|
func (c *chatService) ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error) {
|
|
client, err := c.ensureClientConnected(instance.Id)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
var ts time.Time
|
|
|
|
recipient, ok := utils.ParseJID(data.Chat)
|
|
if !ok {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
|
|
return "", errors.New("invalid phone number")
|
|
}
|
|
|
|
err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, false, 0*time.Hour))
|
|
if err != nil {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmute chat: %v", instance.Id, err)
|
|
return "", err
|
|
}
|
|
|
|
return ts.String(), nil
|
|
}
|
|
|
|
func (c *chatService) HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error) {
|
|
client, err := c.ensureClientConnected(instance.Id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
messageInfo := types.MessageInfo{
|
|
MessageSource: types.MessageSource{
|
|
Chat: data.MessageInfo.Chat,
|
|
IsFromMe: data.MessageInfo.IsFromMe,
|
|
IsGroup: data.MessageInfo.IsGroup,
|
|
},
|
|
ID: data.MessageInfo.ID,
|
|
Timestamp: data.MessageInfo.Timestamp,
|
|
}
|
|
|
|
histRequest := client.BuildHistorySyncRequest(&messageInfo, data.Count)
|
|
|
|
res, err := client.SendMessage(context.Background(), messageInfo.Chat, histRequest, whatsmeow.SendRequestExtra{Peer: true})
|
|
if err != nil {
|
|
c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error history sync request: %v", instance.Id, err)
|
|
return nil, err
|
|
}
|
|
|
|
return &res, nil
|
|
}
|
|
|
|
func NewChatService(
|
|
clientPointer *safemap.Map[*whatsmeow.Client],
|
|
whatsmeowService whatsmeow_service.WhatsmeowService,
|
|
loggerWrapper *logger_wrapper.LoggerManager,
|
|
) ChatService {
|
|
return &chatService{
|
|
clientPointer: clientPointer,
|
|
whatsmeowService: whatsmeowService,
|
|
loggerWrapper: loggerWrapper,
|
|
}
|
|
}
|