fix: delete instance cleanup on baileys failure
📋 Description
🐛 Problem
When calling DELETE /instance/delete/{instanceName} on a corrupted
instance (disconnected/bugged Baileys session), the API returns:
{
"status": 400,
"error": "Bad Request",
"response": { "message": ["[object Object]"] }
}
After this error, the instance name remains permanently blocked in
waInstances memory. Even after manually cleaning the database, Redis,
and session files, calling POST /instance/create with the same name
returns:
{
"status": 403,
"message": ["This name \"agent-xxx\" is already in use."]
}
The only workaround was restarting the container — not viable in production environments.
🔍 Root Cause
Two bugs working together:
1. Aborted cleanup
deleteInstance()stopped execution iflogout()failed
2. Bad error serialization
- Errors returned as
[object Object]
✅ Fix
-
Split
try/catchinto isolated steps -
Ensure cleanup always runs
-
Always remove instance from
waInstances -
Fix error serialization using:
error?.message ?? String(error)
🔗 Related Issue
Closes # (leave empty if not applicable)
🧪 Type of Change
- [x] 🐛 Bug fix (non-breaking change which fixes an issue)
- [ ] ✨ New feature
- [ ] 💥 Breaking change
- [ ] 📚 Documentation update
- [ ] 🔧 Refactoring
- [ ] ⚡ Performance improvement
- [ ] 🧹 Code cleanup
- [ ] 🔒 Security fix
🧪 Testing
- [x] Manual testing completed
- [x] Functionality verified in development environment
- [x] No breaking changes introduced
- [ ] Tested with different connection types
📸 Screenshots (if applicable)
N/A
✅ Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] My changes generate no new warnings
- [x] I have manually tested my changes thoroughly
- [x] I have verified the changes work with different scenarios
📝 Additional Notes
Tested in production environment with Docker Swarm + PostgreSQL + Redis. Fix only affects failure path — no impact on healthy instances.
⚠️ Behavior Change — Contract Documentation
The endpoint now returns { status: 'SUCCESS' } even on partial failures.
Logout and webhook steps were changed from "abort on error" to logger.warn.
This is intentional — the cleanup is best-effort to ensure the instance
name is always released from waInstances memory, even when secondary steps fail.
Clients relying on 4xx responses to detect cleanup failures will need to
adjust their logic.
Hi! As part of our PR triage, we re-ran CI on this PR and the Check Code Quality workflow is failing. Could you please:
- Check the latest run output (
Actionstab on this PR) and address the build/lint errors - Push the fix to your branch — CI will re-run automatically (no need to ping us; it's now auto-approved)
- Make sure the base branch is
develop(already adjusted on our side)
Once CI is green I'll re-review for merge. Thanks!
Boa refatoração — quebrar o try/catch monolítico em steps isolados é a forma idiomática correta de cleanup robusto, e adicionar await em cleaningUp e cleaningStoreData corrige uma race condition latente.
Bloqueadores para o merge:
- [ ] Rebase — PR está CONFLITANDO com main
- [ ] Rodar
npm run lint -- --fix— CI falha com 85 erros prettier emmonitor.service.ts(linhas 1850-2791, formatação automática) - [ ] Documentar mudança de contrato no PR body: o endpoint passa a retornar
{ status: 'SUCCESS' }mesmo em falhas parciais (logout/webhook viramlogger.warnem vez de abortar). Isso é uma escolha deliberada — o cleanup é "best effort" para liberar o nome da instância — mas merece estar explícito para clientes que dependiam de 4xx.
Após os 3 itens, aprovo.
Olá @antonio-abrantes, obrigado pela contribuição — o fix está correto e endereça um problema real de produção (instâncias travadas no waInstances em memória após falha de cleanup).
A PR está em estado CONFLICTING com develop. Pode fazer rebase contra develop quando puder?
git fetch upstream
git rebase upstream/develop
git push --force-with-lease
Após o rebase, mergeio. Obrigado!
🟢 👍
Na develop e focado: melhora o cleanup ao deletar instância quando o Baileys falha — isola o try/catch por etapa e adiciona os await que faltavam, sem reescrever a lógica. Pode seguir.
@dpaes