GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
fix(whatsapp): dispatch events through the current registry slot (#935)
Aldino Kemale66173b2978d
diff --git a/src/infrastructure/whatsapp/client_events.go b/src/infrastructure/whatsapp/client_events.gonew file mode 100644index 00000000..b3cd092e--- /dev/null+++ b/src/infrastructure/whatsapp/client_events.go@@ -0,0 +1,74 @@+package whatsapp++import (+ "context"++ "github.com/sirupsen/logrus"+ "go.mau.fi/whatsmeow"+)++// Resolve ownership at admission: a startup client can move into a persisted slot.+// No registry lock is held while handlers perform network, storage or websocket work.+func (m *DeviceManager) eventHandler(client *whatsmeow.Client) func(any) {+ return func(evt any) {+ if owner := m.eventOwner(client); owner != nil {+ handler(context.Background(), owner, evt)+ }+ }+}++func (m *DeviceManager) eventOwner(client *whatsmeow.Client) *DeviceInstance {+ if client == nil {+ return nil+ }+ m.mu.RLock()+ defer m.mu.RUnlock()+ var owner *DeviceInstance+ for _, instance := range m.devices {+ if instance != nil && instance.GetClient() == client {+ if owner != nil {+ return nil+ }+ owner = instance+ }+ }+ if m.transient != nil && m.transient.GetClient() == client {+ if owner != nil {+ return nil+ }+ owner = m.transient+ }+ return owner+}++// Caller holds m.mu before taking any instance lock.+func (m *DeviceManager) attachClientLocked(instance *DeviceInstance, client *whatsmeow.Client) {+ if m.transient != nil && m.transient != instance && client != nil && m.transient.GetClient() == client {+ m.transient.ResetClient()+ m.transient = nil+ }+ if instance.GetClient() != client {+ instance.SetClient(client)+ instance.UpdateStateFromClient()+ }+ instance.SetOnLoggedOut(func(deviceID string) {+ if deviceID == "" {+ m.mu.Lock()+ if m.transient != instance {+ m.mu.Unlock()+ return+ }+ jid := storeIdentity(instance)+ instance.ResetClient()+ m.transient = nil+ m.mu.Unlock()+ if err := m.deleteStoreRowsForJID(context.Background(), jid); err != nil {+ logrus.WithError(err).Warn("[REMOTE_LOGOUT] transient cleanup failed")+ }+ return+ }+ if err := m.keepSlotLogout(context.Background(), deviceID); err != nil {+ logrus.WithError(err).Warnf("[REMOTE_LOGOUT] keep-slot cleanup failed for %s", deviceID)+ }+ })+}diff --git a/src/infrastructure/whatsapp/client_events_test.go b/src/infrastructure/whatsapp/client_events_test.gonew file mode 100644index 00000000..0a49e45e--- /dev/null+++ b/src/infrastructure/whatsapp/client_events_test.go@@ -0,0 +1,254 @@+package whatsapp++import (+ "context"+ "go.mau.fi/whatsmeow"+ "testing"++ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"+ "github.com/stretchr/testify/require"+ "go.mau.fi/whatsmeow/store"+ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+)++func TestStartupEventsFollowRegistryOwner(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ container := newTestSQLStore(t)+ keys := newTestSQLStore(t)+ ad := types.NewADJID("6281777000099", types.WhatsAppDomain, 28)+ require.NoError(t, newTestStoreDevice(container, ad, "Sales").Save(ctx))+ storage := ®istryStubStorage{records: []*domainChatStorage.DeviceRecord{+ {DeviceID: "slot-a", DisplayName: "Sales", JID: ad.ToNonAD().String(), ADJID: ad.String()},+ }}+ globalStateMu.Lock()+ oldManager, oldClient, oldDB, oldKeys := deviceManager, cli, db, keysDB+ deviceManager = nil+ globalStateMu.Unlock()+ oldOS, oldPlatform := store.DeviceProps.Os, store.DeviceProps.PlatformType+ oldChatwoot := config.ChatwootEnabled+ config.ChatwootEnabled = false+ oldBroadcast := websocket.Broadcast+ websocket.Broadcast = make(chan websocket.BroadcastMessage, 10)+ t.Cleanup(func() {+ websocket.Broadcast = oldBroadcast+ config.ChatwootEnabled = oldChatwoot+ store.DeviceProps.Os, store.DeviceProps.PlatformType = oldOS, oldPlatform+ globalStateMu.Lock()+ deviceManager, cli, db, keysDB = oldManager, oldClient, oldDB, oldKeys+ globalStateMu.Unlock()+ })+ got := captureDeviceWebhooks(t)+ client := InitWaCLI(ctx, container, keys, storage)+ manager := GetDeviceManager()+ startup, ok := manager.GetDevice(ad.String())+ require.True(t, ok)+ dispatch := manager.eventHandler(client)+ cancel()+ require.NoError(t, manager.LoadExistingDevices(context.Background()))+ current, ok := manager.GetDevice("slot-a")+ require.True(t, ok)+ require.NotSame(t, startup, current)+ require.Same(t, client, current.GetClient())+ keyDevice, err := keys.GetDevice(context.Background(), ad)+ require.NoError(t, err)+ require.NotNil(t, keyDevice)+ require.NoError(t, keys.DeleteDevice(context.Background(), keyDevice))+ dispatch(&events.PairSuccess{ID: ad})+ require.Equal(t, "LOGIN_SUCCESS", (<-websocket.Broadcast).Code)+ keyDevice, err = keys.GetDevice(context.Background(), ad)+ require.NoError(t, err)+ require.NotNil(t, keyDevice, "pairing must sync keys even after the startup context is cancelled")+ require.NoError(t, newTestStoreDevice(container, types.NewADJID(ad.User, types.WhatsAppDomain, 32), "sibling").Save(context.Background()))+ dispatch(&events.TemporaryBan{})+ require.Equal(t, "slot-a", recvWebhook(t, got).body["session_id"])+ require.Equal(t, "slot-a", (<-websocket.Broadcast).Result.(map[string]any)["device_id"])+ dispatch(&events.LoggedOut{})+ require.Equal(t, "slot-a", recvWebhook(t, got).body["session_id"])+ require.Nil(t, current.GetClient())+ require.Empty(t, current.JID())+ require.Empty(t, current.ADJID())+ require.Equal(t, "Sales", current.DisplayName())+ require.Empty(t, storage.deletedData)+ require.Empty(t, storage.deletedRecords)+ require.Equal(t, "slot-a", storage.savedRecords[len(storage.savedRecords)-1].DeviceID)+ require.Empty(t, storage.savedRecords[len(storage.savedRecords)-1].ADJID)+ require.Equal(t, 1, countStoreRows(t, context.Background(), manager, ad.ToNonAD().String()))+ require.Empty(t, got)+ require.Nil(t, manager.eventOwner(client))+}++func eventTestBroadcast(t *testing.T) {+ t.Helper()+ old := websocket.Broadcast+ websocket.Broadcast = make(chan websocket.BroadcastMessage, 20)+ t.Cleanup(func() { websocket.Broadcast = old })+}++func TestClientEventsSelectExactOwnerAndRejectObsoleteOrAmbiguousClient(t *testing.T) {+ eventTestBroadcast(t)+ container := newTestSQLStore(t)+ manager := NewDeviceManager(container, nil, nil)+ ad := types.NewADJID("6281777000098", types.WhatsAppDomain, 28)+ first := whatsmeow.NewClient(newTestStoreDevice(container, ad, ""), nil)+ second := whatsmeow.NewClient(newTestStoreDevice(container, types.NewADJID(ad.User, types.WhatsAppDomain, 32), ""), nil)+ a, b := NewDeviceInstance("a", first, nil), NewDeviceInstance("b", second, nil)+ manager.AddDevice(a)+ manager.AddDevice(b)+ dispatch := manager.eventHandler(first)+ dispatch(&events.PairPasskeyConfirmation{Code: "first"})+ _, code, _ := a.PasskeyState()+ require.Equal(t, "first", code)+ _, code, _ = b.PasskeyState()+ require.Empty(t, code)+ require.Len(t, websocket.Broadcast, 1)+ a.ClearPasskeyState()+ replacement := whatsmeow.NewClient(newTestStoreDevice(container, ad, ""), nil)+ manager.mu.Lock()+ manager.attachClientLocked(a, replacement)+ manager.mu.Unlock()+ dispatch(&events.PairPasskeyConfirmation{Code: "obsolete"})+ _, code, _ = a.PasskeyState()+ require.Empty(t, code)+ require.Len(t, websocket.Broadcast, 1)+ b.SetClient(replacement)+ manager.eventHandler(replacement)(&events.PairPasskeyConfirmation{Code: "ambiguous"})+ require.Len(t, websocket.Broadcast, 1)+}++func TestClientEventsEnsureDefaultTransferAndSameID(t *testing.T) {+ eventTestBroadcast(t)+ container := newTestSQLStore(t)+ manager := NewDeviceManager(container, nil, nil)+ ad := types.NewADJID("6281777000097", types.WhatsAppDomain, 28)+ client := whatsmeow.NewClient(newTestStoreDevice(container, ad, ""), nil)+ destination := NewDeviceInstance("named", nil, nil)+ manager.applyStoreJID(destination, ad)+ manager.AddDevice(destination)+ source := NewDeviceInstance(ad.String(), client, nil)+ manager.EnsureDefault(source)+ require.Same(t, destination, manager.eventOwner(client))+ require.Nil(t, source.GetClient())+ manager.eventHandler(client)(&events.PairPasskeyConfirmation{Code: "transferred"})+ require.Equal(t, "named", (<-websocket.Broadcast).Result.(map[string]any)["device_id"])+ discarded := whatsmeow.NewClient(newTestStoreDevice(container, ad, ""), nil)+ manager.EnsureDefault(NewDeviceInstance("named", discarded, nil))+ require.Nil(t, manager.eventOwner(discarded))+ require.Same(t, destination, manager.eventOwner(client))+ destination.TriggerLoggedOut()+ require.Nil(t, destination.GetClient())+ require.Empty(t, destination.JID())+}++func TestClientEventsUnpairedNamedSlot(t *testing.T) {+ eventTestBroadcast(t)+ container := newTestSQLStore(t)+ manager := NewDeviceManager(container, nil, nil)+ oldOS, oldPlatform := store.DeviceProps.Os, store.DeviceProps.PlatformType+ t.Cleanup(func() { store.DeviceProps.Os, store.DeviceProps.PlatformType = oldOS, oldPlatform })+ ctx, cancel := context.WithCancel(context.Background())+ instance, err := manager.EnsureClient(ctx, "unpaired")+ require.NoError(t, err)+ cancel()+ client := instance.GetClient()+ require.Nil(t, client.Store.ID)+ manager.eventHandler(client)(&events.PairPasskeyConfirmation{Code: "paired"})+ require.Equal(t, "unpaired", (<-websocket.Broadcast).Result.(map[string]any)["device_id"])+ require.Same(t, instance, manager.eventOwner(client))+}++func TestClientEventsTransientStartupAndRetirement(t *testing.T) {+ eventTestBroadcast(t)+ container := newTestSQLStore(t)+ storage := &keepSlotStubStorage{}+ globalStateMu.Lock()+ oldManager, oldClient, oldDB, oldKeys := deviceManager, cli, db, keysDB+ deviceManager = nil+ globalStateMu.Unlock()+ oldOS, oldPlatform := store.DeviceProps.Os, store.DeviceProps.PlatformType+ t.Cleanup(func() {+ store.DeviceProps.Os, store.DeviceProps.PlatformType = oldOS, oldPlatform+ globalStateMu.Lock()+ deviceManager, cli, db, keysDB = oldManager, oldClient, oldDB, oldKeys+ globalStateMu.Unlock()+ })+ client := InitWaCLI(context.Background(), container, nil, storage)+ manager := GetDeviceManager()+ require.Empty(t, manager.ListDevices())+ require.Nil(t, manager.DefaultDevice())+ owner := manager.eventOwner(client)+ require.NotNil(t, owner)+ manager.eventHandler(client)(&events.PairPasskeyConfirmation{Code: "anonymous"})+ require.Len(t, websocket.Broadcast, 1)+ ad := types.NewADJID("6281777000096", types.WhatsAppDomain, 28)+ client.Store.ID = &ad+ manager.eventHandler(client)(&events.Connected{})+ require.Empty(t, storage.savedRecords)+ require.Empty(t, manager.ListDevices())+ named := NewDeviceInstance("named", client, nil)+ manager.EnsureDefault(named)+ require.Nil(t, manager.transient)+ require.Nil(t, owner.GetClient())+ require.Same(t, named, manager.eventOwner(client))+ manager.eventHandler(client)(&events.PairPasskeyConfirmation{Code: "named"})+ require.Len(t, websocket.Broadcast, 2)+ require.Len(t, manager.ListDevices(), 1)+}++func TestClientEventsRegistryPublicationHasNoOwnershipGap(t *testing.T) {+ container := newTestSQLStore(t)+ manager := NewDeviceManager(container, nil, nil)+ ad := types.NewADJID("6281777000095", types.WhatsAppDomain, 28)+ client := whatsmeow.NewClient(newTestStoreDevice(container, ad, ""), nil)+ manager.EnsureDefault(NewDeviceInstance(ad.String(), client, nil))+ done := make(chan struct{})+ missing := make(chan bool, 1)+ go func() {+ for {+ select {+ case <-done:+ missing <- false+ return+ default:+ if manager.eventOwner(client) == nil {+ missing <- true+ return+ }+ }+ }+ }()+ for i := 0; i < 100; i++ {+ manager.loadFromRegistry([]*domainChatStorage.DeviceRecord{{DeviceID: "named", JID: ad.ToNonAD().String(), ADJID: ad.String()}})+ }+ close(done)+ require.False(t, <-missing)+ require.Equal(t, "named", manager.eventOwner(client).ID())+}++func TestClientEventsTransientRegistryAdoptionAndLogout(t *testing.T) {+ eventTestBroadcast(t)+ container := newTestSQLStore(t)+ manager := NewDeviceManager(container, nil, nil)+ client := whatsmeow.NewClient(container.NewDevice(), nil)+ transient := NewDeviceInstance("", client, nil)+ manager.EnsureDefault(transient)+ ad := types.NewADJID("6281777000094", types.WhatsAppDomain, 28)+ client.Store.ID = &ad+ manager.eventHandler(client)(&events.PairPasskeyConfirmation{Code: "pairing"})+ manager.loadFromRegistry([]*domainChatStorage.DeviceRecord{{DeviceID: "named", JID: ad.ToNonAD().String(), ADJID: ad.String()}})+ require.Nil(t, manager.transient)+ require.Nil(t, transient.GetClient())+ require.Equal(t, "named", manager.eventOwner(client).ID())+ manager.eventOwner(client).TriggerLoggedOut()+ require.Nil(t, manager.eventOwner(client))++ fresh := whatsmeow.NewClient(container.NewDevice(), nil)+ manager.EnsureDefault(NewDeviceInstance("", fresh, nil))+ manager.eventHandler(fresh)(&events.LoggedOut{})+ require.Nil(t, manager.transient)+ require.Nil(t, manager.eventOwner(fresh))+ require.Len(t, manager.ListDevices(), 1)+}diff --git a/src/infrastructure/whatsapp/device_manager.go b/src/infrastructure/whatsapp/device_manager.goindex 29b0c27b..0376cb85 100644--- a/src/infrastructure/whatsapp/device_manager.go+++ b/src/infrastructure/whatsapp/device_manager.go@@ -26,13 +26,14 @@ import (// DeviceManager keeps a registry of active device instances.type DeviceManager struct {- mu sync.RWMutex- devices map[string]*DeviceInstance- store *sqlstore.Container- keys *sqlstore.Container- storage domainChatStorage.IChatStorageRepository- initted bool- initOnce sync.Once+ mu sync.RWMutex+ devices map[string]*DeviceInstance+ transient *DeviceInstance+ store *sqlstore.Container+ keys *sqlstore.Container+ storage domainChatStorage.IChatStorageRepository+ initted bool+ initOnce sync.Once}func NewDeviceManager(store *sqlstore.Container, keys *sqlstore.Container, chatStorageRepo domainChatStorage.IChatStorageRepository) *DeviceManager {@@ -51,6 +52,7 @@ func (m *DeviceManager) AddDevice(instance *DeviceInstance) {m.mu.Lock()defer m.mu.Unlock()+ m.attachClientLocked(instance, instance.GetClient())m.devices[instance.ID()] = instance// Persist registry entry if available@@ -738,76 +740,71 @@ func (m *DeviceManager) loadFromRegistry(records []*domainChatStorage.DeviceRecoseenIdentities[identity] = true}- // Check if a device with this identity already exists in memory (from InitWaCLI)- m.mu.RLock()- var existingByJID *DeviceInstance- for id, inst := range m.devices {- if id != rec.DeviceID && slotIdentityMatches(inst, rec.JID, rec.ADJID) {- existingByJID = inst- break- }- }- m.mu.RUnlock()-- // If device with matching identity exists, remove it and use the registry device- if existingByJID != nil {- m.mu.Lock()- delete(m.devices, existingByJID.ID())- m.mu.Unlock()- logrus.Infof("[DEVICE_MANAGER] replacing in-memory device %s with registry device %s", existingByJID.ID(), rec.DeviceID)- }-- // Create device instancestorageDeviceID := rec.DeviceIDif rec.JID != "" {storageDeviceID = rec.JID}instance := NewDeviceInstance(rec.DeviceID, nil, newDeviceChatStorage(storageDeviceID, m.storage))- instance.SetState(domainDevice.DeviceStateDisconnected)instance.displayName = rec.DisplayNameinstance.jid = rec.JIDinstance.adJID = rec.ADJID- // If we had an existing device with client, transfer the client- if existingByJID != nil {- if client := existingByJID.GetClient(); client != nil {- instance.SetClient(client)- instance.UpdateStateFromClient()+ // Publish the destination and retire the source under one registry lock.+ m.mu.Lock()+ existing := m.devices[rec.DeviceID]+ if existing == nil {+ for id, inst := range m.devices {+ if slotIdentityMatches(inst, rec.JID, rec.ADJID) {+ existing = inst+ delete(m.devices, id)+ break+ }}}-- m.AddDevice(instance)+ if existing == nil && slotIdentityMatches(m.transient, rec.JID, rec.ADJID) {+ existing = m.transient+ }+ if existing != nil {+ m.attachClientLocked(instance, existing.GetClient())+ existing.ResetClient()+ } else {+ m.attachClientLocked(instance, nil)+ }+ m.devices[rec.DeviceID] = instance+ m.mu.Unlock()+ m.persistInstanceRecord(instance)}}// EnsureDefault registers the current global client as the default device if present.// It checks both by device ID and by JID to avoid creating duplicates.-func (m *DeviceManager) EnsureDefault(client *DeviceInstance) {- if client == nil || client.ID() == "" {+func (m *DeviceManager) EnsureDefault(instance *DeviceInstance) {+ if instance == nil {return}-m.mu.Lock()defer m.mu.Unlock()- // Check if device exists by ID- if _, ok := m.devices[client.ID()]; ok {+ if instance.ID() == "" {+ m.transient = instance+ m.attachClientLocked(instance, instance.GetClient())return}-- // Check if any existing device refers to the same companion session- clientJID := client.JID()- if clientJID != "" {- for _, inst := range m.devices {- if slotIdentityMatches(inst, clientJID, client.ADJID()) {- // Update existing device with the new client- inst.SetClient(client.GetClient())+ if current, ok := m.devices[instance.ID()]; ok {+ m.attachClientLocked(current, current.GetClient())+ return+ }+ if jid := instance.JID(); jid != "" {+ for _, current := range m.devices {+ if slotIdentityMatches(current, jid, instance.ADJID()) {+ m.attachClientLocked(current, instance.GetClient())+ instance.ResetClient()return}}}-- m.devices[client.ID()] = client+ m.attachClientLocked(instance, instance.GetClient())+ m.devices[instance.ID()] = instance}// EnsureClient returns a device instance with an initialized WhatsApp client.@@ -857,27 +854,10 @@ func (m *DeviceManager) EnsureClient(ctx context.Context, deviceID string) (*Devinst.SetChatStorage(repo)}- // Events outlive ctx, which is usually a login request's context and is- // cancelled once that request responds.- client.AddEventHandler(func(rawEvt any) {- // A client replaced by a newer login must no longer drive the slot.- if inst.GetClient() != client {- return- }- handler(context.Background(), inst, rawEvt)- })-- inst.SetOnLoggedOut(func(deviceID string) {- // On remote logout (device unlinked from the phone) keep the slot so it can- // be re-paired under the same id, matching the explicit logout semantics.- // Use a fresh context: the original request ctx may already be cancelled.- if err := m.keepSlotLogout(context.Background(), deviceID); err != nil {- logrus.WithError(err).Warnf("[REMOTE_LOGOUT] keep-slot cleanup failed for %s", deviceID)- }- })-- inst.SetClient(client)- inst.UpdateStateFromClient()+ client.AddEventHandler(m.eventHandler(client))+ m.mu.Lock()+ m.attachClientLocked(inst, client)+ m.mu.Unlock()return inst, nil}diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.goindex c026254c..3fca7fd3 100644--- a/src/infrastructure/whatsapp/event_handler.go+++ b/src/infrastructure/whatsapp/event_handler.go@@ -278,7 +278,7 @@ func handleConnectionEvents(_ context.Context, client *whatsmeow.Client, instanc// Persist updated JID/DisplayName to database after successful connection// Skip if instance.ID looks like a JID (auto-created device) to avoid recreating deleted duplicates- if repo := instance.GetChatStorage(); repo != nil && !strings.Contains(instance.ID(), "@") {+ if repo := instance.GetChatStorage(); repo != nil && instance.ID() != "" && !strings.Contains(instance.ID(), "@") {jid := instance.JID()displayName := instance.DisplayName()if jid != "" {diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.goindex 7ee710fd..fcf52c9f 100644--- a/src/infrastructure/whatsapp/init.go+++ b/src/infrastructure/whatsapp/init.go@@ -11,7 +11,6 @@ import ("github.com/aldinokemal/go-whatsapp-web-multidevice/config"domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"- "github.com/sirupsen/logrus""go.mau.fi/whatsmeow""go.mau.fi/whatsmeow/store""go.mau.fi/whatsmeow/store/sqlstore"@@ -126,26 +125,9 @@ func InitWaCLI(ctx context.Context, storeContainer, keysStoreContainer *sqlstoredeviceRepo := newDeviceChatStorage(instanceID, chatStorageRepo)instance := NewDeviceInstance(instanceID, client, deviceRepo)- client.AddEventHandler(func(rawEvt any) {- handler(ctx, instance, rawEvt)- })-- // Register device instance in the manager for multi-device awareness- // Use EnsureDefault to avoid creating duplicates when a device with matching JID already exists- if device.ID != nil {- instanceID = device.ID.String()- }dm := InitializeDeviceManager(storeContainer, keysStoreContainer, deviceRepo)- if dm != nil && instanceID != "" {- dm.EnsureDefault(instance)- instance.SetOnLoggedOut(func(deviceID string) {- // Route the startup path through the same keep-slot cleanup as the lazy- // EnsureClient path, so a remote logout never deletes the device slot.- if err := dm.keepSlotLogout(context.Background(), deviceID); err != nil {- logrus.WithError(err).Warnf("[REMOTE_LOGOUT] keep-slot cleanup failed for %s", deviceID)- }- })- }+ dm.EnsureDefault(instance)+ client.AddEventHandler(dm.eventHandler(client))globalStateMu.Lock()cli = client