Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

fix(chatwoot): serialize lazy inbox identifier resolution (#907)

gobeyondpty1a880fcc8e4b
diff --git a/src/infrastructure/chatwoot/client.go b/src/infrastructure/chatwoot/client.go
index fba94bb0..3b2b82b2 100644
--- a/src/infrastructure/chatwoot/client.go
+++ b/src/infrastructure/chatwoot/client.go
@@ -35,9 +35,65 @@ type Client struct {
// endpoints (e.g. update_last_seen). It is immutable for a given inbox, so
// it is resolved once (at provisioning or on first use) and cached here to
// avoid a full inbox-list GET on every read receipt.
+ //
+ // It may be assigned directly only before the client is shared between
+ // goroutines. Read receipts are forwarded concurrently, so afterwards it
+ // is read and written through resolveInboxIdentifier and
+ // setInboxIdentifier, which serialise on inboxIdentifierLock.
InboxIdentifier string
}
+// inboxIdentifierKey names one inbox of one Chatwoot installation.
+type inboxIdentifierKey struct {
+ BaseURL string
+ AccountID int
+ InboxID int
+}
+
+// inboxIdentifierLocks holds one mutex per inbox (inboxIdentifierKey ->
+// *sync.Mutex). The lock lives here rather than in Client so that Client
+// stays an ordinary copyable struct; it is bounded by the number of inboxes.
+var inboxIdentifierLocks sync.Map
+
+func (c *Client) inboxIdentifierLock() *sync.Mutex {
+ key := inboxIdentifierKey{BaseURL: c.BaseURL, AccountID: c.AccountID, InboxID: c.InboxID}
+ lock, _ := inboxIdentifierLocks.LoadOrStore(key, &sync.Mutex{})
+ return lock.(*sync.Mutex)
+}
+
+// setInboxIdentifier records an inbox identifier learned outside the lazy
+// lookup (inbox provisioning).
+func (c *Client) setInboxIdentifier(identifier string) {
+ lock := c.inboxIdentifierLock()
+ lock.Lock()
+ defer lock.Unlock()
+ c.InboxIdentifier = identifier
+}
+
+// resolveInboxIdentifier returns the inbox identifier, looking it up from the
+// inbox list the first time. The lock is held across the lookup so concurrent
+// first callers wait for one request instead of each sending their own; a
+// failed lookup is not remembered, so the next caller tries again.
+func (c *Client) resolveInboxIdentifier() (string, error) {
+ lock := c.inboxIdentifierLock()
+ lock.Lock()
+ defer lock.Unlock()
+ if c.InboxIdentifier != "" {
+ return c.InboxIdentifier, nil
+ }
+ inboxes, err := c.ListInboxes()
+ if err != nil {
+ return "", err
+ }
+ for _, inbox := range inboxes {
+ if inbox.ID == c.InboxID && inbox.InboxIdentifier != "" {
+ c.InboxIdentifier = inbox.InboxIdentifier
+ return c.InboxIdentifier, nil
+ }
+ }
+ return "", fmt.Errorf("chatwoot inbox %d has no inbox_identifier", c.InboxID)
+}
+
// HTTPStatusError is returned by every Client method that hits Chatwoot's
// REST API when the response status is outside 2xx. It carries the HTTP
// status code so callers (notably retrySyncOp in sync.go) can decide
@@ -777,22 +833,9 @@ func (c *Client) UpdateLastSeen(conversationID int, contactInboxSourceID string)
// inbox_identifier is immutable, so resolve it once and reuse the cached
// value — read sync fires this per receipt and a full inbox-list GET each
// time is pure overhead.
- inboxIdentifier := c.InboxIdentifier
- if inboxIdentifier == "" {
- inboxes, err := c.ListInboxes()
- if err != nil {
- return err
- }
- for _, inbox := range inboxes {
- if inbox.ID == c.InboxID {
- inboxIdentifier = inbox.InboxIdentifier
- break
- }
- }
- if inboxIdentifier == "" {
- return fmt.Errorf("chatwoot inbox %d has no inbox_identifier", c.InboxID)
- }
- c.InboxIdentifier = inboxIdentifier
+ inboxIdentifier, err := c.resolveInboxIdentifier()
+ if err != nil {
+ return err
}
endpoint := fmt.Sprintf(
diff --git a/src/infrastructure/chatwoot/client_inbox_identifier_test.go b/src/infrastructure/chatwoot/client_inbox_identifier_test.go
new file mode 100644
index 00000000..9b69b15f
--- /dev/null
+++ b/src/infrastructure/chatwoot/client_inbox_identifier_test.go
@@ -0,0 +1,97 @@
+package chatwoot
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+)
+
+// Read receipts are forwarded from concurrent goroutines, and each one calls
+// UpdateLastSeen on the shared client. The first calls race to resolve the
+// inbox identifier: run with -race, this test fails if that resolution is not
+// synchronised, and without -race it still requires a single inbox lookup.
+func TestUpdateLastSeen_ConcurrentCallsResolveInboxIdentifierOnce(t *testing.T) {
+ var listCalls, updateCalls atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.URL.Path == "/api/v1/accounts/1/inboxes":
+ listCalls.Add(1)
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Inbox{{ID: 2, Name: "WhatsApp", InboxIdentifier: "api-inbox-token"}},
+ })
+ case strings.HasPrefix(r.URL.Path, "/public/api/v1/inboxes/api-inbox-token/"):
+ updateCalls.Add(1)
+ w.WriteHeader(http.StatusOK)
+ default:
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.String())
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+
+ const callers = 32
+ var wg sync.WaitGroup
+ start := make(chan struct{})
+ errs := make(chan error, callers)
+ for i := 0; i < callers; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ errs <- c.UpdateLastSeen(5, "[email protected]")
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ if err != nil {
+ t.Errorf("UpdateLastSeen: %v", err)
+ }
+ }
+
+ if got := listCalls.Load(); got != 1 {
+ t.Errorf("inbox list lookups = %d, want exactly 1", got)
+ }
+ if got := updateCalls.Load(); got != callers {
+ t.Errorf("update_last_seen calls = %d, want %d", got, callers)
+ }
+}
+
+// A failed lookup must not be remembered: the next receipt tries again.
+func TestUpdateLastSeen_FailedInboxLookupIsRetried(t *testing.T) {
+ var listCalls atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/v1/accounts/1/inboxes" {
+ if listCalls.Add(1) == 1 {
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Inbox{{ID: 2, Name: "WhatsApp", InboxIdentifier: "api-inbox-token"}},
+ })
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ if err := c.UpdateLastSeen(5, "[email protected]"); err == nil {
+ t.Fatal("first UpdateLastSeen succeeded although the inbox lookup failed")
+ }
+ if err := c.UpdateLastSeen(5, "[email protected]"); err != nil {
+ t.Fatalf("second UpdateLastSeen: %v", err)
+ }
+ if err := c.UpdateLastSeen(5, "[email protected]"); err != nil {
+ t.Fatalf("third UpdateLastSeen: %v", err)
+ }
+ if got := listCalls.Load(); got != 2 {
+ t.Errorf("inbox list lookups = %d, want 2 (one failure, one success, then cached)", got)
+ }
+}
diff --git a/src/infrastructure/chatwoot/provision.go b/src/infrastructure/chatwoot/provision.go
index 0129b976..69bacb50 100644
--- a/src/infrastructure/chatwoot/provision.go
+++ b/src/infrastructure/chatwoot/provision.go
@@ -79,6 +79,6 @@ func applyResolvedInbox(client *Client, inbox Inbox) {
config.ChatwootInboxID = inbox.ID
client.InboxID = inbox.ID
if inbox.InboxIdentifier != "" {
- client.InboxIdentifier = inbox.InboxIdentifier
+ client.setInboxIdentifier(inbox.InboxIdentifier)
}
}