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): stop creating threads when conversation lookup fails (#908)

gobeyondpty77d10e63526e
diff --git a/src/infrastructure/chatwoot/client.go b/src/infrastructure/chatwoot/client.go
index 3b2b82b2..1c2da8e1 100644
--- a/src/infrastructure/chatwoot/client.go
+++ b/src/infrastructure/chatwoot/client.go
@@ -634,11 +634,22 @@ func (c *Client) CreateConversation(contactID int, sourceID string) (*Conversati
// land in. sourceID is the WhatsApp chat JID, forwarded to CreateConversation
// when a fresh thread is opened. The contact's conversation list is fetched
// once and scanned in-process for both the open-conversation and reopen cases.
+// A conversation is created only when that list was read; when it cannot be
+// read the error is returned and nothing is created.
func (c *Client) FindOrCreateConversation(contactID int, sourceID string) (*Conversation, error) {
items, err := c.listContactConversations(contactID)
if err != nil {
- // A list failure is logged and we fall through to creation rather than
- // dropping the message.
+ var statusErr *HTTPStatusError
+ if !errors.As(err, &statusErr) || statusErr.StatusCode != http.StatusNotFound {
+ // Not knowing the contact's conversations is not the same as the
+ // contact having none. Creating one now would open a second thread
+ // next to the customer's open conversation, and every later
+ // message would follow it there. The error is returned instead: a
+ // transient one (network, 429, 5xx) is retried by the caller.
+ return nil, fmt.Errorf("failed to list the conversations of contact %d: %w", contactID, err)
+ }
+ // 404: Chatwoot does not know the contact. Creating the conversation
+ // below fails the same way and reports it.
logrus.Errorf("Error finding conversation: %v", err)
}
diff --git a/src/infrastructure/chatwoot/client_methods_test.go b/src/infrastructure/chatwoot/client_methods_test.go
index c9319f35..a8df64f0 100644
--- a/src/infrastructure/chatwoot/client_methods_test.go
+++ b/src/infrastructure/chatwoot/client_methods_test.go
@@ -11,6 +11,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync/atomic"
"testing"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
@@ -741,16 +742,99 @@ func TestFindOrCreateConversation_CreatesWhenNotFound(t *testing.T) {
}
}
-func TestFindOrCreateConversation_SwallowsFindErrorThenCreates(t *testing.T) {
- // Listing conversations failing is logged but NOT propagated: the method
- // still proceeds to create. This codifies the current swallow-and-create
- // behavior — a find error must not block conversation creation.
+// TestFindOrCreateConversation_ListFailureCreatesNothing: when the contact's
+// conversations cannot be read, no conversation is created. The contact may
+// well have an open one, and a new thread would split the customer's
+// messages over two conversations. The error keeps its status, so a transient
+// failure is retried by the caller and the message lands in the right thread
+// once the list can be read again.
+func TestFindOrCreateConversation_ListFailureCreatesNothing(t *testing.T) {
+ for name, tc := range map[string]struct {
+ status int
+ retryable bool
+ }{
+ "server error": {http.StatusInternalServerError, true},
+ "bad gateway": {http.StatusBadGateway, true},
+ "too many requests": {http.StatusTooManyRequests, true},
+ "unauthorized": {http.StatusUnauthorized, false},
+ } {
+ t.Run(name, func(t *testing.T) {
+ var creates atomic.Int32
+ listFails := atomic.Bool{}
+ listFails.Store(true)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && listFails.Load():
+ writeJSON(t, w, tc.status, map[string]any{"error": "find failed"})
+ case r.Method == http.MethodGet:
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": []map[string]any{{"id": 20, "inbox_id": 2, "status": "open"}}})
+ case r.Method == http.MethodPost:
+ creates.Add(1)
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": map[string]any{"id": 800}})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindOrCreateConversation(7, "")
+ if err == nil {
+ t.Fatalf("FindOrCreateConversation returned conversation %+v for an unreadable conversation list", conv)
+ }
+ if creates.Load() != 0 {
+ t.Fatalf("%d conversation(s) were created although the contact's conversations could not be read", creates.Load())
+ }
+ var statusErr *HTTPStatusError
+ if !errors.As(err, &statusErr) || statusErr.StatusCode != tc.status {
+ t.Fatalf("error = %v, want it to carry status %d", err, tc.status)
+ }
+ if Retryable(err) != tc.retryable {
+ t.Fatalf("Retryable(%v) = %v, want %v", err, Retryable(err), tc.retryable)
+ }
+
+ // The retry, once Chatwoot answers again, finds the open
+ // conversation and still creates nothing.
+ listFails.Store(false)
+ conv, err = c.FindOrCreateConversation(7, "")
+ if err != nil || conv == nil || conv.ID != 20 {
+ t.Fatalf("retry = %+v, %v; want the existing conversation 20", conv, err)
+ }
+ if creates.Load() != 0 {
+ t.Fatalf("%d conversation(s) were created on the retry", creates.Load())
+ }
+ })
+ }
+}
+
+// TestFindOrCreateConversation_NetworkFailureCreatesNothing: the same for a
+// failure without a status (connection refused, timeout).
+func TestFindOrCreateConversation_NetworkFailureCreatesNothing(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
+ c := newTestClient(t, server.URL)
+ server.Close()
+
+ conv, err := c.FindOrCreateConversation(7, "")
+ if err == nil || conv != nil {
+ t.Fatalf("FindOrCreateConversation = %+v, %v; want an error and no conversation", conv, err)
+ }
+ if !Retryable(err) {
+ t.Fatalf("a network failure must stay retryable, got %v", err)
+ }
+}
+
+// TestFindOrCreateConversation_UnknownContactStillReportsTheCreateError: a 404
+// for the list means Chatwoot does not know the contact. The create is still
+// attempted and its own answer is what the caller gets, as before.
+func TestFindOrCreateConversation_UnknownContactStillReportsTheCreateError(t *testing.T) {
+ var creates atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch {
- case r.Method == http.MethodGet:
- writeJSON(t, w, http.StatusInternalServerError, map[string]any{"error": "find failed"})
- case r.Method == http.MethodPost:
- writeJSON(t, w, http.StatusOK, map[string]any{"payload": map[string]any{"id": 800}})
+ switch r.Method {
+ case http.MethodGet:
+ writeJSON(t, w, http.StatusNotFound, map[string]any{"error": "Resource could not be found"})
+ case http.MethodPost:
+ creates.Add(1)
+ writeJSON(t, w, http.StatusNotFound, map[string]any{"error": "Resource could not be found"})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
}
@@ -758,12 +842,11 @@ func TestFindOrCreateConversation_SwallowsFindErrorThenCreates(t *testing.T) {
defer server.Close()
c := newTestClient(t, server.URL)
- conv, err := c.FindOrCreateConversation(7, "")
- if err != nil {
- t.Fatalf("FindOrCreateConversation should swallow find error, got: %v", err)
+ if _, err := c.FindOrCreateConversation(7, ""); err == nil {
+ t.Fatal("expected the create error for a contact Chatwoot does not know")
}
- if conv.ID != 800 {
- t.Fatalf("conv.ID = %d, want 800 (created after find error)", conv.ID)
+ if creates.Load() != 1 {
+ t.Fatalf("creates = %d, want the one attempt", creates.Load())
}
}