fix(instance): prevent GetQr from disconnecting active logged-in session - #149
Open
iagocotta wants to merge 1 commit into
Open
fix(instance): prevent GetQr from disconnecting active logged-in session#149iagocotta wants to merge 1 commit into
iagocotta wants to merge 1 commit into
Conversation
Reviewer's guide (collapsed on small PRs)Reviewer's GuideAdjusts GetQr behavior to avoid restarting an already logged-in WhatsApp instance, preventing active sessions from being disconnected when the QR endpoint is polled, and refines the conditions and logging around when StartInstance is invoked. File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've left some high level feedback:
- Consider defining a sentinel error (e.g.,
ErrSessionAlreadyLoggedIn) instead offmt.Errorf("session already logged in")so callers can reliably distinguish this case from other errors when mapping to HTTP status codes. - The new logging messages are quite verbose and repeated on every
GetQrcall; consider reducing or standardizing them to avoid log noise while still capturing the key state transitions.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider defining a sentinel error (e.g., `ErrSessionAlreadyLoggedIn`) instead of `fmt.Errorf("session already logged in")` so callers can reliably distinguish this case from other errors when mapping to HTTP status codes.
- The new logging messages are quite verbose and repeated on every `GetQr` call; consider reducing or standardizing them to avoid log noise while still capturing the key state transitions.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
Quando
GET /instance/qré chamado em uma instância que já está logada (client.IsLoggedIn() == true), a implementação atual doGetQrchamawhatsmeowService.StartInstance()mesmo assim, derrubando o cliente whatsmeow ativo e forçando um novo pareamento.Reprodução
PairSuccessPairSuccess, o whatsmeow entra emConnected: true, LoggedIn: falsepor ~5–15 s enquanto faz o history sync inicialGET /instance/qrdurante esse intervalo (muito comum — a maioria dos managers faz polling a cada 3–5 s para detectar a conexão) cai no branch com bugIsLoggedIn()retornatrueem qualquer momento após o login completar, o handler chamaStartInstance()→ whatsmeow desconecta → novo QR code é emitidoSequência de webhooks observada
Isso não ocorre ao usar o próprio manager web do Evolution-Go, porque ele usa SSE para mudanças de status em vez de fazer polling em
/instance/qr.Causa raiz
pkg/instance/service/instance_service.gono métodoGetQr:O comentário ("iniciar um novo cliente") revela que a intenção original era (re)iniciar quando não houvesse cliente. Mas a condição também dispara para clientes logados, provavelmente para forçar um novo QR quando o chamador quer explicitamente re-parear. Esse caminho deveria ser um opt-in explícito, não o comportamento padrão do
GetQr.Correção
Separar os dois casos:
client.IsLoggedIn()→ retorna"session already logged in"imediatamente, sem tocar noStartInstance. Chamadores que queiram forçar re-pareamento podem fazer logout antes viaDELETE /instance/logoutou usarPOST /instance/forcereconnect.client == nilou!client.IsConnected() && !client.IsLoggedIn()→ inicia a instância como antes.Comportamento quando o chamador faz polling em
/instance/qrnuma instância logada:"session already logged in"(já era o comportamento documentado da segunda checagem deIsLoggedIndentro do branch — essa correção apenas faz o short-circuit antes da chamada destrutiva aoStartInstance)Impacto
"session already logged in"; essa correção apenas torna a resposta consistente independentemente do timing e remove o efeito colateral/instance/qrpara detectar conexão agora podem fazer isso com segurança, sem risco de desconectar a instância que acabaram de parearTestado
/instance/qra cada 4 sPairSuccessSummary by Sourcery
Prevent QR retrieval from restarting already logged-in WhatsApp instances, avoiding unintended disconnects during polling.
Bug Fixes: