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: pre-warm and one-shot retry on WhatsApp send error 463 (#695)

Aldino Kemalfccb1451e9c4
diff --git a/src/infrastructure/whatsapp/send_retry.go b/src/infrastructure/whatsapp/send_retry.go
new file mode 100644
index 00000000..d54f6f66
--- /dev/null
+++ b/src/infrastructure/whatsapp/send_retry.go
@@ -0,0 +1,83 @@
+package whatsapp
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "time"
+
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/types"
+)
+
+// reachoutSubscribeTimeout bounds the pre-warm SubscribePresence so an
+// unhealthy socket cannot stall the retry. One round-trip's worth of slack.
+const reachoutSubscribeTimeout = 3 * time.Second
+
+// Seams for unit tests. Mirrors the submitWebhookFn pattern in webhook_forward.go.
+var (
+ sendMessageFn = func(ctx context.Context, client *whatsmeow.Client, recipient types.JID, msg *waE2E.Message) (whatsmeow.SendResponse, error) {
+ return client.SendMessage(ctx, recipient, msg)
+ }
+ subscribePresenceFn = func(ctx context.Context, client *whatsmeow.Client, recipient types.JID) error {
+ return client.SubscribePresence(ctx, recipient)
+ }
+)
+
+// IsReachoutTimelockError reports whether err is WhatsApp server error 463
+// (NackCallerReachoutTimelocked) — surfaced when the recipient's privacy
+// token (tctoken) is missing/expired or the recipient is a cold contact.
+//
+// whatsmeow formats this error as fmt.Errorf("%w %d", ErrServerReturnedError,
+// code) → "server returned error 463". errors.Is gates on the sentinel; the
+// leading-space suffix guards against false matches like "4631".
+func IsReachoutTimelockError(err error) bool {
+ return err != nil &&
+ errors.Is(err, whatsmeow.ErrServerReturnedError) &&
+ strings.HasSuffix(err.Error(), " 463")
+}
+
+// SendMessageWithReachoutRetry sends msg to recipient and, if the send fails
+// with WhatsApp error 463 on a 1:1 user JID, performs a SubscribePresence
+// pre-warm and retries the send exactly once.
+//
+// SubscribePresence is the only step in WA-Web's chat-open sequence that
+// participates in whatsmeow's privacy-token path (it attaches any cached
+// tctoken to the subscribe stanza). The retry itself does the real work:
+// whatsmeow's post-send issuePrivacyTokenAndSave runs on the failed first
+// attempt and lets the second succeed once a token is in place.
+//
+// Group/broadcast/newsletter/legacy-server JIDs skip the retry — 463 does
+// not apply to them.
+func SendMessageWithReachoutRetry(ctx context.Context, client *whatsmeow.Client, recipient types.JID, msg *waE2E.Message) (whatsmeow.SendResponse, error) {
+ resp, err := sendMessageFn(ctx, client, recipient, msg)
+ if err == nil || !IsReachoutTimelockError(err) || !isUserJID(recipient) {
+ return resp, err
+ }
+
+ logrus.Warnf("Send to %s rejected with WhatsApp error 463; subscribing to presence and retrying once", recipient.String())
+
+ // Detached context so an upstream cancel cannot abort the subscribe
+ // mid-flight. Device scoping (via ContextWithDevice) is preserved.
+ warmCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), reachoutSubscribeTimeout)
+ if subscribeErr := subscribePresenceFn(warmCtx, client, recipient); subscribeErr != nil {
+ logrus.Debugf("Pre-warm SubscribePresence for %s failed: %v", recipient.String(), subscribeErr)
+ }
+ cancel()
+
+ resp, err = sendMessageFn(ctx, client, recipient, msg)
+ if err != nil {
+ logrus.Warnf("Retry send to %s after pre-warm still failed: %v", recipient.String(), err)
+ } else {
+ logrus.Infof("Retry send to %s after pre-warm succeeded", recipient.String())
+ }
+ return resp, err
+}
+
+// isUserJID reports whether the JID is a 1:1 user JID (regular or hidden/LID).
+// Error 463 does not apply to group/broadcast/newsletter/legacy-server JIDs.
+func isUserJID(jid types.JID) bool {
+ return jid.Server == types.DefaultUserServer || jid.Server == types.HiddenUserServer
+}
diff --git a/src/infrastructure/whatsapp/send_retry_test.go b/src/infrastructure/whatsapp/send_retry_test.go
new file mode 100644
index 00000000..bbc0e513
--- /dev/null
+++ b/src/infrastructure/whatsapp/send_retry_test.go
@@ -0,0 +1,201 @@
+package whatsapp
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/types"
+)
+
+// reachoutErr mimics the error whatsmeow produces for server error 463:
+// fmt.Errorf("%w %d", ErrServerReturnedError, 463).
+func reachoutErr() error {
+ return errors.Join(whatsmeow.ErrServerReturnedError, errors.New("server returned error 463"))
+}
+
+func nonReachoutServerErr(code string) error {
+ return errors.Join(whatsmeow.ErrServerReturnedError, errors.New("server returned error "+code))
+}
+
+func TestIsReachoutTimelockError(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ want bool
+ }{
+ {"nil", nil, false},
+ {"wrapped 463", reachoutErr(), true},
+ {"wrapped non-463", nonReachoutServerErr("500"), false},
+ {"unrelated error", errors.New("network unreachable"), false},
+ {"bare 463 string without sentinel", errors.New("error 463"), false},
+ {"sentinel but no 463", nonReachoutServerErr("400"), false},
+ {"superstring 4631 must not match", nonReachoutServerErr("4631"), false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := IsReachoutTimelockError(tt.err); got != tt.want {
+ t.Fatalf("IsReachoutTimelockError(%v) = %v, want %v", tt.err, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestSendMessageWithReachoutRetry(t *testing.T) {
+ userJID := types.JID{User: "12345", Server: types.DefaultUserServer}
+ lidJID := types.JID{User: "12345", Server: types.HiddenUserServer}
+ groupJID := types.JID{User: "12345-67890", Server: types.GroupServer}
+
+ type result struct {
+ resp whatsmeow.SendResponse
+ err error
+ }
+
+ tests := []struct {
+ name string
+ recipient types.JID
+ first result
+ second result
+ wantSendCalls int
+ wantSubscribes int
+ wantErrIs error
+ wantRespID string
+ }{
+ {
+ name: "success on first attempt",
+ recipient: userJID,
+ first: result{resp: whatsmeow.SendResponse{ID: "msg-1"}},
+ wantSendCalls: 1,
+ wantSubscribes: 0,
+ wantRespID: "msg-1",
+ },
+ {
+ name: "non-463 error is not retried",
+ recipient: userJID,
+ first: result{err: nonReachoutServerErr("500")},
+ wantSendCalls: 1,
+ wantSubscribes: 0,
+ wantErrIs: whatsmeow.ErrServerReturnedError,
+ },
+ {
+ name: "463 on user JID retries and succeeds",
+ recipient: userJID,
+ first: result{err: reachoutErr()},
+ second: result{resp: whatsmeow.SendResponse{ID: "msg-retry"}},
+ wantSendCalls: 2,
+ wantSubscribes: 1,
+ wantRespID: "msg-retry",
+ },
+ {
+ name: "463 on LID JID retries and succeeds",
+ recipient: lidJID,
+ first: result{err: reachoutErr()},
+ second: result{resp: whatsmeow.SendResponse{ID: "msg-retry-lid"}},
+ wantSendCalls: 2,
+ wantSubscribes: 1,
+ wantRespID: "msg-retry-lid",
+ },
+ {
+ name: "463 on user JID retries and still fails",
+ recipient: userJID,
+ first: result{err: reachoutErr()},
+ second: result{err: reachoutErr()},
+ wantSendCalls: 2,
+ wantSubscribes: 1,
+ wantErrIs: whatsmeow.ErrServerReturnedError,
+ },
+ {
+ name: "463 on group JID is not retried",
+ recipient: groupJID,
+ first: result{err: reachoutErr()},
+ wantSendCalls: 1,
+ wantSubscribes: 0,
+ wantErrIs: whatsmeow.ErrServerReturnedError,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ origSend := sendMessageFn
+ origSub := subscribePresenceFn
+ defer func() {
+ sendMessageFn = origSend
+ subscribePresenceFn = origSub
+ }()
+
+ var sendCalls, subscribes int
+ sendMessageFn = func(_ context.Context, _ *whatsmeow.Client, _ types.JID, _ *waE2E.Message) (whatsmeow.SendResponse, error) {
+ sendCalls++
+ if sendCalls == 1 {
+ return tt.first.resp, tt.first.err
+ }
+ return tt.second.resp, tt.second.err
+ }
+ subscribePresenceFn = func(_ context.Context, _ *whatsmeow.Client, _ types.JID) error {
+ subscribes++
+ return nil
+ }
+
+ resp, err := SendMessageWithReachoutRetry(context.Background(), nil, tt.recipient, &waE2E.Message{})
+
+ if sendCalls != tt.wantSendCalls {
+ t.Errorf("send calls = %d, want %d", sendCalls, tt.wantSendCalls)
+ }
+ if subscribes != tt.wantSubscribes {
+ t.Errorf("subscribe calls = %d, want %d", subscribes, tt.wantSubscribes)
+ }
+ if tt.wantErrIs != nil {
+ if !errors.Is(err, tt.wantErrIs) {
+ t.Errorf("err = %v, want errors.Is(..., %v)", err, tt.wantErrIs)
+ }
+ } else {
+ if err != nil {
+ t.Errorf("err = %v, want nil", err)
+ }
+ if resp.ID != tt.wantRespID {
+ t.Errorf("resp.ID = %q, want %q", resp.ID, tt.wantRespID)
+ }
+ }
+ })
+ }
+}
+
+func TestSendMessageWithReachoutRetry_SubscribeFailureDoesNotAbortRetry(t *testing.T) {
+ origSend := sendMessageFn
+ origSub := subscribePresenceFn
+ defer func() {
+ sendMessageFn = origSend
+ subscribePresenceFn = origSub
+ }()
+
+ var sendCalls int
+ sendMessageFn = func(_ context.Context, _ *whatsmeow.Client, _ types.JID, _ *waE2E.Message) (whatsmeow.SendResponse, error) {
+ sendCalls++
+ if sendCalls == 1 {
+ return whatsmeow.SendResponse{}, reachoutErr()
+ }
+ return whatsmeow.SendResponse{ID: "msg-retry"}, nil
+ }
+ subscribePresenceFn = func(_ context.Context, _ *whatsmeow.Client, _ types.JID) error {
+ return errors.New("subscribe boom")
+ }
+
+ resp, err := SendMessageWithReachoutRetry(
+ context.Background(),
+ nil,
+ types.JID{User: "12345", Server: types.DefaultUserServer},
+ &waE2E.Message{},
+ )
+ if err != nil {
+ t.Fatalf("expected retry to succeed despite subscribe failure, got %v", err)
+ }
+ if resp.ID != "msg-retry" {
+ t.Fatalf("expected retry result, got %q", resp.ID)
+ }
+ if sendCalls != 2 {
+ t.Fatalf("expected 2 send attempts, got %d", sendCalls)
+ }
+}
diff --git a/src/pkg/error/whatsapp_error.go b/src/pkg/error/whatsapp_error.go
index 7bb2da07..7295b468 100644
--- a/src/pkg/error/whatsapp_error.go
+++ b/src/pkg/error/whatsapp_error.go
@@ -91,5 +91,5 @@ const (
ErrInvalidJID = InvalidJID("your JID is invalid")
ErrUserNotRegistered = InvalidJID("user is not registered")
ErrWaCLI = WaCliError("your WhatsApp CLI is invalid or empty")
- ErrWaReachoutTimelock = WaReachoutTimelockError("WhatsApp rejected this send due to reachout timelock or privacy-token state. Try sending to an existing conversation, have the recipient message you first, and make sure WhatsApp privacy tokens are persisted.")
+ ErrWaReachoutTimelock = WaReachoutTimelockError("WhatsApp rejected this send (error 463). This usually means the recipient is a cold contact (no prior conversation), the WhatsApp account is restricted to mobile-only by Meta, or privacy tokens are missing/expired. Try messaging this number from the official WhatsApp app once, ask the recipient to message you first, or wait a few minutes before retrying. An automatic pre-warm + retry has already been attempted by the server.")
)
diff --git a/src/usecase/send.go b/src/usecase/send.go
index f415f8dd..2b3ba63d 100644
--- a/src/usecase/send.go
+++ b/src/usecase/send.go
@@ -50,9 +50,12 @@ func NewSendService(appService app.IAppUsecase, chatStorageRepo domainChatStorag
}
}
-// wrapSendMessage wraps the message sending process with message ID saving
+// wrapSendMessage sends the message and stores it asynchronously on success.
+// The send goes through whatsapp.SendMessageWithReachoutRetry, which retries
+// once on WhatsApp error 463 after a SubscribePresence pre-warm — see
+// infrastructure/whatsapp/send_retry.go for the protocol-level rationale.
func (service serviceSend) wrapSendMessage(ctx context.Context, client *whatsmeow.Client, recipient types.JID, msg *waE2E.Message, content string) (whatsmeow.SendResponse, error) {
- ts, err := client.SendMessage(ctx, recipient, msg)
+ ts, err := whatsapp.SendMessageWithReachoutRetry(ctx, client, recipient, msg)
if err != nil {
return whatsmeow.SendResponse{}, normalizeSendError(err)
}
@@ -85,7 +88,7 @@ func normalizeSendError(err error) error {
if err == nil {
return nil
}
- if errors.Is(err, whatsmeow.ErrServerReturnedError) && strings.Contains(err.Error(), "463") {
+ if whatsapp.IsReachoutTimelockError(err) {
return pkgError.ErrWaReachoutTimelock
}
return err
diff --git a/src/usecase/send_test.go b/src/usecase/send_test.go
index cd94acc3..d9450bd9 100644
--- a/src/usecase/send_test.go
+++ b/src/usecase/send_test.go
@@ -79,7 +79,7 @@ func TestNormalizeSendErrorMapsReachoutTimelock(t *testing.T) {
if got := genericErr.StatusCode(); got != http.StatusTooManyRequests {
t.Fatalf("expected status %d, got %d", http.StatusTooManyRequests, got)
}
- if got := genericErr.Error(); got != "WhatsApp rejected this send due to reachout timelock or privacy-token state. Try sending to an existing conversation, have the recipient message you first, and make sure WhatsApp privacy tokens are persisted." {
+ if got := genericErr.Error(); got != string(pkgError.ErrWaReachoutTimelock) {
t.Fatalf("unexpected error message: %q", got)
}
}