fix: fecha socket anterior antes de recriar cliente Baileys#2656
Open
PhyBruno wants to merge 6 commits into
Open
fix: fecha socket anterior antes de recriar cliente Baileys#2656PhyBruno wants to merge 6 commits into
PhyBruno wants to merge 6 commits into
Conversation
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…n-foundation Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
QR Code as vezes era gerado mas o WhatsApp respondia com "Nao foi
possivel conectar o dispositivo". Causa raiz: createClient sobrescrevia
this.client com um novo makeWASocket(...) sem fechar o socket anterior,
deixando handlers de evento antigos vivos e disputando a mesma
authState/credenciais com o socket novo - corrompendo o handshake da
nova sessao.
Antes de criar o socket novo, fecha explicitamente o anterior
(ws.close() + end()), reaproveitando o mesmo padrao ja usado no
handler de connection.update para fechamento de conexao ('close').
Contributor
Reviewer's guide (collapsed on small PRs)Reviewer's GuideThis PR ensures the previous Baileys WhatsApp socket is cleanly closed before recreating a client, preventing concurrent sockets from corrupting authentication state during QR-based reconnections. Sequence diagram for recreating Baileys WhatsApp client with socket cleanupsequenceDiagram
participant BaileysStartupService
participant BaileysClient_old as BaileysClient_old
participant BaileysClient_new as BaileysClient_new
BaileysStartupService->>BaileysClient_old: ws.close()
BaileysStartupService->>BaileysClient_old: end(Error)
BaileysStartupService->>BaileysClient_new: makeWASocket(socketConfig)
BaileysStartupService->>BaileysStartupService: this.client = BaileysClient_new
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Contributor
There was a problem hiding this comment.
Hey - I've left some high level feedback:
- Consider extracting the socket cleanup logic (ws.close + end) into a shared helper or method, since the same pattern is already used in the connection.update 'close' handler, to keep behavior consistent and avoid duplication.
- When logging the error in the cleanup try/catch, you may want to log the full error object or message separately (e.g., this.logger.warn('...', { error })) to preserve stack and structured information for easier debugging.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider extracting the socket cleanup logic (ws.close + end) into a shared helper or method, since the same pattern is already used in the connection.update 'close' handler, to keep behavior consistent and avoid duplication.
- When logging the error in the cleanup try/catch, you may want to log the full error object or message separately (e.g., this.logger.warn('...', { error })) to preserve stack and structured information for easier debugging.Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problema
Mesmo apos gerar o QR Code, as vezes o WhatsApp responde com "Nao foi possivel conectar o dispositivo" ao escanear.
Causa raiz
createClient(emwhatsapp.baileys.service.ts) sobrescrevethis.clientcom um novomakeWASocket(socketConfig)sem antes fechar o socket anterior. Em tentativas repetidas de gerar QR (retry manual do usuario, ou reconexao disparada por uma integracao externa), o socket antigo continua "vivo", com seus event handlers ativos disputando a mesmaauthState/credenciais com o socket novo - corrompendo o handshake da nova sessao.Mudanca
Antes de
this.client = makeWASocket(socketConfig), se ja existir umthis.clientde uma tentativa anterior, ele e fechado (ws.close()+end(new Error(...))) - mesmo padrao ja usado no proprio arquivo, no handler deconnection.updateparaconnection === 'close'. A limpeza fica em try/catch (log emwarn) para nao impedir a criacao do novo socket em caso de falha ao fechar o antigo.Nota: este PR toca o mesmo metodo (
createClient) que #2655. Os dois foram gerados/validados de forma independente contramaine cada um builda/lint limpo isoladamente, mas ao mesclar ambos pode ser necessario um rebase simples (proximidade de linha, nao conflito de logica).Validacao
npx tsc --noEmit: sem erros.npx eslint --ext .ts src: sem erros/warnings.Summary by Sourcery
Bug Fixes: