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): isolate cached group names by account (#910)
gobeyondptyfa9189698106
diff --git a/src/infrastructure/whatsapp/chatwoot_content_test.go b/src/infrastructure/whatsapp/chatwoot_content_test.goindex 6ee7183a..ad536bea 100644--- a/src/infrastructure/whatsapp/chatwoot_content_test.go+++ b/src/infrastructure/whatsapp/chatwoot_content_test.go@@ -138,11 +138,6 @@ func TestExtractChatwootContactInfo(t *testing.T) {// messages collapse into one conversation). With no client in context// getGroupName returns "", so Name falls back to "Group: <extracted phone>".groupJID := "[email protected]"- // Seed the cache with an empty name so the fallback is deterministic even- // if another test in this package has set a global WhatsApp client. A- // cached "" still flows to the "Group: <phone>" fallback. This is a fresh- // entry (TTL in the future), so no timing dependency is introduced.- setCachedGroupName(groupJID, "")info, err := extractChatwootContactInfo(ctx, map[string]any{"from": "[email protected]","chat_id": groupJID,@@ -170,7 +165,6 @@ func TestExtractChatwootContactInfo(t *testing.T) {t.Run("group fallback prefix even when from_name empty", func(t *testing.T) {groupJID := "[email protected]"- setCachedGroupName(groupJID, "")info, err := extractChatwootContactInfo(ctx, map[string]any{"from": "[email protected]","chat_id": groupJID,@@ -1003,19 +997,20 @@ func TestIsEventWhitelisted(t *testing.T) {// expiry timing. setCachedGroupName stores with a future TTL, so a subsequent load// returns (name, true); an unknown key returns ("", false).func TestGroupNameCache(t *testing.T) {+ const groupNameCacheTestDevice = "[email protected]"t.Run("store then load returns cached name", func(t *testing.T) {// Use a JID unlikely to collide with other tests so a leftover entry from a// prior run can't mask a regression.jid := "[email protected]"- setCachedGroupName(jid, "My Group")- name, ok := getCachedGroupName(jid)+ setCachedGroupName(groupNameCacheTestDevice, jid, "My Group")+ name, ok := getCachedGroupName(groupNameCacheTestDevice, jid)if !ok || name != "My Group" {t.Fatalf("expected ('My Group', true), got (%q, %v)", name, ok)}})t.Run("unknown key returns empty and false", func(t *testing.T) {- name, ok := getCachedGroupName("[email protected]")+ name, ok := getCachedGroupName(groupNameCacheTestDevice, "[email protected]")if ok || name != "" {t.Fatalf("expected ('', false) for unknown key, got (%q, %v)", name, ok)}@@ -1025,8 +1020,8 @@ func TestGroupNameCache(t *testing.T) {// Storing an empty name is meaningful (it records "we tried and got nothing")// — load must still return ok=true so callers don't re-fetch.jid := "[email protected]"- setCachedGroupName(jid, "")- name, ok := getCachedGroupName(jid)+ setCachedGroupName(groupNameCacheTestDevice, jid, "")+ name, ok := getCachedGroupName(groupNameCacheTestDevice, jid)if !ok || name != "" {t.Fatalf("expected ('', true) for empty cached name, got (%q, %v)", name, ok)}diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.goindex aec82987..ff9cef03 100644--- a/src/infrastructure/whatsapp/event_handler.go+++ b/src/infrastructure/whatsapp/event_handler.go@@ -403,6 +403,11 @@ func handleGroupInfo(ctx context.Context, evt *events.GroupInfo, deviceID stringreturn}+ // A new subject makes this device's cached group name stale.+ if evt.Name != nil {+ invalidateCachedGroupName(groupNameCacheDeviceID(client), evt.JID.ToNonAD().String())+ }+// Log group events for debuggingif len(evt.Join) > 0 {log.Infof("Group %s: %d users joined at %s", evt.JID, len(evt.Join), evt.Timestamp)diff --git a/src/infrastructure/whatsapp/group_name_cache_test.go b/src/infrastructure/whatsapp/group_name_cache_test.gonew file mode 100644index 00000000..3f198294--- /dev/null+++ b/src/infrastructure/whatsapp/group_name_cache_test.go@@ -0,0 +1,198 @@+package whatsapp++import (+ "context"+ "errors"+ "testing"+ "time"++ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/store"+ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+ waLog "go.mau.fi/whatsmeow/util/log"+)++func TestGroupNameLookupNeverFallsBackToTheGlobalAccount(t *testing.T) {+ const group = "[email protected]"+ globalClient, _ := groupNameTestDevice(t, "15550000041")+ globalStateMu.Lock()+ originalClient := cli+ cli = globalClient+ globalStateMu.Unlock()+ originalFetch := fetchGroupInfoFn+ fetchGroupInfoFn = func(context.Context, *whatsmeow.Client, types.JID) (*types.GroupInfo, error) {+ t.Error("unresolved device queried the global account")+ return nil, nil+ }+ deviceID := groupNameCacheDeviceID(globalClient)+ setCachedGroupName(deviceID, group, "Global account's group")+ t.Cleanup(func() {+ globalStateMu.Lock()+ cli = originalClient+ globalStateMu.Unlock()+ fetchGroupInfoFn = originalFetch+ invalidateCachedGroupName(deviceID, group)+ })+ for _, ctx := range []context.Context{+ context.Background(), // Replay when the original device cannot be resolved.+ ContextWithDevice(context.Background(), nil),+ ContextWithDevice(context.Background(), NewDeviceInstance("logged-out", nil, nil)),+ } {+ if got := getGroupName(ctx, group); got != "" {+ t.Fatalf("unresolved device received group name %q", got)+ }+ }+}++func TestGroupNameInvalidationCannotBeUndoneByAnInflightFetch(t *testing.T) {+ const group = "[email protected]"+ client, ctx := groupNameTestDevice(t, "15550000031")+ deviceID := groupNameCacheDeviceID(client)+ original := fetchGroupInfoFn+ calls := 0+ fetchGroupInfoFn = func(_ context.Context, _ *whatsmeow.Client, jid types.JID) (*types.GroupInfo, error) {+ calls+++ name := "Renamed"+ if calls == 1 {+ // A subject-change event arrives after the request started, before the+ // server's older response is returned to the cache writer.+ invalidateCachedGroupName(deviceID, group)+ name = "Old subject"+ }+ return &types.GroupInfo{JID: jid, GroupName: types.GroupName{Name: name}}, nil+ }+ t.Cleanup(func() {+ fetchGroupInfoFn = original+ invalidateCachedGroupName(deviceID, group)+ })+ if got := getGroupName(ctx, group); got != "Old subject" {+ t.Fatalf("in-flight result = %q", got)+ }+ if name, ok := getCachedGroupName(deviceID, group); ok {+ t.Fatalf("in-flight fetch restored invalidated subject %q", name)+ }+ if got := getGroupName(ctx, group); got != "Renamed" || calls != 2 {+ t.Fatalf("next lookup = %q after %d fetches", got, calls)+ }+}++// groupNameTestDevice returns a logged-in client for the given account and a+// context that carries its device, the way an event for that device does.+func groupNameTestDevice(t *testing.T, user string) (*whatsmeow.Client, context.Context) {+ t.Helper()+ jid := types.NewJID(user, types.DefaultUserServer)+ client := &whatsmeow.Client{Store: &store.Device{ID: &jid}}+ return client, ContextWithDevice(context.Background(), NewDeviceInstance(user, client, nil))+}++// stubGroupInfo answers group-info lookups per client: a client listed in+// subjects is a member and reads that subject, any other client is refused.+// It returns a counter of lookups per account.+func stubGroupInfo(t *testing.T, subjects map[*whatsmeow.Client]*string) map[string]int {+ t.Helper()+ calls := make(map[string]int)+ original := fetchGroupInfoFn+ fetchGroupInfoFn = func(_ context.Context, client *whatsmeow.Client, jid types.JID) (*types.GroupInfo, error) {+ calls[client.Store.ID.User]+++ subject, ok := subjects[client]+ if !ok {+ return nil, errors.New("not a participant")+ }+ return &types.GroupInfo{JID: jid, GroupName: types.GroupName{Name: *subject}}, nil+ }+ t.Cleanup(func() { fetchGroupInfoFn = original })+ return calls+}++// A device that is not in a group must not be handed the subject another+// device read for it.+func TestGroupNameCacheDoesNotServeAnotherDevice(t *testing.T) {+ const group = "[email protected]"+ clientA, ctxA := groupNameTestDevice(t, "15550000011")+ clientB, ctxB := groupNameTestDevice(t, "15550000012")+ subject := "Members only"+ calls := stubGroupInfo(t, map[*whatsmeow.Client]*string{clientA: &subject})+ t.Cleanup(func() {+ invalidateCachedGroupName(groupNameCacheDeviceID(clientA), group)+ invalidateCachedGroupName(groupNameCacheDeviceID(clientB), group)+ })++ if got := getGroupName(ctxA, group); got != "Members only" {+ t.Fatalf("device A group name = %q, want its own lookup result", got)+ }+ if got := getGroupName(ctxB, group); got != "" {+ t.Fatalf("device B (not a member) group name = %q, want empty", got)+ }+ if calls["15550000012"] != 1 {+ t.Fatalf("device B lookups = %d, want 1 (it must ask for itself)", calls["15550000012"])+ }+ // Device A is still served from its own entry.+ if got := getGroupName(ctxA, group); got != "Members only" || calls["15550000011"] != 1 {+ t.Fatalf("device A second read = %q after %d lookups, want the cached name after 1", got, calls["15550000011"])+ }+}++// Two devices cache independently, and a subject change seen by one device+// drops only that device's entry.+func TestGroupNameCacheIsPerDevice(t *testing.T) {+ const group = "[email protected]"+ clientA, ctxA := groupNameTestDevice(t, "15550000021")+ clientB, ctxB := groupNameTestDevice(t, "15550000022")+ subjectA, subjectB := "Seen by A", "Seen by B"+ calls := stubGroupInfo(t, map[*whatsmeow.Client]*string{clientA: &subjectA, clientB: &subjectB})+ originalLog := log+ log = waLog.Noop+ t.Cleanup(func() {+ log = originalLog+ invalidateCachedGroupName(groupNameCacheDeviceID(clientA), group)+ invalidateCachedGroupName(groupNameCacheDeviceID(clientB), group)+ })++ if got := getGroupName(ctxA, group); got != "Seen by A" {+ t.Fatalf("device A group name = %q", got)+ }+ if got := getGroupName(ctxB, group); got != "Seen by B" {+ t.Fatalf("device B group name = %q, want its own lookup result", got)+ }++ // Device A receives a subject change. No webhook or Chatwoot target is+ // configured, so the event goes no further than the cache.+ subjectA = "Renamed"+ groupJID, err := types.ParseJID(group)+ if err != nil {+ t.Fatalf("parse group JID: %v", err)+ }+ instance, _ := DeviceFromContext(ctxA)+ handler(ctxA, instance, &events.GroupInfo{+ JID: groupJID,+ Name: &types.GroupName{Name: "Renamed"},+ Timestamp: time.Now(),+ })++ if got := getGroupName(ctxA, group); got != "Renamed" {+ t.Fatalf("device A group name after a subject change = %q, want the new subject", got)+ }+ if got := getGroupName(ctxB, group); got != "Seen by B" || calls["15550000022"] != 1 {+ t.Fatalf("device B group name = %q after %d lookups, want its own cached entry untouched", got, calls["15550000022"])+ }+}++// A client that is not logged in has no identity to cache under: it neither+// reads another device's entry nor leaves one behind.+func TestGroupNameCacheSkipsAnUnidentifiedClient(t *testing.T) {+ const group = "[email protected]"+ if got := groupNameCacheDeviceID(nil); got != "" {+ t.Fatalf("nil client cache identity = %q, want empty", got)+ }+ if got := groupNameCacheDeviceID(&whatsmeow.Client{Store: &store.Device{}}); got != "" {+ t.Fatalf("logged-out client cache identity = %q, want empty", got)+ }+ setCachedGroupName("", group, "Leaked")+ if name, ok := getCachedGroupName("", group); ok {+ t.Fatalf("empty device read %q from the cache", name)+ }+ if _, ok := groupNameCache.Load(groupNameCacheKey{groupJID: group}); ok {+ t.Fatal("an entry was stored without a device")+ }+}diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.goindex def1b888..54c4731d 100644--- a/src/infrastructure/whatsapp/webhook_forward.go+++ b/src/infrastructure/whatsapp/webhook_forward.go@@ -15,6 +15,7 @@ import ("github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils""github.com/sirupsen/logrus"+ "go.mau.fi/whatsmeow""go.mau.fi/whatsmeow/types")@@ -52,40 +53,102 @@ const mutexShardCount = 64// This approach prevents memory leaks that would occur with a sync.Map that grows indefinitely.var contactMutexShards [mutexShardCount]sync.Mutex+// groupNameCacheKey identifies a cached group name. A subject belongs to the+// account that read it: another account may not be in the group at all, so a+// name is never shared between devices.+type groupNameCacheKey struct {+ deviceID string+ groupJID string+}+// groupNameCacheEntry holds cached group name with expiration timetype groupNameCacheEntry struct {- name string- expiresAt time.Time+ name string+ expiresAt time.Time+ fetchToken *int}var (// groupNameCache provides TTL-based caching for group names to reduce WhatsApp API callsgroupNameCache sync.MapgroupNameCacheTTL = 5 * time.Minute++ // fetchGroupInfoFn asks WhatsApp for a group's info as the given client. It+ // is a seam so tests can answer per device without a live connection.+ fetchGroupInfoFn = func(ctx context.Context, client *whatsmeow.Client, jid types.JID) (*types.GroupInfo, error) {+ return client.GetGroupInfo(ctx, jid)+ })-// getCachedGroupName retrieves group name from cache if not expired.-// Returns empty string and false if not cached or expired.-func getCachedGroupName(groupJID string) (string, bool) {- if entry, ok := groupNameCache.Load(groupJID); ok {+// groupNameCacheDeviceID returns the identity a client's group names are cached+// under: its own account JID, the same identity chat storage files rows under.+// A client that is not logged in has none and never uses the cache.+func groupNameCacheDeviceID(client *whatsmeow.Client) string {+ if client == nil || client.Store == nil || client.Store.ID == nil {+ return ""+ }+ return client.Store.ID.ToNonAD().String()+}++// getCachedGroupName retrieves the name one device cached for a group, if not+// expired. Returns empty string and false if not cached or expired.+func getCachedGroupName(deviceID, groupJID string) (string, bool) {+ if deviceID == "" {+ return "", false+ }+ key := groupNameCacheKey{deviceID: deviceID, groupJID: groupJID}+ if entry, ok := groupNameCache.Load(key); ok {cached := entry.(groupNameCacheEntry)if time.Now().Before(cached.expiresAt) {return cached.name, true}// Entry expired, delete it- groupNameCache.Delete(groupJID)+ groupNameCache.Delete(key)}return "", false}-// setCachedGroupName stores group name in cache with TTL.-func setCachedGroupName(groupJID, name string) {- groupNameCache.Store(groupJID, groupNameCacheEntry{+// setCachedGroupName stores a group name for one device with TTL.+func setCachedGroupName(deviceID, groupJID, name string) {+ if deviceID == "" {+ return+ }+ groupNameCache.Store(groupNameCacheKey{deviceID: deviceID, groupJID: groupJID}, groupNameCacheEntry{name: name,expiresAt: time.Now().Add(groupNameCacheTTL),})}+// invalidateCachedGroupName drops the name one device cached for a group, so+// the next lookup by that device reads the current subject.+func invalidateCachedGroupName(deviceID, groupJID string) {+ if deviceID == "" {+ return+ }+ groupNameCache.Delete(groupNameCacheKey{deviceID: deviceID, groupJID: groupJID})+}++// beginGroupNameCacheFetch reserves a unique cache value before the network+// read. Deleting or replacing that value prevents an older fetch from caching+// a name after a subject-change event invalidated it.+func beginGroupNameCacheFetch(deviceID, groupJID string) func(string) {+ if deviceID == "" {+ return func(string) {}+ }+ key := groupNameCacheKey{deviceID: deviceID, groupJID: groupJID}+ pending := groupNameCacheEntry{fetchToken: new(int)}+ groupNameCache.Store(key, pending)+ return func(name string) {+ if name == "" {+ groupNameCache.CompareAndDelete(key, pending)+ return+ }+ groupNameCache.CompareAndSwap(key, pending, groupNameCacheEntry{+ name: name, expiresAt: time.Now().Add(groupNameCacheTTL),+ })+ }+}+// getContactMutex returns a mutex for the given phone number to serialize contact operations.// Uses FNV-1a hash to distribute phones across shards for balanced lock contention.func getContactMutex(phone string) *sync.Mutex {@@ -1347,24 +1410,25 @@ func isEventWhitelisted(eventName string) bool {}// getGroupName fetches the group name from WhatsApp using the group JID.-// Uses a TTL cache to avoid repeated API calls for the same group.+// Uses a per-device TTL cache to avoid repeated API calls for the same group.func getGroupName(ctx context.Context, groupJID string) string {- // Check cache first- if name, ok := getCachedGroupName(groupJID); ok {- logrus.Debugf("Chatwoot: Using cached group name for %s: %s", groupJID, name)- return name- }-- client := ClientFromContext(ctx)- if client == nil {- logrus.Debug("Chatwoot: ClientFromContext returned nil, trying GetClient()")- client = GetClient()+ instance, ok := DeviceFromContext(ctx)+ if !ok || instance == nil {+ return ""}- if client == nil {- logrus.Warn("Chatwoot: No WhatsApp client available to fetch group name")+ client := instance.GetClient()+ if client == nil || groupNameCacheDeviceID(client) == "" {return ""}+ // Check this device's cache first. The name is only ever served to the+ // device that fetched it.+ deviceID := groupNameCacheDeviceID(client)+ if name, ok := getCachedGroupName(deviceID, groupJID); ok {+ logrus.Debugf("Chatwoot: Using cached group name for %s: %s", groupJID, name)+ return name+ }+jid, err := types.ParseJID(groupJID)if err != nil {logrus.Warnf("Chatwoot: Failed to parse group JID %s: %v", groupJID, err)@@ -1375,9 +1439,11 @@ func getGroupName(ctx context.Context, groupJID string) string {// (this function is called from a goroutine)freshCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()+ cacheResult := beginGroupNameCacheFetch(deviceID, groupJID)+ defer cacheResult("")logrus.Debugf("Chatwoot: Fetching group info for %s", groupJID)- groupInfo, err := client.GetGroupInfo(freshCtx, jid)+ groupInfo, err := fetchGroupInfoFn(freshCtx, client, jid)if err != nil {logrus.Warnf("Chatwoot: Failed to get group info for %s: %v", groupJID, err)return ""@@ -1386,7 +1452,7 @@ func getGroupName(ctx context.Context, groupJID string) string {if groupInfo != nil && groupInfo.Name != "" {logrus.Infof("Chatwoot: Got group name: %s", groupInfo.Name)// Cache the result- setCachedGroupName(groupJID, groupInfo.Name)+ cacheResult(groupInfo.Name)return groupInfo.Name}