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
[codex] wait for reachout privacy token before retry (#711)
Aldino Kemal2f72f24f8b17
diff --git a/src/infrastructure/whatsapp/send_retry.go b/src/infrastructure/whatsapp/send_retry.goindex d54f6f66..185fa182 100644--- a/src/infrastructure/whatsapp/send_retry.go+++ b/src/infrastructure/whatsapp/send_retry.go@@ -16,6 +16,11 @@ import (// unhealthy socket cannot stall the retry. One round-trip's worth of slack.const reachoutSubscribeTimeout = 3 * time.Second+var (+ reachoutPrivacyTokenWait = 2 * time.Second+ reachoutPrivacyTokenPollPeriod = 50 * time.Millisecond+)+// 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) {@@ -67,6 +72,12 @@ func SendMessageWithReachoutRetry(ctx context.Context, client *whatsmeow.Client,}cancel()+ if waitForReachoutPrivacyToken(ctx, client, recipient) {+ logrus.Debugf("Privacy token for %s became available before retry", recipient.String())+ } else {+ logrus.Debugf("Retrying send to %s without an observed privacy token", recipient.String())+ }+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)@@ -81,3 +92,39 @@ func SendMessageWithReachoutRetry(ctx context.Context, client *whatsmeow.Client,func isUserJID(jid types.JID) bool {return jid.Server == types.DefaultUserServer || jid.Server == types.HiddenUserServer}++func waitForReachoutPrivacyToken(ctx context.Context, client *whatsmeow.Client, recipient types.JID) bool {+ if client == nil || client.Store == nil || client.Store.PrivacyTokens == nil {+ return false+ }++ waitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), reachoutPrivacyTokenWait)+ defer cancel()++ if hasReachoutPrivacyToken(waitCtx, client, recipient) {+ return true+ }++ ticker := time.NewTicker(reachoutPrivacyTokenPollPeriod)+ defer ticker.Stop()++ for {+ select {+ case <-waitCtx.Done():+ return false+ case <-ticker.C:+ if hasReachoutPrivacyToken(waitCtx, client, recipient) {+ return true+ }+ }+ }+}++func hasReachoutPrivacyToken(ctx context.Context, client *whatsmeow.Client, recipient types.JID) bool {+ token, err := client.Store.PrivacyTokens.GetPrivacyToken(ctx, recipient.ToNonAD())+ if err != nil {+ logrus.Debugf("Failed to check privacy token for %s before retry: %v", recipient.String(), err)+ return false+ }+ return token != nil && len(token.Token) > 0+}diff --git a/src/infrastructure/whatsapp/send_retry_test.go b/src/infrastructure/whatsapp/send_retry_test.goindex bbc0e513..fd82d524 100644--- a/src/infrastructure/whatsapp/send_retry_test.go+++ b/src/infrastructure/whatsapp/send_retry_test.go@@ -3,10 +3,13 @@ package whatsappimport ("context""errors"+ "sync""testing"+ "time""go.mau.fi/whatsmeow""go.mau.fi/whatsmeow/proto/waE2E"+ "go.mau.fi/whatsmeow/store""go.mau.fi/whatsmeow/types")@@ -199,3 +202,129 @@ func TestSendMessageWithReachoutRetry_SubscribeFailureDoesNotAbortRetry(t *testit.Fatalf("expected 2 send attempts, got %d", sendCalls)}}++func TestSendMessageWithReachoutRetry_WaitsForPrivacyTokenBeforeRetry(t *testing.T) {+ origSend := sendMessageFn+ origSub := subscribePresenceFn+ defer func() {+ sendMessageFn = origSend+ subscribePresenceFn = origSub+ }()++ recipient := types.JID{User: "12345", Server: types.DefaultUserServer}+ tokenStore := &memoryPrivacyTokenStore{}+ client := &whatsmeow.Client{+ Store: &store.Device{+ PrivacyTokens: tokenStore,+ },+ }++ var sendCalls int+ sendMessageFn = func(ctx context.Context, client *whatsmeow.Client, recipient types.JID, _ *waE2E.Message) (whatsmeow.SendResponse, error) {+ sendCalls+++ if sendCalls == 1 {+ return whatsmeow.SendResponse{}, reachoutErr()+ }+ token, err := client.Store.PrivacyTokens.GetPrivacyToken(ctx, recipient)+ if err != nil {+ return whatsmeow.SendResponse{}, err+ }+ if token == nil {+ return whatsmeow.SendResponse{}, reachoutErr()+ }+ return whatsmeow.SendResponse{ID: "msg-after-token"}, nil+ }+ subscribePresenceFn = func(context.Context, *whatsmeow.Client, types.JID) error {+ go func() {+ time.Sleep(25 * time.Millisecond)+ _ = tokenStore.PutPrivacyTokens(context.Background(), store.PrivacyToken{+ User: recipient,+ Token: []byte("token"),+ Timestamp: time.Now(),+ })+ }()+ return nil+ }++ resp, err := SendMessageWithReachoutRetry(context.Background(), client, recipient, &waE2E.Message{})+ if err != nil {+ t.Fatalf("expected retry to wait for token and succeed, got %v", err)+ }+ if resp.ID != "msg-after-token" {+ t.Fatalf("expected retry response after token, got %q", resp.ID)+ }+ if sendCalls != 2 {+ t.Fatalf("expected 2 send attempts, got %d", sendCalls)+ }+}++func TestSendMessageWithReachoutRetry_RetriesWhenPrivacyTokenNeverAppears(t *testing.T) {+ origSend := sendMessageFn+ origSub := subscribePresenceFn+ origWait := reachoutPrivacyTokenWait+ origPoll := reachoutPrivacyTokenPollPeriod+ defer func() {+ sendMessageFn = origSend+ subscribePresenceFn = origSub+ reachoutPrivacyTokenWait = origWait+ reachoutPrivacyTokenPollPeriod = origPoll+ }()++ reachoutPrivacyTokenWait = 20 * time.Millisecond+ reachoutPrivacyTokenPollPeriod = 5 * time.Millisecond++ recipient := types.JID{User: "12345", Server: types.DefaultUserServer}+ client := &whatsmeow.Client{+ Store: &store.Device{+ PrivacyTokens: &memoryPrivacyTokenStore{},+ },+ }++ var sendCalls int+ sendMessageFn = func(context.Context, *whatsmeow.Client, types.JID, *waE2E.Message) (whatsmeow.SendResponse, error) {+ sendCalls+++ return whatsmeow.SendResponse{}, reachoutErr()+ }+ subscribePresenceFn = func(context.Context, *whatsmeow.Client, types.JID) error {+ return nil+ }++ _, err := SendMessageWithReachoutRetry(context.Background(), client, recipient, &waE2E.Message{})+ if !errors.Is(err, whatsmeow.ErrServerReturnedError) {+ t.Fatalf("expected original reachout error after retry, got %v", err)+ }+ if sendCalls != 2 {+ t.Fatalf("expected 2 send attempts, got %d", sendCalls)+ }+}++type memoryPrivacyTokenStore struct {+ mu sync.RWMutex+ tokens map[types.JID]store.PrivacyToken+}++func (s *memoryPrivacyTokenStore) PutPrivacyTokens(_ context.Context, tokens ...store.PrivacyToken) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.tokens == nil {+ s.tokens = make(map[types.JID]store.PrivacyToken)+ }+ for _, token := range tokens {+ s.tokens[token.User.ToNonAD()] = token+ }+ return nil+}++func (s *memoryPrivacyTokenStore) GetPrivacyToken(_ context.Context, user types.JID) (*store.PrivacyToken, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()+ token, ok := s.tokens[user.ToNonAD()]+ if !ok {+ return nil, nil+ }+ return &token, nil+}++func (s *memoryPrivacyTokenStore) DeleteExpiredPrivacyTokens(context.Context, time.Time) (int64, error) {+ return 0, nil+}