Skip to content

fix: Melhora o método createConversation (evita conversas criadas duplicadas Chatwoot) #1504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 27, 2025

Conversation

KokeroO
Copy link
Contributor

@KokeroO KokeroO commented May 27, 2025

Descrição

Atualmente o método createConversation recebe acionamentos devido aos eventos recebido d service Baileys.
O método verifica se o contato existe e se a conversa já existe, senão cria-os respectivamente.
O método em si não verifica se outra conversa esta em criação por outro evento do mesmo contato gerando alguns problemas.

Problemas

Principalmente ocorre de mensagens encaminhadas de uma só vez do mesmo contato, o que dispara o método de criação múltiplas vezes de forma instantânea em algumas situações. Cada mensagem recebida cria uma nova conversa no Chatwoot.

Independentemente do recurso disponível ou fluxo de mensagens, múltiplas conversas eram abertas na seguinte situação:

Solução

Criar um bloqueio na execução antes do try/catch de criação da conversa se outro evento ainda esteja criando uma conversa para o mesmo número.
Criei através do uso do cache atual. A solução através de um map parecia ser melhor, mas isso implicaria futuramente na EvolutionApi em trabalhar com replicas de conteiners.

Testes

Testei em 2 clientes, um dele principal, com 15 instancias e mais de 30 mil mensagens todos os dias. Anteriormente tinha de 50 a 100 conversas criadas em duplicidade no Chatwoot, em alguns casos mais de duas conversas.
Atualmente os clientes não tiveram nenhuma conversa criada em duplicidade mais desde a implementação.

Nenhum problema foi relatado alterando parâmetros dentro do Chatwoot ou na integração através do manager.

Summary by Sourcery

Prevent multiple duplicate conversations in Chatwoot by serializing and caching conversation creation per contact

Bug Fixes:

  • Avoid duplicate Chatwoot conversations when multiple simultaneous events for the same contact arrive

Enhancements:

  • Introduce cache-based locks with wait and timeout around createConversation to serialize concurrent requests
  • Cache conversation IDs per contact to reuse existing threads
  • Refine contact and group synchronization logic with improved logging during conversation setup

Copy link
Contributor

sourcery-ai bot commented May 27, 2025

Reviewer's Guide

Introduz um mecanismo de cache e bloqueio em createConversation para evitar conversas duplicadas, reorganiza o fluxo de obtenção e atualização de contatos e grupos, refatora a busca/criação de conversas incluindo lógica de reopenConversation e conversationPending, e remove trechos redundantes de código, com logs mais claros.

Sequence Diagram: Concurrent createConversation Handling

sequenceDiagram
    participant Requester1
    participant Requester2
    participant ChatwootService
    participant Cache

    Requester1->>ChatwootService: createConversation(remoteJid)
    ChatwootService->>Cache: has(convCacheKey_remoteJid)  // Check if conversation already cached
    Cache-->>ChatwootService: false
    ChatwootService->>Cache: has(lockKey_remoteJid)     // Check if operation is locked
    Cache-->>ChatwootService: false
    ChatwootService->>Cache: set(lockKey_remoteJid, true) // Requester1 acquires lock
    Note over ChatwootService, Cache: Lock acquired by Requester1

    Requester2->>ChatwootService: createConversation(remoteJid) // Concurrent request for same remoteJid
    ChatwootService->>Cache: has(convCacheKey_remoteJid)
    Cache-->>ChatwootService: false
    ChatwootService->>Cache: has(lockKey_remoteJid)
    Cache-->>ChatwootService: true // Lock is active, held by Requester1
    Note over ChatwootService: Requester2 starts waiting/polling period

    activate ChatwootService
    Note left of ChatwootService: Requester1 processing
    ChatwootService->>ChatwootService: Perform actual conversation creation/retrieval
    ChatwootService->>Cache: set(convCacheKey_remoteJid, conversationId) // Cache the created conversationId
    ChatwootService->>Cache: delete(lockKey_remoteJid) // Requester1 releases lock
    ChatwootService-->>Requester1: conversationId
    deactivate ChatwootService
    Note over ChatwootService, Cache: Lock released by Requester1, conversationId cached

    activate ChatwootService
    Note left of ChatwootService: Requester2's polling finds change
    ChatwootService->>Cache: has(convCacheKey_remoteJid) // Requester2 checks cache during its wait
    Cache-->>ChatwootService: true // ConversationId found in cache
    ChatwootService->>Cache: get(convCacheKey_remoteJid)
    Cache-->>ChatwootService: conversationId
    ChatwootService-->>Requester2: conversationId (from cache)
    deactivate ChatwootService
Loading

Class Diagram: ChatwootService Update for createConversation

classDiagram
  class ChatwootService {
    -cache: CacheProvider
    -logger: LoggerProvider
    +createConversation(instance: InstanceDto, body: any): Promise<number | null>
  }
  note for ChatwootService "The createConversation method is updated to include caching and a locking mechanism to prevent duplicate conversation creations. It utilizes the 'cache' member for these operations."
Loading

File-Level Changes

Change Details Files
Prevent duplicate conversation creation using cache locks
  • Defined cacheKey, lockKey, and maxWaitTime variables
  • Added early cache.has(cacheKey) check
  • Implemented lock wait loop with timeout and polling
  • Acquired and released lock around creation logic
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Streamline contact and group metadata processing
  • Unified chatId and nameContact derivation
  • Integrated group metadata and participant handling under lock
  • Consolidated findContact, updateContact, and createContact flows
  • Optimized profile picture retrieval and conditional updates
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Refactor conversation lookup and creation flow
  • Simplified client.conversations.listConversations usage
  • Handled reopenConversation and conversationPending status toggling
  • Cached conversationId after retrieval or creation
  • Standardized API calls for conversation creation
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Clean up redundant code and improve logging
  • Removed outdated re-entrancy branches
  • Eliminated duplicate code blocks
  • Refactored verbose logging statements
  • Simplified error handling and early returns
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts

Possibly linked issues

  • #0: The PR prevents duplicate conversations in Chatwoot by adding a lock to the creation method, addressing the issue.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@KokeroO
Copy link
Contributor Author

KokeroO commented May 27, 2025

@sourcery-ai resolve

@rodolfolsouza
Copy link

Essa correção de duplicidade de conversas vai ajudar muito!

@DavidsonGomes DavidsonGomes merged commit dd0dfd4 into EvolutionAPI:develop May 27, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants