44 changed files with 618 additions and 2913 deletions

No files matched your search

-52
View File
@@ -1,52 +0,0 @@
name: CI - Validacao Go
on:
push:
branches:
- main
- maintained-develop
- maintained-stable
- 'fix/*'
- 'maintenance/*'
pull_request:
branches:
- maintained-develop
- maintained-stable
workflow_dispatch:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
validate:
name: Validar Codigo e Testes
runs-on: ubuntu-latest
steps:
- name: Checkout do Repositorio
uses: actions/checkout@v4
with:
submodules: recursive
- name: Configurar Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Instalar Dependencias de Sistema
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends libjpeg-dev libwebp-dev poppler-utils ffmpeg
- name: Verificar Integridade das Dependencias
run: go mod verify
- name: Compilar Codigo
run: go build ./...
- name: Analise Estatica (Go Vet)
run: go vet ./...
- name: Executar Testes Unitarios
run: go test -v ./...
-171
View File
@@ -1,171 +0,0 @@
name: Docker - Build e Publicacao
# Publicacao no registry do Gitea (git.jf.eng.br/jfeng/evogo):
# - push de tag v<versao> (ex: v0.7.2-evogo.1) = release aprovado -> publica
# git.jf.eng.br/jfeng/evogo:<versao> (tag semantica)
# git.jf.eng.br/jfeng/evogo:<versao>-<sha7> (tag imutavel do commit)
# - workflow_dispatch com publish_image=true -> idem, versao = target_tag ou VERSION
# - push em maintained-stable -> apenas build + teste + scan (nao publica)
# Tags v* aprovadas em maintained-stable tambem promovem :latest apos o push
# das tags imutavel e semantica, evitando a corrida com promote-latest.yml.
on:
push:
branches:
- maintained-stable
tags:
- 'v*'
workflow_dispatch:
inputs:
publish_image:
description: 'Publicar imagem no registry apos build e testes (requer aprovacao)'
type: boolean
default: false
required: true
target_tag:
description: 'Tag semantica para publicacao (ex: 0.7.2-evogo.1). Vazio = arquivo VERSION'
type: string
default: ''
required: false
promote_latest:
description: 'Tambem atualizar :latest (somente versoes aprovadas em maintained-stable)'
type: boolean
default: false
required: false
concurrency:
group: promote-latest
cancel-in-progress: false
env:
REGISTRY: git.jf.eng.br
IMAGE: git.jf.eng.br/jfeng/evogo
jobs:
build_docker:
name: Build, Scan e Publicacao
runs-on: ubuntu-latest
steps:
- name: Checkout do Repositorio
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Validar origem da promocao latest
id: promotion
run: |
PROMOTE=false
if { [ "${{ github.event_name }}" = "push" ] && [ "${{ github.ref_type }}" = "tag" ]; } || [ "${{ github.event.inputs.promote_latest }}" = "true" ]; then
git fetch origin maintained-stable
if git merge-base --is-ancestor HEAD FETCH_HEAD; then
PROMOTE=true
elif [ "${{ github.event.inputs.promote_latest }}" = "true" ]; then
echo "Promocao recusada: commit nao aprovado em maintained-stable"
exit 1
fi
fi
echo "promote=${PROMOTE}" >> "$GITHUB_OUTPUT"
- name: Configurar Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Validar codigo antes da publicacao
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends libjpeg-dev libwebp-dev poppler-utils ffmpeg
go mod verify
go vet ./...
go test -v ./...
- name: Obter Versao e Commit SHA
id: meta
run: |
COMMIT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
if [ "${{ github.ref_type }}" = "tag" ]; then
VERSION="${{ github.ref_name }}"
VERSION="${VERSION#v}"
PUBLISH=true
else
VERSION="${{ github.event.inputs.target_tag }}"
[ -n "$VERSION" ] || VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
PUBLISH="${{ github.event.inputs.publish_image == 'true' }}"
fi
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
echo "commit_sha=${COMMIT_SHA}" >> "$GITHUB_OUTPUT"
echo "image_tag=${VERSION}-${COMMIT_SHA}" >> "$GITHUB_OUTPUT"
echo "publish=${PUBLISH}" >> "$GITHUB_OUTPUT"
echo "Versao: ${VERSION} | Commit: ${COMMIT_SHA} | Publicar: ${PUBLISH}"
- name: Construir Imagem Docker Local
run: |
docker build \
--build-arg VERSION=${{ steps.meta.outputs.image_tag }} \
-t evogo:ci-${{ steps.meta.outputs.commit_sha }} .
- name: Testar Inicializacao do Container
run: |
# O binario precisa subir e falhar apenas por falta de banco/config,
# nunca por erro de link (CGO/libwebp/libjpeg) ou arquivo ausente.
set +e
timeout 20 docker run --rm evogo:ci-${{ steps.meta.outputs.commit_sha }} > /tmp/run.log 2>&1
set -e
tail -20 /tmp/run.log
if grep -qiE "error while loading shared libraries|exec format error|exec /app/server" /tmp/run.log; then
echo "Falha ao iniciar o binario dentro da imagem"; exit 1
fi
docker run --rm --entrypoint sh evogo:ci-${{ steps.meta.outputs.commit_sha }} -c 'test -x /app/server && test -d /app/manager/dist && cat /app/VERSION'
- name: Verificar Vulnerabilidades (Trivy, nao bloqueante)
continue-on-error: true
run: |
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest \
image --severity HIGH,CRITICAL --ignore-unfixed --no-progress \
evogo:ci-${{ steps.meta.outputs.commit_sha }}
- name: Login no Gitea Package Registry
if: steps.meta.outputs.publish == 'true'
run: |
USER="${{ secrets.REGISTRY_USER }}"
[ -n "$USER" ] || USER="${{ github.actor }}"
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
# O registry ja estourou timeout pontualmente (run 482); tenta de novo antes de falhar.
for n in 1 2 3 4 5; do
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin && exit 0
echo "Login falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
exit 1
- name: Publicar Imagens no Registry
if: steps.meta.outputs.publish == 'true'
run: |
push() {
for n in 1 2 3 4 5; do
docker push "$1" && return 0
echo "Push de $1 falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
return 1
}
SRC=evogo:ci-${{ steps.meta.outputs.commit_sha }}
for TAG in "${{ steps.meta.outputs.image_tag }}" "${{ steps.meta.outputs.version }}"; do
docker tag "$SRC" "$IMAGE:$TAG"
push "$IMAGE:$TAG"
echo "Publicado: $IMAGE:$TAG"
done
if [ "${{ steps.promotion.outputs.promote }}" = "true" ]; then
docker tag "$SRC" "$IMAGE:latest"
push "$IMAGE:latest"
IMMUTABLE_DIGEST=$(docker buildx imagetools inspect "$IMAGE:${{ steps.meta.outputs.image_tag }}" --format '{{json .Manifest.Digest}}')
LATEST_DIGEST=$(docker buildx imagetools inspect "$IMAGE:latest" --format '{{json .Manifest.Digest}}')
[ -n "$IMMUTABLE_DIGEST" ] && [ "$IMMUTABLE_DIGEST" = "$LATEST_DIGEST" ]
echo "Publicado e verificado: $IMAGE:latest = $IMMUTABLE_DIGEST"
fi
- name: Limpeza
if: always()
run: docker image rm -f evogo:ci-${{ steps.meta.outputs.commit_sha }} >/dev/null 2>&1 || true
-71
View File
@@ -1,71 +0,0 @@
name: Docker - Promover latest
# :latest = ultimo release v* contido em maintained-stable.
# Nao recompila: baixa a imagem imutavel <versao>-<sha7> ja publicada pelo
# docker-build.yml para aquela tag e apenas a re-etiqueta, preservando o digest.
# So roda quando maintained-stable avanca (promocao aprovada) ou manualmente.
on:
push:
branches:
- maintained-stable
workflow_dispatch:
concurrency:
group: promote-latest
cancel-in-progress: false
env:
REGISTRY: git.jf.eng.br
IMAGE: git.jf.eng.br/jfeng/evogo
jobs:
promote:
name: Promover release para latest
runs-on: ubuntu-latest
steps:
- name: Checkout do Repositorio
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Identificar release
id: rel
run: |
git fetch --tags --force
TAG=$(git describe --tags --abbrev=0 --match 'v*' HEAD)
SHA7=$(git rev-list -n1 "$TAG" | cut -c1-7)
VERSION="${TAG#v}"
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
echo "source=${IMAGE}:${VERSION}-${SHA7}" >> "$GITHUB_OUTPUT"
echo "Release: ${TAG} -> ${IMAGE}:${VERSION}-${SHA7}"
- name: Login no Gitea Package Registry
run: |
USER="${{ secrets.REGISTRY_USER }}"
[ -n "$USER" ] || USER="${{ github.actor }}"
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
for n in 1 2 3 4 5; do
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin && exit 0
echo "Login falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
exit 1
- name: Re-etiquetar como latest
run: |
retry() {
for n in 1 2 3 4 5; do
"$@" && return 0
echo "'$*' falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
return 1
}
SRC="${{ steps.rel.outputs.source }}"
retry docker pull "$SRC"
docker tag "$SRC" "$IMAGE:latest"
retry docker push "$IMAGE:latest"
echo "Publicado: $IMAGE:latest (mesmo digest de $SRC)"
-53
View File
@@ -1,53 +0,0 @@
name: Sincronizacao Diaria com o Upstream
# Incorpora o upstream oficial (evolution-foundation/evolution-go) sem perder as
# correcoes EvoGO: o merge e feito numa branch maintenance/sync-upstream-<sha>
# criada a partir de maintained-develop, testado e enviado como PR.
# Conflitos viram Issue. maintained-stable nunca e tocada.
# Ver scripts/upstream-sync.sh e docs/maintenance/UPSTREAM_SYNC.md.
on:
schedule:
# Diariamente as 04:00 UTC (01:00 BRT)
- cron: '0 4 * * *'
workflow_dispatch:
concurrency:
group: upstream-sync
cancel-in-progress: false
jobs:
sync:
name: Incorporar upstream e verificar whatsmeow
runs-on: ubuntu-latest
steps:
- name: Checkout do Repositorio
uses: actions/checkout@v4
with:
ref: maintained-develop
fetch-depth: 0
token: ${{ secrets.GITEA_TOKEN }}
- name: Configurar Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Instalar Dependencias de Sistema
run: |
sudo apt-get update -qq
sudo apt-get install -y -qq --no-install-recommends libjpeg-dev libwebp-dev
- name: Sincronizar com o upstream
env:
GITEA_URL: ${{ github.server_url }}
REPO: ${{ github.repository }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
# Defina a variavel de repositorio AUTO_MERGE_UPSTREAM=true para mesclar
# automaticamente em maintained-develop quando build e testes passarem.
AUTO_MERGE: ${{ vars.AUTO_MERGE_UPSTREAM || 'false' }}
run: |
git config user.name "EvoGO Upstream Bot"
git config user.email "[email protected]"
bash scripts/upstream-sync.sh
-157
View File
@@ -1,157 +0,0 @@
# AGENTS.md — Diretrizes de Manutenção para Agentes de IA (EvoGO)
Este repositório é uma distribuição/fork independente do **Evolution Go**, mantido no Gitea com suporte contínuo, correções de compatibilidade, segurança e pipelines automatizados.
Qualquer agente de IA que atue neste repositório deve obrigatoriamente seguir as diretrizes abaixo.
---
## 1. Infraestrutura e Ambientes
- **Servidor Git:** `https://git.jf.eng.br` (Gitea v28.3.0)
- **Organização / Proprietário padrão:** `jfeng`
- **Repositório:** `EvoGO`
- **URL Remota (SSH):** `ssh://[email protected]:1080/jfeng/EvoGO.git`
- **Gitea Actions Runner:** `runner-do-zimaos` (Global)
- **Label para execução de jobs:** `ubuntu-latest`
- **Upstream Oficial:** `https://github.com/evolution-foundation/evolution-go.git`
### Regras de Autenticação e Segredos
- Reutilize credenciais já configuradas no Gitea (`GITEA_TOKEN` nativo).
- Segredos de container registry disponíveis: `REGISTRY_USER` e `REGISTRY_TOKEN`.
- **NUNCA** inclua credenciais, senhas ou tokens no código-fonte, nos commits ou em logs.
- Não crie runners adicionais sem autorização explícita do proprietário.
---
## 2. Arquitetura Resumida do Projeto
O Evolution Go é uma API de integração com o WhatsApp desenvolvida em Go (Go 1.25/1.26), de alta performance e baixo consumo de memória, utilizando a biblioteca `whatsmeow` (Go/WebSocket/Noise protocol).
### Estrutura de Pastas:
- `cmd/evolution-go/main.go`: Ponto de entrada da aplicação, inicialização de rotas, banco e serviços.
- `pkg/core/`: Gerenciamento de runtime, middlewares centrais e verificação de licença.
- `pkg/whatsmeow/service/`: Camada de abstração e comunicação com a biblioteca whatsmeow, controle de clientes, reconexão e handshake de versão.
- `pkg/instance/`: Gerenciamento de instâncias (iniciar, parar, conectar, QR Code, pairing).
- `pkg/message/`: Modelos, repositórios e serviços de mensagens recebidas e salvas.
- `pkg/sendMessage/`: Envio de mensagens de texto, mídias, áudios, stickers, enquetes e interações.
- `pkg/routes/`: Registro de todas as rotas da API REST (Gin).
- `pkg/events/`: Publicadores de eventos para Webhooks, WebSocket, RabbitMQ e NATS.
- `manager/dist/`: Frontend SPA compilado do console de gerenciamento.
- `.gitea/workflows/`: Pipelines de CI/CD para Gitea Actions.
- `docs/maintenance/`: Documentação operacional e governança do fork independente.
---
## 3. Estratégia de Branches e Ciclo de Vida
O repositório adota um modelo de isolamento estrito para proteger o código em produção:
```
[upstream/main] (GitHub)
│ (sincronização manual/controlada)
▼
[upstream-sync] (Gitea)
│
▼
[maintained-develop] ◄── [fix/*] (ex: fix/client-outdated-405)
│ ◄── [maintenance/*] (ex: dependências)
▼ (após testes e validação)
[maintained-stable] (origem das releases e imagens Docker oficiais)
```
1. **`upstream-sync`**:
- Espelha fielmente a branch principal do upstream oficial (`evolution-foundation/evolution-go`).
- Nunca recebe commits diretos com alterações locais ou de customização.
2. **`maintained-stable`**:
- Versão de produção da nossa distribuição.
- Apenas recebe merges após validação completa na branch `maintained-develop`.
- Origem das tags imutáveis e releases de imagens Docker.
3. **`maintained-develop`**:
- Branch principal de integração. Novas correções e bumps de dependências são mesclados aqui primeiro.
4. **`fix/*` e `maintenance/*`**:
- Branches de trabalho isoladas para correções específicas e atualizações de bibliotecas.
- Devem ser criadas a partir de `maintained-develop`.
---
## 4. Regras para Modificações e Padrões Go
1. **Priorize correções atômicas, pequenas e reversíveis:**
- Evite refatorações em massa que dificultem o rebase ou cherry-pick futuro contra o upstream.
2. **Preservação de Licenças e Atribuições:**
- Mantenha intocados os arquivos `LICENSE`, `NOTICE` e `TRADEMARKS.md`.
- Não altere, remova ou burle mecanismos de licenciamento ou autenticação existentes em `pkg/core/`.
3. **Padrões de Código Go:**
- Formatação obrigatória com `go fmt ./...`.
- Análise estática limpa com `go vet ./...`.
- Tratamento explícito de erros: nunca ignore erros (`_ = err` é proibido em I/O e conexões).
- Use contextos (`context.Context`) em todas as chamadas bloqueantes e de rede.
- Proteção de concorrência com `sync.Mutex` ao manipular estados de clientes ou caches globais.
4. **Compatibilidade com o Upstream:**
- Mantenha modificações isoladas em camadas de serviço (`pkg/.../service/`), preservando as assinaturas dos handlers HTTP e contratos públicos da API sempre que possível.
---
## 5. Procedimentos de Atualização e Sincronização
Quando houver novos lançamentos ou commits no repositório upstream:
1. **Buscar alterações sem merge imediato:**
```bash
git fetch upstream --tags
```
2. **Comparar histórico:**
```bash
git log upstream-sync..upstream/main --oneline
git diff upstream-sync..upstream/main
```
3. **Atualizar `upstream-sync` (fast-forward apenas):**
```bash
git checkout upstream-sync
git merge --ff-only upstream/main
```
4. **Criar branch de integração para análise de impacto:**
```bash
git checkout -b maintenance/sync-upstream-<versao> maintained-develop
git merge upstream-sync
```
5. **Resolver conflitos e executar testes:**
- Validar testes automatizados: `go test ./...`.
- Construir imagem de teste e validar checklist de compatibilidade.
6. **Abrir Pull Request no Gitea:**
- Submeta PR de `maintenance/sync-upstream-<versao>` para `maintained-develop`.
- Nunca faça merge direto para `maintained-stable`.
---
## 6. Procedimento de Build e Docker
### Build Local / Validação Go:
```bash
go vet ./...
go test -v ./...
CGO_ENABLED=1 go build -o server ./cmd/evolution-go
```
### Build Docker:
```bash
docker build -t evogo:local -f Dockerfile .
```
### Regras de Publicação de Imagens:
1. Imagens **NUNCA** devem ser publicadas sem aprovação humana expressa.
2. As tags devem incluir o identificador imutável do commit git (ex: `evogo:0.7.2-abc1234`) e a tag semântica (ex: `evogo:0.7.2`).
3. A tag `:latest` só deve ser atualizada quando uma versão for promovida e aprovada em `maintained-stable`.
---
## 7. Processo de Revisão e Checklist Obrigatório
Antes de aprovar ou propor qualquer merge:
- [ ] O código compila sem warnings no `go vet`.
- [ ] Todos os testes unitários passam (`go test ./...`).
- [ ] A compatibilidade com sessões do WhatsApp existentes foi avaliada (migrações de SQLite/Postgres).
- [ ] Nenhuma credencial ou segredo foi exposta.
- [ ] O arquivo `CHANGELOG.md` foi atualizado sob a seção adequada.
- [ ] O rollback foi planejado e documentado caso ocorra regressão.
+37 -69
View File
@@ -1,78 +1,46 @@
# Evolution GO - Changelog
## Não lançado
## v0.7.3
### Manutenção da atualização 0.7.3
- Incorporadas seletivamente as melhorias do upstream 0.7.3: timeout de 60 s
no upgrade do banco de autenticação, nova tentativa após falha e registro
explícito do driver Postgres na configuração.
- SQLite de autenticação limitado a uma conexão compartilhada, evitando
concorrência de escrita; preservadas as correções próprias de envio e reconexão.
- Releases por tag aprovadas em `maintained-stable` passam a publicar `latest`
após as imagens versionadas, com conferência do digest e testes Go no pipeline.
- Sem alteração de dependências, schema ou contratos públicos nesta atualização.
**Docker:** `evoapicloud/evolution-go:0.7.3`
### 🔧 Correções
- **whatsmeow atualizado para 2026-11-02** — a versão fixada na 0.7.2
(commit `b572e5bcb92b`, de 30/06/2026) ficou 125 dias atrás do upstream. O
WhatsApp subiu a versão mínima de cliente nesse intervalo e passou a recusar a
conexão com **405 client outdated**, impedindo pareamento e reconexão das
instâncias. Agora em `v0.0.0-20261102152715-54038813c47f`.
- **Go 1.26** — o whatsmeow novo exige `go >= 1.26.0`; o `Dockerfile` passou a
usar `golang:1.26.10-alpine` no estágio de build.
- **Ajustes de API do whatsmeow** — `UpdateBlocklist` e `GetBlocklist` agora
recebem um `dhash`; `SetStatusMessage` passou a receber `types.SetStatusInput`
(novo endpoint mex). O formato de resposta de bloqueio mudou de
`Modifications` para `Items` (com `LID`/`PN`/`Active`) — a documentação foi
atualizada, mas integrações que leem `Modifications` precisam de ajuste.
- **Migração automática do banco de autenticação** — o schema do whatsmeow sobe
de v14 para v16 (`companion_meta_nonce`, `wasa_root_secret_id`). Roda sozinho
ao abrir o container; testado com banco SQLite v14 existente.
- **Build quebrado após o fix 405** — `whatsmeow.go` referenciava `waProto`
(pacote inexistente); `ClientPayload_UserAgent_AppVersion` vem de
`go.mau.fi/whatsmeow/proto/waWa6`.
### 🐛 Bug Fixes
- **`Client outdated (405)` on every connect.** Since 2026-11-02 WhatsApp
rejects the client version sent by 0.7.2 (`2.3000.1042386815`), so every
instance dropped and could not reconnect. whatsmeow moves to `54038813c47f`,
which sends `2.3000.1052556849`. Paired sessions reconnect without a new QR
code.
- **Postgres connection leak on every connect and reconnect.** `StartClient`
called `sqlstore.New` on each run, so every connect, reconnect and client
restart opened a new connection pool that was never closed: one more
connection to `POSTGRES_AUTH_DB` per call. It now uses a single auth container
per process, built with `sqlstore.NewWithDB` on the pool `main.go` already
opens and caps (25 open / 5 idle). Against a real Postgres, 40 `StartClient`
calls grew the backend connections by 40 on 0.7.2 and by 1 on 0.7.3.
- **Auth store upgrade bounded by a deadline.** The container upgrade runs
under a mutex; it now gives up after 60s instead of stalling every
`StartClient` behind a database that accepts TCP but never answers. A failed
creation is retried on the next call instead of being cached.
- **`postgres` driver registered explicitly** in `pkg/config`, with a test, so
`sql.Open("postgres")` cannot start failing at boot after an import cleanup.
- **Nono dígito (BR)** — envios para celulares brasileiros consultam no
WhatsApp as duas variantes (com e sem o 9) e usam a que está registrada.
Contas antigas sem o 9 (ex.: `554291389691`) passam a receber mesmo quando o
sistema envia `5542991389691`, e vice-versa (upstream issue #214 / PR #208).
- **LID enviado como número** — quando o `number` não existe como telefone mas
é o LID de um contato já conhecido pela instância (ex.: `255284433936406`),
o envio vai direto para `255284433936406@lid` em vez de falhar com
`no LID found for [email protected]`.
### ⚠️ Breaking Changes
- **Blocklist responses changed shape.** The `data` returned by
`POST /user/block`, `POST /user/unblock` and `GET /user/blocklist` follows
the new whatsmeow blocklist: `JIDs` is replaced by `Items`, a list of
`{LID, PN, Active}`, and `AddressingMode` is added. `DHash` stays. Blocking a
number that has no LID on WhatsApp now returns an error.
### 🆕 Novidades
- `GET /server/ok` passa a informar a versão em execução
(`{"status":"ok","version":"0.7.2-evogo.3-<sha7>"}`).
### 🛡️ Estabilidade (correções da comunidade incorporadas pelo EvoGO)
- **Crash `concurrent map writes`** — `clientPointer`, `myClientPointer` e
`killChannel` agora são `safemap.Map` com RWMutex (upstream PR #196, issue #203).
- **Vazamento de conexões Postgres** — um único `sqlstore.Container`
compartilhado em vez de um novo pool a cada `StartClient`/reconexão
(upstream PR #206, issues #165/#175/#215).
- **Loop de reconexão/QR infinito** — backoff progressivo após 5 reinícios em
15 min (upstream PR #197); cliente sem dispositivo pareado não é reiniciado
(upstream PR #240); `StartClient` duplicado é ignorado (upstream PR #239).
- **Panics que derrubavam todas as instâncias** — `ReconnectClient` serializado
por instância com checagem de nil (issue #188); envio em canal fechado ao
excluir instância durante o QR (issue #222); evento `Archive` (upstream PR #195).
- **Webhooks paravam após desconectar pela API** — `Disconnect` não apaga mais
as inscrições de eventos (upstream PR #187).
- **`/user/info` e `/user/avatar` travando 75 s** — `ParseJID` remove o `+` de
JIDs de usuário (upstream PR #224, issue #223).
- **WebSocket** — todos os assinantes de uma instância recebem eventos e as
escritas são serializadas por conexão (upstream PR #181).
- **NATS** — sem `NATS_URL` a conexão não é tentada (upstream PR #143).
### ⚙️ Manutenção EvoGO
- Sincronização diária com o upstream via Gitea Actions: merge em
`maintenance/sync-upstream-<sha>` a partir de `maintained-develop`, build/testes
e PR automático; conflitos viram Issue; aviso de whatsmeow desatualizado.
- Publicação da imagem em `git.jf.eng.br/jfeng/evogo` por tag `v*`, com tag
imutável `<versão>-<sha7>` e scan Trivy.
- Login, pull e push no registry com até 5 tentativas — um timeout pontual do
endpoint de token derrubou a publicação da `v0.7.2-evogo.2` (run 482).
### ⬆️ Upgrade notes
- No configuration change. With SQLite (no `POSTGRES_AUTH_DB`), all instances
now share one auth database connection.
- Building from source requires Go 1.26. The Docker image builds with
`golang:1.26.10-alpine`.
- The whatsmeow store gets two new columns on startup (schema v16). The
migration is backwards compatible, so going back to the 0.7.2 image keeps
working.
- A `CONNECTION LIMIT` set on the database role to contain the leak can stay;
this service now keeps its connections within its own pool.
## v0.7.2
+1 -1
View File
@@ -5,7 +5,7 @@ APP_NAME=evolution-go
MAIN_PATH=cmd/evolution-go/main.go
BUILD_DIR=build
GO=go
VERSION=$(shell sed -n 's/^## \(v[0-9][^ ]*\).*/\1/p' CHANGELOG.md | head -1)
VERSION=$(shell grep -om1 "v[0-9].*" CHANGELOG.md)
LDFLAGS=-ldflags "-X main.version=$(VERSION)"
GOFLAGS=-v
+1 -1
View File
@@ -1 +1 @@
0.7.3-evogo.1
0.7.3
+3 -4
View File
@@ -5,7 +5,6 @@ import (
"database/sql"
"flag"
"fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"log"
"net/http"
"os"
@@ -84,8 +83,8 @@ func init() {
}
func setupRouter(db *gorm.DB, authDB *sql.DB, sqliteDB *sql.DB, config *config.Config, conn *amqp.Connection, exPath string, runtimeCtx *core.RuntimeContext) *gin.Engine {
killChannel := safemap.New[chan bool]()
clientPointer := safemap.New[*whatsmeow.Client]()
killChannel := make(map[string](chan bool))
clientPointer := make(map[string]*whatsmeow.Client)
loggerWrapper := logger_wrapper.NewLoggerManager(config)
@@ -239,7 +238,7 @@ func setupRouter(db *gorm.DB, authDB *sql.DB, sqliteDB *sql.DB, config *config.C
label_handler.NewLabelHandler(labelService),
newsletter_handler.NewNewsletterHandler(newsletterService),
pollHandler,
server_handler.NewServerHandler(version),
server_handler.NewServerHandler(),
).AssignRoutes(r)
if config.ConnectOnStartup {
-98
View File
@@ -1,98 +0,0 @@
# Arquitetura do Sistema — EvoGO
## 1. Visão Geral
O **EvoGO** é uma distribuição independente da Evolution Go, uma API de alto desempenho construída em Go para controle e integração com instâncias do WhatsApp Web via protocolo WebSocket/Noise utilizando a biblioteca `whatsmeow`.
A aplicação atua como um gateway REST e Websocket/Eventos, permitindo que sistemas corporativos e aplicações SaaS gerenciem instâncias do WhatsApp, enviem mensagens de texto, mídias, stickers, listas interativas, botões, realizem consultas a grupos e processem webhooks em tempo real.
---
## 2. Diagrama de Arquitetura
```
┌────────────────────────────────────────────────────────┐
│ Clientes Externos │
│ (Sistemas Web, CRMs, n8n, Agentes IA) │
└───────────────────────────┬────────────────────────────┘
│ HTTP REST / WebSocket
▼
┌───────────────────────────────────────────────────────────────────────────────────┐
│ EvoGO Core │
│ │
│ ┌─────────────────────┐ ┌───────────────────────┐ ┌─────────────────────┐ │
│ │ Rotas Gin HTTP │──▶│ Auth / License Check │──▶│ Handlers (pkg/*) │ │
│ │ (pkg/routes) │ │ (pkg/core) │ │ (instance, msg, …) │ │
│ └─────────────────────┘ └───────────────────────┘ └──────────┬──────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ Services de Negócio │ │
│ │ (pkg/*/service) │ │
│ └──────────┬──────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ Whatsmeow Service │ │
│ │ (Handshake/Versão) │ │
│ └──────────┬──────────┘ │
└────────────────────────────────────────────────────────────────────┼──────────────┘
│
┌───────────────────────────────────────────┴─────────────────────────┐
│ │
▼ ▼
┌───────────────────────────────────────┐ ┌───────────────────────────────────────┐
│ WhatsApp Web Servers │ │ Bancos e Mensageria Local │
│ (Noise Protocol / WebSocket) │ │ - SQLite / PostgreSQL (Sessões) │
│ - Handshake com store.SetWAVersion│ │ - Redis / Caches de Versão / MinIO │
│ - Pairing Code e QR Code │ │ - RabbitMQ / NATS / Webhooks │
└───────────────────────────────────────┘ └───────────────────────────────────────┘
```
---
## 3. Módulos e Componentes Principais
### 3.1. `cmd/evolution-go/main.go`
- Inicializa as variáveis de ambiente e configurações globais (`pkg/config`).
- Inicializa a conexão com o banco de dados (SQLite ou PostgreSQL via GORM).
- Inicializa os serviços de mensageria (RabbitMQ, NATS, Webhooks e WebSockets).
- Configura o mecanismo de licenciamento e heartbeat (`pkg/core`).
- Inicia o servidor HTTP Gin na porta configurada (padrão: 8080).
### 3.2. `pkg/core/`
- **Validação de Runtime e Licença:** Contém a verificação de ativação via `EVOLUTION_OPERATOR_EMAIL` ou `GLOBAL_API_KEY`.
- **Middleware de Proteção:** Intercepta rotas e garante que endpoints da API retornem 503 caso o serviço ainda não esteja licenciado, permitindo apenas rotas administrativas de ativação (`/license/*`).
### 3.3. `pkg/whatsmeow/service/`
- **Abstração do Whatsmeow:** Gerencia a criação do `whatsmeow.Client`, mapeia manipuladores de eventos (`EventHandler`) para mensagens, status e presença.
- **Handshake e Resolução de Versão:** Responsável por evitar o erro `Client outdated (405)`. Realiza busca da versão do WhatsApp Web em `https://web.whatsapp.com/sw.js` com cache de 1 hora, injeta User-Agent padronizado e aplica via `store.SetWAVersion` e `store.BaseClientPayload.UserAgent.AppVersion`.
### 3.4. `pkg/instance/`
- Controla o ciclo de vida de cada número de WhatsApp conectado (instância).
- Salva o estado da conexão (`connecting`, `open`, `close`, `refused`).
- Permite pareamento via QR Code (Base64) ou código de pareamento numérico (Pairing Code).
### 3.5. `pkg/sendMessage/`
- Implementa endpoints de envio com suporte a texto, áudios convertidos (opus/ogg), imagens, vídeos, documentos PDF com prévia/thumbnail rasterizada via `poppler-utils` (`pdftoppm`), enquetes, contatos e mensagens interativas (botões e listas).
### 3.6. `manager/dist/`
- Console administrativo em frontend SPA (React/Vite) servido diretamente pelo binário em `/manager`.
---
## 4. Persistência de Dados
1. **Estado das Instâncias e Mensagens da API:**
- Suporta SQLite (`evolution.db`) para ambientes simples ou PostgreSQL para ambientes de alta concorrência.
2. **Sessões Criptográficas do WhatsApp:**
- O `whatsmeow` armazena chaves de sessão, tokens de pré-chave, registros de identidade e metadados de autenticação nas tabelas de schema do whatsmeow (`whatsmeow_device`, `whatsmeow_identity_keys`, etc.).
- As migrações de schema do whatsmeow (ex: v14 para v16) são executadas automaticamente pela biblioteca na abertura do container.
---
## 5. Práticas para Manutenção por Agentes de IA
- Ao implementar novas rotas, mantenha a separação em camadas: `handler` (validação e parsing HTTP) -> `service` (regras de negócio e chamadas whatsmeow) -> `repository` (interação com banco).
- Nunca modifique métodos do `pkg/core/` que alterem a verificação de licenciamento.
- Nunca adicione chamadas diretas de rede sem timeout configurado.
-156
View File
@@ -1,156 +0,0 @@
# Guia de Compilação e Publicação (BUILD_AND_RELEASE.md)
Este documento descreve detalhadamente o processo de compilação da aplicação, construção das imagens Docker, convenções de tags e fluxo de publicação em registry próprio.
---
## 1. Requisitos de Ambiente
- **Go:** Versão Go 1.25+ ou 1.26+ (conforme exigido pela versão do `whatsmeow` em uso).
- **CGO:** Habilitado (`CGO_ENABLED=1`) para compilação com suporte a drivers nativos e processamento de imagens/PDFs.
- **Bibliotecas nativas de sistema (Alpine/Debian):**
- `libjpeg-turbo-dev`
- `libwebp-dev`
- `poppler-utils` (`pdftoppm` para geração de thumbnails de PDF)
- `ffmpeg` (para conversão e manipulação de mídias de áudio/vídeo)
- **Docker:** Engine 24.0+ com plugin `buildx`.
---
## 2. Compilação Local
### Compilar binário para teste:
```bash
# Definir versão de compilação
VERSION=$(cat VERSION 2>/dev/null || echo "dev")
# Compilar com tags de linkagem
CGO_ENABLED=1 go build -ldflags "-X main.version=${VERSION}" -o build/evolution-go ./cmd/evolution-go
```
### Executar a suite de testes:
```bash
# Executar todos os testes
go test -v ./...
# Executar testes com detecção de data race
go test -race ./...
```
---
## 3. Construção da Imagem Docker
A construção utiliza Dockerfile multi-stage otimizado:
- **Estágio 1 (`build`):** Imagem base Go Alpine com compilador, dependências C e ferramentas de build.
- **Estágio 2 (`final`):** Imagem final Alpine mínima contendo apenas os binários, dependências de runtime (`ffmpeg`, `poppler-utils`, `libwebp`), assets estáticos do manager (`manager/dist`) e timezone.
### Comando de Build Manual:
```bash
# Exemplo para versão 0.7.2 com SHA do commit
COMMIT_SHA=$(git rev-parse --short HEAD)
VERSION=$(cat VERSION)
docker build \
--build-arg VERSION="${VERSION}-${COMMIT_SHA}" \
-t evogo:${VERSION}-${COMMIT_SHA} \
-t evogo:latest \
-f Dockerfile .
```
---
## 4. Estratégia de Registry e Publicação
### Registries Alvo:
1. **Gitea Package Registry (Recomendado):**
- Endereço: `git.jf.eng.br`
- Imagem: `git.jf.eng.br/jfeng/evogo`
- Autenticação: Utiliza o token padrão do Gitea Actions (`secrets.GITEA_TOKEN`) ou credenciais configuradas.
2. **Registry Externo (se configurado):**
- Variáveis: `REGISTRY_USER` e `REGISTRY_TOKEN`.
### Convenções de Tags:
- **Tag Imutável por Commit:** `git.jf.eng.br/jfeng/evogo:${VERSION}-${COMMIT_SHA}` (ex: `0.7.2-9337afc`)
- **Tag de Versão Semântica:** `git.jf.eng.br/jfeng/evogo:${VERSION}` (ex: `0.7.2`)
- **Tag Flutuante Estável:** `git.jf.eng.br/jfeng/evogo:latest` (atualizada **somente** após aprovação em `maintained-stable`)
- **Tag de Integração:** `git.jf.eng.br/jfeng/evogo:develop`
---
## 5. Pipeline Automatizado no Gitea Actions
O pipeline é orquestrado via `.gitea/workflows/docker-build.yml`:
1. **Push em `maintained-stable`:** build da imagem (`linux/amd64`), teste de
inicialização do binário e scan Trivy (HIGH/CRITICAL, não bloqueante).
**Não publica.**
2. **Push de tag `v<versão>` (release aprovado):** mesmo build/teste/scan e
publicação de:
- `git.jf.eng.br/jfeng/evogo:<versão>-<sha7>` (imutável)
- `git.jf.eng.br/jfeng/evogo:<versão>`
Se o commit já estiver em `maintained-stable`, promove também `latest`
e confere seu digest após publicar as imagens versionadas.
3. **`workflow_dispatch`:** publica apenas com `publish_image=true`; `:latest`
só com `promote_latest=true`.
### Gerar um release
```bash
# Após validar em maintained-develop e aprovar a promoção do commit:
git checkout maintained-stable
git pull --ff-only
# Integrar o commit validado pelo processo de revisão antes de criar a tag.
git tag -a v0.7.3-evogo.1 -m "EvoGO 0.7.3-evogo.1"
git push origin v0.7.3-evogo.1 # publica versão, tag imutável e latest
```
### Usar no docker-compose
```yaml
services:
evolution-go:
image: git.jf.eng.br/jfeng/evogo:0.7.2-evogo.1
```
Como o pacote é privado, o host precisa de `docker login git.jf.eng.br`
(usuário Gitea + token com escopo `read:package`) antes de `docker compose pull`.
Para fixar exatamente o commit testado, use a tag imutável `<versão>-<sha7>`.
### Promover para `:latest`
`.gitea/workflows/promote-latest.yml` roda quando `maintained-stable` avança:
re-etiqueta a imagem imutável do último release `v*` contido na branch
(`<versão>-<sha7>`) como `:latest`, sem recompilar (mesmo digest).
```bash
git checkout maintained-stable
git merge --ff-only v0.7.2-evogo.1
git push origin maintained-stable # dispara a promoção para :latest
```
Rollback de `:latest`: avance/reverta `maintained-stable` para o release
anterior e rode o workflow manualmente, ou fixe a tag de versão no compose.
## Atualização seletiva 0.7.3-evogo.1
Esta release preserva o fork e incorpora apenas as melhorias de inicialização
SQL da 0.7.3. Não altera o whatsmeow, o schema, o licenciamento ou as APIs.
Ordem de publicação: validar a branch de manutenção, integrar em
`maintained-develop`, validar a imagem e sessões em homologação, promover o
commit validado a `maintained-stable` e então criar a tag
`v0.7.3-evogo.1` nesse commit. A publicação exige aprovação humana.
O workflow de build executa vet e testes antes de publicar. Para pushes de tags `v*`
cujo commit esteja em `maintained-stable`, publica as tags semântica e imutável,
promove `latest` e exige que o digest remoto seja igual ao da tag imutável.
A promoção e o build compartilham o grupo de concorrência `promote-latest`.
O workflow manual também exige essa ancestralidade para `promote_latest=true`.
Uma execução verde e a igualdade dos digests são a evidência da publicação;
a existência do YAML não comprova que uma imagem foi publicada.
Rollback: registrar o digest e a tag imutável anteriormente usados por `latest`
antes da promoção. Em caso de regressão, fixar essa imagem no Compose e seguir
[ROLLBACK.md](ROLLBACK.md). Esta alteração não requer migração adicional nem
restauração do banco. Manter o snapshot anterior para recuperação operacional.
-73
View File
@@ -1,73 +0,0 @@
# Procedimento de Rollback e Recuperação (ROLLBACK.md)
Este documento descreve os passos operacionais para reverter rapidamente uma versão do **EvoGO** em caso de falha crítica em produção.
---
## 1. Condições de Disparo para Rollback
Um rollback imediato deve ser acionado nas seguintes situações:
1. **Rejeição em Massa pelo WhatsApp:** A taxa de erro na conexão ou pareamento ultrapassa 20% com respostas `405 Client Outdated`, `401 Unauthorized` ou `503 Service Unavailable`.
2. **Panic ou Reinicializações Contínuas (CrashLoop):** O container do EvoGO reinicia em loop devido a erros de runtime, falhas de I/O ou vazamento crítico de memória.
3. **Corrupção de Sessões:** Instâncias anteriormente pareadas perdem suas chaves de sessão após atualização.
4. **Regressão de Contrato de API:** Endpoints críticos de envio de mensagens falham de forma generalizada.
---
## 2. Procedimento Operacional de Rollback
### Passo 1: Identificar a Última Imagem Estável Validada
Consulte o histórico de deploys ou os registros no Gitea Package Registry.
Exemplo:
- Versão com falha: `git.jf.eng.br/jfeng/evogo:0.7.3-f8a9b2c`
- Versão estável anterior: `git.jf.eng.br/jfeng/evogo:0.7.2-9337afc`
### Passo 2: Atualização do Container / Docker Compose
No host de produção (ex: ZimaOS ou servidor Docker Swarm/Compose):
1. Edite o arquivo `docker-compose.yml`:
```yaml
services:
evolution-go:
image: git.jf.eng.br/jfeng/evogo:0.7.2-9337afc # Reverter para a tag imutável estável
```
2. Baixe a imagem anterior e reinicie o serviço:
```bash
docker compose pull evolution-go
docker compose up -d evolution-go
```
3. Verifique os logs de inicialização imediatamente:
```bash
docker compose logs -f --tail=100 evolution-go
```
---
## 3. Considerações sobre o Banco de Dados
### Sessões Whatsmeow e Schemas:
- O banco de dados armazena o schema do `whatsmeow` nas tabelas `whatsmeow_version` e associadas.
- **Atenção:** Se a versão nova executou uma migração de schema (ex: schema v14 para v16), o downgrade da biblioteca para uma versão antiga que espere schema v14 pode falhar se não houver compatibilidade reversa.
- **Boas Práticas de Prevenção:**
- Sempre realize um snapshot/backup do volume do banco de dados (`/data` ou banco PostgreSQL) antes de rodar atualizações de versão de dependência.
- Para restaurar o backup de emergência em SQLite:
```bash
cp /var/data/evolution.db.backup /var/data/evolution.db
```
---
## 4. Reversão no Git
Caso uma branch tenha sido integrada inadvertidamente em `maintained-stable`:
1. **Reverta o commit de merge:**
```bash
git checkout maintained-stable
git revert -m 1 <commit_do_merge> -m "revert: rollback da versão com falha"
git push origin maintained-stable
```
2. **Abra uma Issue no Gitea:**
- Descreva os sintomas observados, logs do erro, versão problemática e passos executados no rollback.
- Rotule como `bug` e `critical`.
-48
View File
@@ -1,48 +0,0 @@
# Diretrizes de Segurança (SECURITY.md)
Este documento estabelece os padrões e práticas de segurança aplicáveis ao fork **EvoGO**, em conformidade com as melhores práticas de desenvolvimento seguro e OWASP.
---
## 1. Gestão de Credenciais e Segredos
1. **Proibição Absoluta de Segredos no Código:**
- Nenhum token, senha de banco de dados, chave de API (`GLOBAL_API_KEY`, `AUTHENTICATION_API_KEY`) ou chave privada SSH pode ser adicionada ao repositório git.
- Utilize arquivos `.env` locais para desenvolvimento e injete variáveis de ambiente via Docker secrets ou docker-compose em produção.
2. **Prevenção de Vazamento em Logs:**
- Assegure que handlers HTTP e middlewares sanitizem cabeçalhos como `apikey`, `Authorization`, `token` e payloads de webhook antes de imprimir logs.
- Variáveis sensíveis como chaves de sessão do WhatsApp (`noise_keys`, `prekeys`) nunca devem ser expostas em logs, mesmo com `WA_DEBUG=DEBUG`.
3. **Controle de Acesso ao Repositório:**
- O repositório no Gitea deve permanecer privado.
- Apenas o proprietário e deploys autorizados possuem permissão de push.
---
## 2. Segurança de Rede e Exposição de Serviços
1. **Isolamento de Portas e Proxies:**
- O Evolution Go não deve ser exposto diretamente na internet sem um proxy reverso seguro (ex: Traefik, Nginx ou Cloudflare Tunnel) com terminação SSL/TLS (HTTPS).
- O console de gerenciamento (`/manager`) deve ter proteção adicional por IP restrito, VPN ou autenticação básica quando acessado remotamente.
2. **Conexões com o WhatsApp:**
- Toda comunicação entre o `whatsmeow` e os servidores do WhatsApp utiliza túneis criptografados via protocolo Noise sobre WebSocket (`wss://web.whatsapp.com/ws/chat`).
- Quando configurado proxy HTTP/SOCKS5 para as instâncias, certifique-se de que as credenciais do proxy sejam transmitidas de forma segura e não fiquem expostas em requisições de listagem pública.
---
## 3. Verificação Contínua de Dependências
1. **Auditoria de Módulos Go:**
- O pipeline do Gitea Actions deve executar verificações periódicas de vulnerabilidades conhecidas:
```bash
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
```
2. **Imagens Base Atualizadas:**
- O `Dockerfile` deve utilizar imagens Alpine e Go com patches de segurança recentes (ex: `golang:1.26.10-alpine` e `alpine:3.19.1+`).
---
## 4. Licenciamento e Proteção Legal
- As condições específicas da licença do Evolution Go (preservação de logotipos e avisos de direitos autorais no frontend manager) devem ser rigorosamente respeitadas.
- Qualquer alteração nos arquivos de licença ou mecanismos de validação é estritamente proibida por diretriz arquitetural.
-70
View File
@@ -1,70 +0,0 @@
# Política de Atualizações e Dependências (UPDATE_POLICY.md)
Este documento define as regras, periodicidades e critérios técnicos para aceitação, teste e incorporação de atualizações no fork **EvoGO**.
---
## 1. Classificação das Atualizações
Toda atualização deve ser classificada em uma das seguintes categorias:
### Nível 1: Emergencial / Crítica (Hotfix)
- **Cenários:** Queda geral de conexão do WhatsApp (ex: erro `Client outdated (405)`), vulnerabilidade de execução remota de código (RCE) ou corrupção de sessões.
- **Janela de Ação:** Imediata.
- **Fluxo:** Criação direta de branch `fix/<nome-do-problema>` baseada em `maintained-develop`, testes de bancada focados e geração de hotfix com deploy controlado após aprovação.
### Nível 2: Atualização de Dependência do WhatsApp (`whatsmeow`)
- **Cenários:** Novas versões da biblioteca `whatsmeow` lançadas por Tulir Asokan, contendo suporte a novos recursos do protocolo do WhatsApp ou novas revisões de schema.
- **Janela de Ação:** Semanal ou quinzenal.
- **Regra Técnica:** Verificar se há mudanças no schema do banco (ex: v14 -> v16) e na assinatura de funções públicas (ex: `UpdateBlocklist`, `GetBlocklist`, `SetStatusMessage`).
### Nível 3: Sincronização Periódica com Upstream
- **Cenários:** Novos commits na branch `main` ou `develop` do upstream oficial que trazem melhorias incrementais, novas rotas ou correções de bugs.
- **Janela de Ação:** Quinzenal ou mensal.
- **Fluxo:** Branch `maintenance/sync-upstream-<data>` -> PR para `maintained-develop`.
### Nível 4: Manutenção de Dependências Gerais (Go Modules)
- **Cenários:** Atualização de drivers (GORM, PostgreSQL, SQLite), Gin, logger, MinIO, etc.
- **Critério:** Atualizações de patches (`patch version`) são aceitas se os testes passarem. Atualizações de minor/major exigem análise de breaking changes.
---
## 2. Regras para Atualização da Biblioteca `whatsmeow`
A biblioteca `whatsmeow` é a peça central do sistema e a mais suscetível a quebras devido a mudanças nos servidores da Meta.
Ao atualizar a versão do `whatsmeow`:
1. **Investigar o histórico recente de commits do whatsmeow:**
- Acesse o repositório oficial da biblioteca: `https://github.com/tulir/whatsmeow`.
- Analise se houve alteração na versão mínima do Go (ex: migração para Go 1.26).
2. **Avaliar alterações de Schema no Banco de Dados:**
- A biblioteca whatsmeow realiza auto-migrações das tabelas do dispositivo (`device store`).
- Verifique se novas tabelas ou colunas foram adicionadas.
- **IMPORTANTE:** Bancos de dados em produção devem ter backup realizado antes da inicialização do novo container.
3. **Manter a injeção dinâmica de versão de handshake:**
- O Evolution Go deve manter a injeção em `pkg/whatsmeow/service/whatsmeow.go` (`store.SetWAVersion` e `store.BaseClientPayload.UserAgent.AppVersion`), assegurando que a versão em runtime seja respeitada mesmo que a biblioteca compilada fique temporariamente defasada.
---
## 3. Critérios de Rejeição de Atualizações
Uma atualização externa do upstream **DEVE SER REJEITADA OU BLOQUEADA** se:
- Modificar, contornar ou desativar os termos da licença Apache 2.0 / avisos de direitos autorais.
- Adicionar dependências externas não auditadas ou binários pré-compilados proprietários sem código-fonte.
- Quebrar retrocompatibilidade com endpoints existentes sem fornecer mecanismo de fallback ou versionamento de rota (`/v1`, `/v2`).
- Remover testes automatizados existentes sem justificativa técnica.
- Apresentar falhas nos testes de estresse ou memory leaks em profiling de conexões ativas.
---
## 4. Política de Versionamento de Releases
As tags e imagens Docker do EvoGO seguem o formato semântico estendido:
- **Versões estáveis:** `v0.7.2`, `v0.7.3`, etc.
- **Imagens Docker imutáveis:** `evogo:0.7.2-<commit_sha_curto>`
- **Imagens de teste (develop):** `evogo:develop-<commit_sha_curto>`
Nenhuma tag imutável já publicada em registry deve ser sobrescrita.
-140
View File
@@ -1,140 +0,0 @@
# Procedimento de Sincronização com o Upstream (UPSTREAM_SYNC.md)
Este documento estabelece o procedimento operacional padrão para rastrear, importar e integrar atualizações do repositório oficial da Evolution Foundation (`evolution-foundation/evolution-go`) em nossa distribuição independente no Gitea.
---
## 1. Configuração dos Remotos Git
O ambiente local e os runners devem estar configurados com dois remotos oficiais:
- **`origin`**: Nosso repositório no Gitea.
- SSH: `ssh://[email protected]:1080/jfeng/EvoGO.git`
- **`upstream`**: O repositório oficial no GitHub.
- HTTPS: `https://github.com/evolution-foundation/evolution-go.git`
Para verificar:
```bash
git remote -v
```
Caso necessário reconfigurar:
```bash
git remote set-url origin ssh://[email protected]:1080/jfeng/EvoGO.git
git remote add upstream https://github.com/evolution-foundation/evolution-go.git
```
---
## 2. Sincronização Automática (Gitea Actions)
O workflow `.gitea/workflows/upstream-sync-check.yml` roda todo dia às 04:00 UTC
(e sob demanda em *Actions → Sincronizacao Diaria com o Upstream → Run workflow*)
e executa `scripts/upstream-sync.sh`:
1. `git fetch upstream main --tags`.
2. Avança `upstream-sync` **somente por fast-forward** (push sem force). Se o
upstream reescrever histórico, abre Issue e para.
3. Se `maintained-develop` ainda não contém o upstream, cria
`maintenance/sync-upstream-<sha7>` **a partir de `maintained-develop`** e faz
`git merge --no-ff upstream/main`. Nossas correções ficam preservadas porque o
upstream é mesclado *por cima* do nosso código, nunca o contrário.
- **Conflito:** aborta e abre Issue com os arquivos em conflito e os comandos
para resolver (seção 3 abaixo).
- **Merge limpo:** roda `go build`, `go vet`, `go test`, faz push da branch e
abre PR para `maintained-develop` com commits novos, arquivos sensíveis
alterados (Dockerfile, go.mod, `pkg/core`, licenças) e resultado dos testes.
4. Compara o `go.mau.fi/whatsmeow` do `go.mod` com `@latest` e abre Issue quando
há versão mais nova (defasagem do whatsmeow causa o erro 405).
Mesclagem automática em `maintained-develop` (opcional): crie a variável de
repositório `AUTO_MERGE_UPSTREAM=true` (*Settings → Actions → Variables*). O PR
só é mesclado se build e testes passarem. `maintained-stable` **nunca** é tocada
pela automação; a promoção e a publicação da imagem continuam manuais.
## 3. Fluxo Manual de Sincronização
A sincronização **NUNCA** deve sobrescrever diretamente a branch `maintained-stable` ou branches ativas de desenvolvimento sem validação.
### Etapa 1: Obter novidades do upstream
```bash
git fetch upstream --tags
```
### Etapa 2: Identificar commits e tags novas
Compare nossa branch de referência `upstream-sync` com a branch `main` do upstream:
```bash
git log upstream-sync..upstream/main --oneline
git log -n 5 upstream/main --stat
```
Verifique se foram geradas novas tags:
```bash
git tag -l -n1 --sort=-v:refname | head -n 10
```
### Etapa 3: Atualizar a branch `upstream-sync`
A branch `upstream-sync` é uma cópia 1:1 do upstream. Atualize-a utilizando exclusivamente fast-forward:
```bash
git checkout upstream-sync
git merge --ff-only upstream/main
git push origin upstream-sync --tags
```
---
## 4. Integração e Análise de Impacto
### Etapa 4: Criar branch de teste e integração
A partir de `maintained-develop`, crie uma branch de manutenção específica para a atualização:
```bash
git checkout maintained-develop
git pull origin maintained-develop
git checkout -b maintenance/sync-upstream-<nova-versao>
```
### Etapa 5: Realizar o merge controlado
```bash
git merge upstream-sync
```
Se houver conflitos:
1. Examine os arquivos em conflito com `git status` e `git diff`.
2. Dê prioridade a preservar nossas melhorias arquiteturais e correções (ex: injeção de handshake no `pkg/whatsmeow/service/whatsmeow.go`, configurações de CI do Gitea).
3. Nunca utilize `git merge -X theirs` indiscriminadamente.
4. Conclua o merge com `git commit`.
---
## 5. Validação Pós-Sincronização
Antes de propor a integração para as branches mantidas:
1. **Validação do Go:**
```bash
go vet ./...
go test -v ./...
```
2. **Compilação da aplicação:**
```bash
CGO_ENABLED=1 go build -o /dev/null ./cmd/evolution-go
```
3. **Verificação de dependências (`go.mod` e `go.sum`):**
```bash
go mod verify
```
4. **Verificação de arquivos de licença e autoria:**
Confirme que `LICENSE`, `NOTICE` e avisos legais permanecem intactos.
---
## 6. Promoção para as Branches Oficiais
1. **Abra um Pull Request no Gitea:**
- Origem: `maintenance/sync-upstream-<nova-versao>`
- Destino: `maintained-develop`
- Anexe o relatório de impacto, diffs relevantes e resultado dos testes.
2. **Revisão e Aprovação:**
- O proprietário valida as mudanças e executa testes em staging.
3. **Promoção para `maintained-stable`:**
- Uma vez homologado em `maintained-develop`, realiza-se o merge para `maintained-stable` para posterior geração de imagem Docker oficial.
@@ -1,91 +0,0 @@
# Compatibilidade com o WhatsApp e Resolução do Erro 405 (WHATSAPP_COMPATIBILITY.md)
Este documento documenta o protocolo de conexão com o WhatsApp Web, o diagnóstico aprofundado do erro **`Client outdated (405)`**, a análise comparativa dos Pull Requests da comunidade e o checklist oficial de testes de compatibilidade.
---
## 1. Funcionamento do Protocolo WhatsApp Web e Versões de Cliente
O WhatsApp Web opera sobre conexões WebSocket criptografadas via protocolo Noise. Durante o handshake de estabelecimento de conexão, o cliente deve enviar um payload (`ClientPayload`) contendo sua versão de aplicação (`AppVersion` / `waVersion`).
Periodicamente, os servidores da Meta elevam o patamar mínimo aceito da versão do cliente web. Quando um cliente envia uma versão abaixo desse patamar mínimo, o servidor WhatsApp recusa o handshake imediatamente com o código de erro:
```
405 Client outdated
```
Isso impede:
- Conexão e inicialização de novas instâncias.
- Geração de QR Code e Pairing Code.
- Reconexão de sessões existentes após reinicialização do container.
---
## 2. Diagnóstico Técnico dos Pull Requests Upstream
Durante o segundo semestre de 2026, uma elevação do patamar de versão do WhatsApp causou a falha 405 generalizada. Quatro Pull Requests principais foram submetidos ao repositório oficial `evolution-foundation/evolution-go`:
### PR #226: `fix(deps): bump whatsmeow to fix "Client outdated (405)"`
- **Autor:** MayconVM
- **Modificações:**
- Atualizou o `whatsmeow` para `v0.0.0-20261102152715-54038813c47f`.
- Atualizou o Go para 1.26 (`go.mod` e `Dockerfile`).
- Corrigiu quebras de API em `user_service.go` (`UpdateBlocklist`, `GetBlocklist`, `SetStatusMessage`).
- **Limitação:** Não adicionou documentação nem tratou a injeção dinâmica de versão de handshake em runtime.
### PR #229: `fix(whatsmeow): apply store.SetWAVersion to update WhatsApp client handshake version`
- **Autor:** Comunidade
- **Modificações:**
- Identificou que o Evolution Go apenas alterava `store.DeviceProps.Version`, o que **não atualiza** o handshake do `whatsmeow`.
- Adicionou chamada explícita a `store.SetWAVersion(...)`.
- Adicionou User-Agent Chrome e timeout de 10s no `fetchWhatsAppWebVersion()` em `sw.js`.
- Adicionou fallback seguro de versão (`2.3000.1052812464`).
- **Limitação:** Feito sobre o código antigo com whatsmeow desatualizado.
### PR #230: `fix: apply fetched WhatsApp version to the handshake (Client outdated 405)`
- **Autor:** Comunidade
- **Modificações:**
- Reforçou a injeção chamando `store.SetWAVersion(next)` e `store.BaseClientPayload.UserAgent.AppVersion = next.ProtoAppVersion()`.
- Adicionou lock de mutex (`waVersionMu`) e comparação `isNewerWAVersion`.
### PR #233: `deps: bump whatsmeow to 2026-11-02 (fix 405 client outdated)`
- **Autor:** MayconVM
- **Modificações:**
- Evolução consolidada do PR #226.
- Atualizou `whatsmeow` para `2026-11-02`.
- Incluiu notas completas no `CHANGELOG.md` documentando a migração do schema SQLite de v14 para v16 e a mudança na resposta do blocklist (`Items` vs `Modifications`).
- Atualizou `Makefile`, `Dockerfile` (`golang:1.26.10-alpine`) e documentação de API (`api-user.md`).
---
## 3. Estratégia Adotada no EvoGO (`fix/client-outdated-405`)
Para garantir uma solução definitiva, robusta e que não quebre novamente na próxima atualização do WhatsApp Web, a branch `fix/client-outdated-405` combina:
1. **A base do PR #233:**
- Biblioteca `whatsmeow` atualizada para `2026-11-02`.
- Toolchain Go 1.26.
- Ajustes de API em `user_service.go`.
- Documentação e migração automática de schema.
2. **As melhorias de runtime dos PRs #229 e #230:**
- Adição de User-Agent e timeout no `fetchWhatsAppWebVersion` para evitar bloqueios ao consultar `web.whatsapp.com/sw.js`.
- Chamada a `store.SetWAVersion` e sincronização de `store.BaseClientPayload.UserAgent.AppVersion` durante o `StartClient`.
Desta forma, mesmo que novos patamares de versão do WhatsApp sejam exigidos antes de um novo rebuild do EvoGO, a aplicação busca e injeta a versão mais recente em tempo de execução automaticamente.
---
## 4. Checklist Obrigatório de Testes de Compatibilidade
Antes de promover qualquer atualização relacionada ao WhatsApp para `maintained-stable`, o seguinte checklist deve ser executado e validado em ambiente de homologação (staging):
- [ ] **1. Inicialização da Aplicação:** O container inicializa limpo, conecta ao banco e sobe o servidor HTTP sem erros de dependência ou biblioteca.
- [ ] **2. Conexão e Handshake:** A instância inicia e o handshake é aceito pelo WhatsApp com log `Applied WhatsApp handshake version`.
- [ ] **3. Geração de QR Code:** O endpoint `/instance/connect/:instance` gera o QR Code em base64 e exibe no console manager.
- [ ] **4. Pareamento por Código (Pairing Code):** O endpoint `/instance/pair/:instance` retorna o código numérico de 8 dígitos para vinculação de aparelho.
- [ ] **5. Persistência de Sessão:** As chaves de criptografia e metadados de sessão são gravados corretamente no banco de dados (`whatsmeow_device`).
- [ ] **6. Reinicialização de Container:** Ao reiniciar o container (`docker restart`), a instância reconecta automaticamente sem exigir nova leitura de QR Code.
- [ ] **7. Envio de Mensagem de Texto:** O endpoint `/message/sendText/:instance` entrega a mensagem com status de sucesso.
- [ ] **8. Envio de Mídias e Áudio:** O endpoint `/message/sendMedia/:instance` entrega imagem e áudio com conversão de formato correta.
- [ ] **9. Recebimento de Mensagens e Webhooks:** Mensagens enviadas de volta para o número pareado disparam eventos no webhook configurado.
- [ ] **10. Compatibilidade de Banco Existente:** Nenhuma instância ou histórico é perdido ao subir uma versão com schema atualizado do whatsmeow (v14 -> v16).
+13 -18
View File
@@ -404,13 +404,12 @@ Bloqueia um contato no WhatsApp.
{
"message": "success",
"data": {
"AddressingMode": "lid",
"DHash": "abc123",
"Items": [
"PrevDHash": "def456",
"Modifications": [
{
"LID": "123456789012345@lid",
"PN": "[email protected]",
"Active": true
"JID": "[email protected]",
"Action": "block"
}
]
}
@@ -453,13 +452,12 @@ Desbloqueia um contato previamente bloqueado.
{
"message": "success",
"data": {
"AddressingMode": "lid",
"DHash": "abc123",
"Items": [
"PrevDHash": "def456",
"Modifications": [
{
"LID": "123456789012345@lid",
"PN": "[email protected]",
"Active": true
"JID": "[email protected]",
"Action": "unblock"
}
]
}
@@ -494,18 +492,15 @@ apikey: SUA-CHAVE-API
{
"message": "success",
"data": {
"AddressingMode": "lid",
"DHash": "abc123",
"Items": [
"Modifications": [
{
"LID": "123456789012345@lid",
"PN": "[email protected]",
"Active": true
"JID": "[email protected]",
"Action": "block"
},
{
"LID": "987654321098765@lid",
"PN": "[email protected]",
"Active": true
"JID": "[email protected]",
"Action": "block"
}
]
}
BIN
View File
Binary file not shown.
+4 -5
View File
@@ -3,7 +3,6 @@ package call_service
import (
"context"
"errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -19,7 +18,7 @@ type CallService interface {
}
type callService struct {
clientPointer *safemap.Map[*whatsmeow.Client]
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
@@ -30,7 +29,7 @@ type RejectCallStruct struct {
}
func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer.Get(instanceId)
client := c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
@@ -44,7 +43,7 @@ func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = c.clientPointer.Get(instanceId)
client = c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
@@ -84,7 +83,7 @@ func (c *callService) RejectCall(data *RejectCallStruct, instance *instance_mode
}
func NewCallService(
clientPointer *safemap.Map[*whatsmeow.Client],
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) CallService {
+4 -5
View File
@@ -3,7 +3,6 @@ package chat_service
import (
"context"
"errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -26,7 +25,7 @@ type ChatService interface {
}
type chatService struct {
clientPointer *safemap.Map[*whatsmeow.Client]
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
@@ -41,7 +40,7 @@ type HistorySyncRequestStruct struct {
}
func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer.Get(instanceId)
client := c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
@@ -55,7 +54,7 @@ func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = c.clientPointer.Get(instanceId)
client = c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
@@ -245,7 +244,7 @@ func (c *chatService) HistorySyncRequest(data *HistorySyncRequestStruct, instanc
}
func NewChatService(
clientPointer *safemap.Map[*whatsmeow.Client],
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) ChatService {
+4 -5
View File
@@ -3,7 +3,6 @@ package community_service
import (
"context"
"errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -22,7 +21,7 @@ type CommunityService interface {
}
type communityService struct {
clientPointer *safemap.Map[*whatsmeow.Client]
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
@@ -37,7 +36,7 @@ type AddParticipantStruct struct {
}
func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer.Get(instanceId)
client := c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
@@ -51,7 +50,7 @@ func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = c.clientPointer.Get(instanceId)
client = c.clientPointer[instanceId]
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
@@ -158,7 +157,7 @@ func (c *communityService) CommunityRemove(data *AddParticipantStruct, instance
}
func NewCommunityService(
clientPointer *safemap.Map[*whatsmeow.Client],
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) CommunityService {
+2 -1
View File
@@ -10,7 +10,8 @@ import (
"time"
"github.com/gomessguii/logger"
// Register the auth database driver independently of the WhatsApp service.
// The binary's only registration of the "postgres" driver. Without it the
// build still passes and sql.Open("postgres") fails at boot.
_ "github.com/lib/pq"
"gorm.io/driver/postgres"
"gorm.io/gorm"
+2 -1
View File
@@ -6,8 +6,9 @@ import (
"testing"
)
// The only guard for the lib/pq import: build and vet pass without it.
func TestPostgresDriverRegistered(t *testing.T) {
if !slices.Contains(sql.Drivers(), "postgres") {
t.Fatalf("postgres driver not registered: %v", sql.Drivers())
t.Fatalf("driver \"postgres\" not registered; sql.Drivers() = %v", sql.Drivers())
}
}
+248 -248
View File
File diff suppressed because it is too large. Load diff
-10
View File
@@ -5,7 +5,6 @@ import (
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/gomessguii/logger"
"github.com/nats-io/nats.go"
"strings"
)
type natsProducer struct {
@@ -21,15 +20,6 @@ func NewNatsProducer(
natsGlobalEvents []string,
loggerWrapper *logger_wrapper.LoggerManager,
) producer_interfaces.Producer {
if strings.TrimSpace(url) == "" {
return &natsProducer{
conn: nil,
natsGlobalEnabled: false,
natsGlobalEvents: nil,
loggerWrapper: loggerWrapper,
}
}
conn, err := nats.Connect(url)
if err != nil {
logger.LogError("Failed to connect to NATS: %v", err)
-31
View File
@@ -1,31 +0,0 @@
package nats_producer
import "testing"
func TestNewNatsProducerDoesNotConnectWithoutURL(t *testing.T) {
tests := []struct {
name string
url string
}{
{"Empty URL", ""},
{"Whitespace URL", " "},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
producer, ok := NewNatsProducer(tt.url, true, []string{"event1"}, nil).(*natsProducer)
if !ok {
t.Fatal("constructor returned an unexpected producer type")
}
if producer.conn != nil {
t.Fatal("NATS connection must stay nil when NATS_URL is empty")
}
if producer.natsGlobalEnabled {
t.Fatal("NATS global publishing must stay disabled without a URL")
}
if producer.natsGlobalEvents != nil {
t.Fatal("natsGlobalEvents must be nil when NATS_URL is empty")
}
})
}
}
+60 -113
View File
@@ -14,131 +14,92 @@ var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
logger.LogInfo("Verificando origem da conexão WebSocket")
return true
},
}
// client wraps a connection together with its own write mutex.
//
// gorilla/websocket permits only one concurrent writer per connection, and
// events are dispatched from independent goroutines (see the `go CallWebhook`
// calls in the whatsmeow event handler), so two events arriving at once used to
// race on the same socket. Serialising per connection removes that.
type client struct {
conn *websocket.Conn
mu sync.Mutex
}
func (c *client) writeJSON(v interface{}) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.conn.WriteJSON(v)
}
type websocketProducer struct {
// clients holds every connection subscribed to a given instance. This is a
// slice, not a single connection: previously a second subscriber replaced the
// first, so opening the UI in two tabs silently cut delivery to the older one,
// and either tab disconnecting removed the whole instance entry.
clients map[string][]*client
broadcast []*client
clients map[string]*websocket.Conn // conexões específicas por instância
broadcast []*websocket.Conn // conexões que recebem todos os eventos
clientsMux sync.RWMutex
loggerWrapper *logger_wrapper.LoggerManager
}
func NewWebsocketProducer(loggerWrapper *logger_wrapper.LoggerManager) *websocketProducer {
return &websocketProducer{
clients: make(map[string][]*client),
broadcast: make([]*client, 0),
clients: make(map[string]*websocket.Conn),
broadcast: make([]*websocket.Conn, 0),
clientsMux: sync.RWMutex{},
loggerWrapper: loggerWrapper,
}
}
// ServeWs upgrades an HTTP request and registers it for the lifetime of the
// connection. An empty instanceId subscribes to every instance's events.
// ServeWs lida com as requisições de upgrade para websocket
func ServeWs(w http.ResponseWriter, r *http.Request, instanceId string, producer *websocketProducer) {
logger.LogInfo("Iniciando upgrade da conexão WebSocket")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.LogError("Erro ao fazer upgrade da conexão websocket: %v", err)
return
}
c := &client{conn: conn}
logger.LogInfo("Conexão WebSocket estabelecida com sucesso")
if instanceId == "" {
producer.addBroadcastClient(c)
producer.AddBroadcastClient(conn)
} else {
producer.addClient(instanceId, c)
producer.AddClient(instanceId, conn)
}
// The read loop exists purely to notice a closed socket; inbound frames are
// ignored. Deregistration is keyed on this exact connection so sibling
// subscribers of the same instance keep receiving events.
// Goroutine para limpar conexão quando fechada
go func() {
defer func() {
if instanceId == "" {
producer.removeBroadcastClient(c)
} else {
producer.removeClient(instanceId, c)
}
_ = conn.Close()
}()
for {
if _, _, err := conn.ReadMessage(); err != nil {
return
_, _, err := conn.ReadMessage()
if err != nil {
if instanceId == "" {
producer.RemoveBroadcastClient(conn)
} else {
producer.RemoveClient(instanceId)
}
conn.Close()
break
}
}
}()
}
func (p *websocketProducer) addBroadcastClient(c *client) {
func (p *websocketProducer) AddBroadcastClient(conn *websocket.Conn) {
p.clientsMux.Lock()
p.broadcast = append(p.broadcast, c)
n := len(p.broadcast)
p.clientsMux.Unlock()
logger.LogInfo("Cliente broadcast websocket adicionado (total: %d)", n)
defer p.clientsMux.Unlock()
p.broadcast = append(p.broadcast, conn)
logger.LogInfo("Cliente broadcast websocket adicionado")
}
func (p *websocketProducer) removeBroadcastClient(c *client) {
func (p *websocketProducer) RemoveBroadcastClient(conn *websocket.Conn) {
p.clientsMux.Lock()
p.broadcast = drop(p.broadcast, c)
n := len(p.broadcast)
p.clientsMux.Unlock()
logger.LogInfo("Cliente broadcast websocket removido (total: %d)", n)
defer p.clientsMux.Unlock()
for i, c := range p.broadcast {
if c == conn {
p.broadcast = append(p.broadcast[:i], p.broadcast[i+1:]...)
break
}
}
logger.LogInfo("Cliente broadcast websocket removido")
}
func (p *websocketProducer) addClient(instanceID string, c *client) {
func (p *websocketProducer) AddClient(instanceID string, conn *websocket.Conn) {
p.clientsMux.Lock()
p.clients[instanceID] = append(p.clients[instanceID], c)
n := len(p.clients[instanceID])
p.clientsMux.Unlock()
p.loggerWrapper.GetLogger(instanceID).LogInfo(
"Cliente websocket adicionado para instância: %s (total: %d)", instanceID, n)
defer p.clientsMux.Unlock()
p.clients[instanceID] = conn
p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket adicionado para instância: %s", instanceID)
}
func (p *websocketProducer) removeClient(instanceID string, c *client) {
func (p *websocketProducer) RemoveClient(instanceID string) {
p.clientsMux.Lock()
remaining := drop(p.clients[instanceID], c)
if len(remaining) == 0 {
defer p.clientsMux.Unlock()
delete(p.clients, instanceID)
} else {
p.clients[instanceID] = remaining
}
p.clientsMux.Unlock()
p.loggerWrapper.GetLogger(instanceID).LogInfo(
"Cliente websocket removido para instância: %s (restantes: %d)", instanceID, len(remaining))
}
// drop returns a new slice without target. It allocates rather than filtering in
// place, so a snapshot taken by a concurrent Produce can never observe a mutated
// backing array.
func drop(list []*client, target *client) []*client {
out := make([]*client, 0, len(list))
for _, c := range list {
if c != target {
out = append(out, c)
}
}
return out
p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket removido para instância: %s", instanceID)
}
func (p *websocketProducer) Produce(queueName string, payload []byte, instanceID string, _ string) error {
@@ -147,43 +108,29 @@ func (p *websocketProducer) Produce(queueName string, payload []byte, instanceID
"payload": string(payload),
}
// Snapshot under the lock, then write outside it: a slow or half-open socket
// must not block other instances' deliveries.
p.clientsMux.RLock()
targets := append([]*client(nil), p.clients[instanceID]...)
targets = append(targets, p.broadcast...)
p.clientsMux.RUnlock()
defer p.clientsMux.RUnlock()
var failed []*client
for _, c := range targets {
if err := c.writeJSON(message); err != nil {
p.loggerWrapper.GetLogger(instanceID).LogError(
"Erro ao enviar mensagem websocket para %s: %v", instanceID, err)
failed = append(failed, c)
// Envia para cliente específico da instância
if client, exists := p.clients[instanceID]; exists {
err := client.WriteJSON(message)
if err != nil {
p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem websocket para %s: %v", instanceID, err)
// Não remove o cliente aqui pois estamos com o RLock
return err
}
p.loggerWrapper.GetLogger(instanceID).LogInfo("Mensagem websocket enviada com sucesso para instância %s na fila %s", instanceID, queueName)
}
// Envia para todos os clientes broadcast
for _, conn := range p.broadcast {
err := conn.WriteJSON(message)
if err != nil {
p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem broadcast websocket: %v", err)
continue
}
}
if len(failed) > 0 {
p.clientsMux.Lock()
for _, c := range failed {
if remaining := drop(p.clients[instanceID], c); len(remaining) == 0 {
delete(p.clients, instanceID)
} else {
p.clients[instanceID] = remaining
}
p.broadcast = drop(p.broadcast, c)
}
p.clientsMux.Unlock()
}
if n := len(targets) - len(failed); n > 0 {
p.loggerWrapper.GetLogger(instanceID).LogInfo(
"Mensagem websocket enviada para %d cliente(s) da instância %s na fila %s", n, instanceID, queueName)
}
// Deliberately nil even when a write failed. sendToQueueOrWebhook aborts the
// remaining producers on error, so reporting a dead browser tab here would
// silently suppress RabbitMQ/NATS/webhook delivery for the same event.
return nil
}
+4 -5
View File
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"io"
"net/http"
"strings"
@@ -38,7 +37,7 @@ type GroupService interface {
}
type groupService struct {
clientPointer *safemap.Map[*whatsmeow.Client]
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
@@ -118,7 +117,7 @@ type UpdateGroupRequestParticipantsStruct struct {
}
func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := g.clientPointer.Get(instanceId)
client := g.clientPointer[instanceId]
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
@@ -132,7 +131,7 @@ func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Clie
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = g.clientPointer.Get(instanceId)
client = g.clientPointer[instanceId]
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
@@ -642,7 +641,7 @@ func (g *groupService) UpdateGroupRequestParticipants(data *UpdateGroupRequestPa
}
func NewGroupService(
clientPointer *safemap.Map[*whatsmeow.Client],
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) GroupService {
+55 -49
View File
@@ -7,7 +7,6 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"os"
"path/filepath"
"slices"
@@ -51,8 +50,8 @@ type InstanceService interface {
type instances struct {
instanceRepository instance_repository.InstanceRepository
config *config.Config
killChannel *safemap.Map[chan bool]
clientPointer *safemap.Map[*whatsmeow.Client]
killChannel map[string](chan bool)
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
@@ -125,7 +124,7 @@ type ForceReconnectStruct struct {
func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
logger := i.loggerWrapper.GetLogger(instanceId)
client := i.clientPointer.Get(instanceId)
client := i.clientPointer[instanceId]
logger.LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
@@ -139,7 +138,7 @@ func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client,
logger.LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = i.clientPointer.Get(instanceId)
client = i.clientPointer[instanceId]
logger.LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
@@ -243,7 +242,7 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
}
// Verifica se a instância já está rodando
isInstanceRunning := i.clientPointer.Get(instance.Id) != nil
isInstanceRunning := i.clientPointer[instance.Id] != nil
// Sincroniza as configurações na instância em execução (se já estiver conectada)
err = i.whatsmeowService.UpdateInstanceSettings(instance.Id)
@@ -259,7 +258,7 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
if !isInstanceRunning {
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting new client instance", instance.Id)
i.killChannel.Set(instance.Id, make(chan bool))
i.killChannel[instance.Id] = make(chan bool)
clientData := &whatsmeow_service.ClientData{
Instance: instance,
@@ -289,8 +288,8 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
// logger.LogInfo("Waiting 1 seconds")
// time.Sleep(1000 * time.Millisecond)
// if i.clientPointer.Get(instance.Id) != nil {
// if !i.clientPointer.Get(instance.Id).IsConnected() {
// if i.clientPointer[instance.Id] != nil {
// if !i.clientPointer[instance.Id].IsConnected() {
// return instance, "", "", fmt.Errorf("failed to connect")
// }
// } else {
@@ -318,14 +317,12 @@ func (i instances) Disconnect(instance *instance_model.Instance) (*instance_mode
if client.IsConnected() {
if client.IsLoggedIn() {
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
safemap.TrySend(i.killChannel.Get(instance.Id), true)
i.killChannel[instance.Id] <- true
// Do not clear instance.Events on disconnect (upstream PR #187): an
// empty events string makes CallWebhook drop every webhook after the
// instance reconnects.
instance.Connected = false
instance.DisconnectReason = "Disconnected by API"
if err := i.instanceRepository.UpdateConnected(instance.Id, false, instance.DisconnectReason); err != nil {
instance.Events = ""
err := i.instanceRepository.Update(instance)
if err != nil {
return instance, err
}
@@ -355,10 +352,13 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
return instance, err
}
safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
select {
case i.killChannel[instance.Id] <- true:
case <-time.After(5 * time.Second):
}
i.clientPointer.Delete(instance.Id)
i.killChannel.Delete(instance.Id)
delete(i.clientPointer, instance.Id)
delete(i.killChannel, instance.Id)
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Logout successful", instance.Id)
return instance, nil
@@ -367,10 +367,13 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
if client.IsConnected() {
client.Disconnect()
safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
select {
case i.killChannel[instance.Id] <- true:
case <-time.After(5 * time.Second):
}
i.clientPointer.Delete(instance.Id)
i.killChannel.Delete(instance.Id)
delete(i.clientPointer, instance.Id)
delete(i.killChannel, instance.Id)
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
return instance, nil
@@ -381,7 +384,7 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
}
func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, error) {
client := i.clientPointer.Get(instance.Id)
client := i.clientPointer[instance.Id]
if client == nil {
return &StatusStruct{
@@ -410,7 +413,7 @@ func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, err
func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, error) {
logger := i.loggerWrapper.GetLogger(instance.Id)
client := i.clientPointer.Get(instance.Id)
client := i.clientPointer[instance.Id]
// Se não há cliente ou o cliente está logado, precisamos iniciar um novo cliente
if client == nil || client.IsLoggedIn() {
@@ -432,7 +435,7 @@ func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, erro
time.Sleep(3 * time.Second)
// Verificar novamente se há cliente
client = i.clientPointer.Get(instance.Id)
client = i.clientPointer[instance.Id]
if client != nil && client.IsLoggedIn() {
return nil, fmt.Errorf("session already logged in")
}
@@ -508,7 +511,7 @@ func buildPasskeyOpenURL(token string) string {
func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error) {
logger := i.loggerWrapper.GetLogger(instance.Id)
client := i.clientPointer.Get(instance.Id)
client := i.clientPointer[instance.Id]
if client == nil || !client.IsConnected() {
if client != nil && client.IsLoggedIn() {
@@ -522,7 +525,7 @@ func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*P
// Wait for the WA websocket connection and initial QR generation to establish.
// PairPhone must be called after the QR event is received per whatsmeow docs.
time.Sleep(3 * time.Second)
client = i.clientPointer.Get(instance.Id)
client = i.clientPointer[instance.Id]
if client == nil {
return nil, fmt.Errorf("failed to initialize client for pairing")
}
@@ -548,7 +551,7 @@ func (i instances) GetAll() ([]*instance_model.Instance, error) {
}
for _, instance := range instances {
if client := i.clientPointer.Get(instance.Id); client != nil {
if client := i.clientPointer[instance.Id]; client != nil {
instance.Connected = client.IsLoggedIn()
} else {
instance.Connected = false
@@ -567,7 +570,7 @@ func (i instances) Info(instanceId string) (*instance_model.Instance, error) {
}
// Atualiza o status connected com base no estado real do cliente
if client := i.clientPointer.Get(instance.Id); client != nil {
if client := i.clientPointer[instance.Id]; client != nil {
instance.Connected = client.IsLoggedIn()
} else {
instance.Connected = false
@@ -584,18 +587,18 @@ func (i instances) Delete(id string) error {
return err
}
if i.clientPointer.Get(instance.Id) != nil && i.clientPointer.Get(instance.Id).IsConnected() {
if i.clientPointer.Get(instance.Id).IsLoggedIn() {
i.clientPointer.Get(instance.Id).Logout(context.Background())
if i.clientPointer[instance.Id] != nil && i.clientPointer[instance.Id].IsConnected() {
if i.clientPointer[instance.Id].IsLoggedIn() {
i.clientPointer[instance.Id].Logout(context.Background())
}
i.clientPointer.Get(instance.Id).Disconnect()
i.clientPointer[instance.Id].Disconnect()
}
// Limpar todos os recursos da instância antes de deletar
i.clientPointer.Delete(instance.Id)
if i.killChannel.Get(instance.Id) != nil {
close(i.killChannel.Get(instance.Id))
i.killChannel.Delete(instance.Id)
delete(i.clientPointer, instance.Id)
if i.killChannel[instance.Id] != nil {
close(i.killChannel[instance.Id])
delete(i.killChannel, instance.Id)
}
// Limpar cache via whatsmeow service
@@ -694,7 +697,7 @@ func (i instances) RemoveProxy(id string) error {
}
func (i instances) ForceReconnect(instanceId string, number string) error {
if i.clientPointer.Get(instanceId).IsConnected() && i.clientPointer.Get(instanceId).IsLoggedIn() {
if i.clientPointer[instanceId].IsConnected() && i.clientPointer[instanceId].IsLoggedIn() {
return fmt.Errorf("client already connected")
}
@@ -710,7 +713,7 @@ func (i instances) ForceReconnect(instanceId string, number string) error {
subscribedEvents := strings.Split(instance.Events, ",")
i.killChannel.Set(instance.Id, make(chan bool))
i.killChannel[instance.Id] = make(chan bool)
clientData := &whatsmeow_service.ClientData{
Instance: instance,
@@ -732,26 +735,29 @@ func (i instances) ForceReconnect(instanceId string, number string) error {
}
}
if i.clientPointer.Get(instance.Id) != nil {
client := i.clientPointer.Get(instance.Id)
if i.clientPointer[instance.Id] != nil {
client := i.clientPointer[instance.Id]
client.Disconnect()
safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
select {
case i.killChannel[instance.Id] <- true:
case <-time.After(5 * time.Second):
}
i.clientPointer.Delete(instance.Id)
i.killChannel.Delete(instance.Id)
delete(i.clientPointer, instance.Id)
delete(i.killChannel, instance.Id)
}
go i.whatsmeowService.StartClient(clientData)
time.Sleep(2 * time.Second)
if i.clientPointer.Get(instance.Id) != nil {
if !i.clientPointer.Get(instance.Id).IsConnected() {
if i.clientPointer[instance.Id] != nil {
if !i.clientPointer[instance.Id].IsConnected() {
return fmt.Errorf("failed to connect")
}
if !i.clientPointer.Get(instance.Id).IsLoggedIn() {
if !i.clientPointer[instance.Id].IsLoggedIn() {
return fmt.Errorf("failed to login")
}
} else {
@@ -906,8 +912,8 @@ func (i instances) UpdateAdvancedSettings(instanceId string, settings *instance_
func NewInstanceService(
instanceRepository instance_repository.InstanceRepository,
killChannel *safemap.Map[chan bool],
clientPointer *safemap.Map[*whatsmeow.Client],
killChannel map[string](chan bool),
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
config *config.Config,
loggerWrapper *logger_wrapper.LoggerManager,
+4 -5
View File
@@ -3,7 +3,6 @@ package label_service
import (
"context"
"errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -26,7 +25,7 @@ type LabelService interface {
}
type labelService struct {
clientPointer *safemap.Map[*whatsmeow.Client]
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
labelRepository label_repository.LabelRepository
loggerWrapper *logger_wrapper.LoggerManager
@@ -51,7 +50,7 @@ type EditLabelStruct struct {
}
func (l *labelService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := l.clientPointer.Get(instanceId)
client := l.clientPointer[instanceId]
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
@@ -65,7 +64,7 @@ func (l *labelService) ensureClientConnected(instanceId string) (*whatsmeow.Clie
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = l.clientPointer.Get(instanceId)
client = l.clientPointer[instanceId]
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
@@ -227,7 +226,7 @@ func (l *labelService) GetLabels(instance *instance_model.Instance) ([]label_mod
}
func NewLabelService(
clientPointer *safemap.Map[*whatsmeow.Client],
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
labelRepository label_repository.LabelRepository,
loggerWrapper *logger_wrapper.LoggerManager,
+4 -5
View File
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"net/http"
"os"
"strings"
@@ -36,7 +35,7 @@ type MessageService interface {
}
type messageService struct {
clientPointer *safemap.Map[*whatsmeow.Client]
clientPointer map[string]*whatsmeow.Client
messageRepository message_repository.MessageRepository
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
@@ -96,7 +95,7 @@ type MessageSendStruct struct {
}
func (m *messageService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := m.clientPointer.Get(instanceId)
client := m.clientPointer[instanceId]
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
@@ -110,7 +109,7 @@ func (m *messageService) ensureClientConnected(instanceId string) (*whatsmeow.Cl
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = m.clientPointer.Get(instanceId)
client = m.clientPointer[instanceId]
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
@@ -527,7 +526,7 @@ func (m *messageService) EditMessage(data *EditMessageStruct, instance *instance
}
func NewMessageService(
clientPointer *safemap.Map[*whatsmeow.Client],
clientPointer map[string]*whatsmeow.Client,
messageRepository message_repository.MessageRepository,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
+4 -5
View File
@@ -3,7 +3,6 @@ package newsletter_service
import (
"context"
"errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -23,7 +22,7 @@ type NewsletterService interface {
}
type newsletterService struct {
clientPointer *safemap.Map[*whatsmeow.Client]
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
@@ -48,7 +47,7 @@ type GetNewsletterMessagesStruct struct {
}
func (n *newsletterService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := n.clientPointer.Get(instanceId)
client := n.clientPointer[instanceId]
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
@@ -62,7 +61,7 @@ func (n *newsletterService) ensureClientConnected(instanceId string) (*whatsmeow
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = n.clientPointer.Get(instanceId)
client = n.clientPointer[instanceId]
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
@@ -196,7 +195,7 @@ func (n *newsletterService) GetNewsletterMessages(data *GetNewsletterMessagesStr
}
func NewNewsletterService(
clientPointer *safemap.Map[*whatsmeow.Client],
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) NewsletterService {
-150
View File
@@ -1,150 +0,0 @@
// Package safemap holds the process-wide maps that are shared across goroutines.
//
// # WHY THIS EXISTS
//
// The three state maps of the process (clientPointer, myClientPointer and
// killChannel) are created once at startup and passed BY REFERENCE into eleven
// packages. Every one of them read and wrote those maps directly, from different
// goroutines, with no synchronisation at all.
//
// Go does not tolerate that. Concurrent writes do not corrupt silently: the
// runtime kills the process with
//
// fatal error: concurrent map writes
//
// and a fatal error is NOT recoverable — a deferred recover() does not catch it.
//
// Measured in production: a process died at StartClient while five instances
// were connecting at the same time. The container orchestrator brought it back
// within seconds, but every number was offline in the meantime, and it repeats
// on every restart that brings up more than a couple of instances at once.
//
// # WHY A SEPARATE PACKAGE, AND WHY GENERICS
//
// MyClient lives in pkg/whatsmeow/service. If the safe type lived there, the
// other ten packages would have to import that package and an import cycle
// would appear. This package has no internal dependencies — only the standard
// library — so anything can use it.
package safemap
import (
"sync"
"time"
)
// Map is a map[string]T guarded by a read/write mutex.
//
// Always use the pointer (*Map[T]): copying the struct would copy the mutex,
// and a copied mutex stops protecting the original — two owners, one lock each,
// and the race comes back silently.
type Map[T any] struct {
mu sync.RWMutex
m map[string]T
}
// New returns an empty map, ready to use.
func New[T any]() *Map[T] {
return &Map[T]{m: make(map[string]T)}
}
// Get returns the value, or the zero value of T when the key is absent —
// exactly like the m[k] it replaces, so swapping call sites changes no
// behaviour.
func (s *Map[T]) Get(k string) T {
s.mu.RLock()
defer s.mu.RUnlock()
return s.m[k]
}
// Lookup is the v, ok := m[k] form.
func (s *Map[T]) Lookup(k string) (T, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
v, ok := s.m[k]
return v, ok
}
// Set is the m[k] = v form.
func (s *Map[T]) Set(k string, v T) {
s.mu.Lock()
defer s.mu.Unlock()
s.m[k] = v
}
// Delete is the delete(m, k) form.
func (s *Map[T]) Delete(k string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.m, k)
}
// Len is the len(m) form.
func (s *Map[T]) Len() int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.m)
}
// Snapshot returns a copy for range loops.
//
// Ranging over the map from the inside would hold the lock for the whole loop,
// and the loop bodies here talk to WhatsApp — the lock would be held across
// network calls. The snapshot costs one copy of the pointers and releases the
// lock immediately.
func (s *Map[T]) Snapshot() map[string]T {
s.mu.RLock()
defer s.mu.RUnlock()
out := make(map[string]T, len(s.m))
for k, v := range s.m {
out[k] = v
}
return out
}
// TrySend delivers v on ch and reports whether it was delivered.
//
// The kill channels are closed when an instance is deleted, and a goroutine
// that still holds a reference (QR timeout, Disconnected handler) used to
// panic with "send on closed channel", taking the whole process down
// (upstream issue #222). A nil channel (instance already removed from the map)
// would block forever, so it is reported as not delivered instead.
func TrySend[T any](ch chan T, v T) (ok bool) {
if ch == nil {
return false
}
defer func() {
if recover() != nil {
ok = false
}
}()
ch <- v
return true
}
// TrySendTimeout is TrySend bounded by d. A d of zero makes it non-blocking.
func TrySendTimeout[T any](ch chan T, v T, d time.Duration) (ok bool) {
if ch == nil {
return false
}
defer func() {
if recover() != nil {
ok = false
}
}()
if d <= 0 {
select {
case ch <- v:
return true
default:
return false
}
}
timer := time.NewTimer(d)
defer timer.Stop()
select {
case ch <- v:
return true
case <-timer.C:
return false
}
}
-71
View File
@@ -1,71 +0,0 @@
package safemap
import (
"sync"
"testing"
)
// TestPlainMapRaces is the calibration test: it proves the detector can see the
// bug in the first place.
//
// It drives a plain Go map the way this code used to — N goroutines writing the
// same key. Under -race the detector flags it. Without -race the runtime kills
// the process with "fatal error: concurrent map writes", which is exactly the
// failure this package exists to prevent.
//
// Skipped by default precisely because that failure is not recoverable and
// would take the whole suite down. Run it on purpose to confirm the detector is
// not blind:
//
// go test -race -run TestPlainMapRaces ./pkg/safemap/
func TestPlainMapRaces(t *testing.T) {
t.Skip("calibration: run by hand — see the comment above")
m := map[string]int{}
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
m["key"] = n // <- the race
}(i)
}
wg.Wait()
}
// TestConcurrentAccess runs the same exercise through the guarded map: fifty
// goroutines writing, reading and ranging over the same key at once — the shape
// of a startup where several instances connect simultaneously.
func TestConcurrentAccess(t *testing.T) {
m := New[int]()
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(3)
go func(n int) { defer wg.Done(); m.Set("key", n) }(i)
go func() { defer wg.Done(); _ = m.Get("key") }()
go func() {
defer wg.Done()
_, _ = m.Lookup("key")
_ = m.Len()
for range m.Snapshot() {
}
}()
}
wg.Wait()
if _, ok := m.Lookup("key"); !ok {
t.Fatal("key should still be in the map")
}
}
// TestGetMissingKeyReturnsZero pins the behaviour the call sites relied on:
// m[k] on an absent key yields the zero value, and Get must do the same —
// otherwise swapping the call sites would have changed logic silently.
func TestGetMissingKeyReturnsZero(t *testing.T) {
if v := New[*int]().Get("absent"); v != nil {
t.Fatalf("want nil, got %v", v)
}
if n := New[int]().Get("absent"); n != 0 {
t.Fatalf("want 0, got %d", n)
}
}
+15 -95
View File
@@ -8,7 +8,6 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"image"
"image/jpeg"
"image/png"
@@ -54,7 +53,7 @@ type SendService interface {
}
type sendService struct {
clientPointer *safemap.Map[*whatsmeow.Client]
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
config *config.Config
loggerWrapper *logger_wrapper.LoggerManager
@@ -381,7 +380,7 @@ type MessageSendStruct struct {
}
func (s *sendService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := s.clientPointer.Get(instanceId)
client := s.clientPointer[instanceId]
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
@@ -395,7 +394,7 @@ func (s *sendService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = s.clientPointer.Get(instanceId)
client = s.clientPointer[instanceId]
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
@@ -531,30 +530,11 @@ func (s *sendService) validateAndCheckUserExists(phone string, formatJid *bool,
return types.NewJID("", types.DefaultUserServer), fmt.Errorf("failed to connect client: %v", err)
}
// Brazilian mobiles: ask WhatsApp for both forms (with and without the 9th
// digit) and use the one that is registered.
if variants := utils.BRPhoneVariants(phone); len(variants) > 1 {
if remoteJID, found := s.checkBRPhoneVariants(client, variants, instance.Id); found {
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Number %s verified as valid WhatsApp user, using remoteJID: %s", instance.Id, phone, remoteJID)
formatJidFalse := false
return validateMessageFields(remoteJID, &formatJidFalse, messageID, participant)
}
}
// Use CheckUser approach: formatJid=false by default
formatJidForCheck := false
// First attempt with formatJid=false
remoteJID, found, err := s.checkSingleUserExists(client, phone, formatJidForCheck, instance.Id)
if err != nil || !found {
// Integrations often store the contact's LID as if it were a phone
// number. If it is a LID this device already knows, send to it directly.
if lid, ok := s.knownLID(client, phone, instance.Id); ok {
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Number %s is a known LID, sending to %s", instance.Id, phone, lid)
formatJidFalse := false
return validateMessageFields(lid.String(), &formatJidFalse, messageID, participant)
}
}
if err != nil {
s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Failed to check user existence: %v", instance.Id, err)
// Continue with sending even if check fails (network issues, etc.)
@@ -611,66 +591,6 @@ func (s *sendService) checkSingleUserExists(client *whatsmeow.Client, phone stri
return remoteJID, true, nil
}
// knownLID reports whether phone is actually a LID with a phone number mapping
// in the local store, returning it as a @lid JID.
func (s *sendService) knownLID(client *whatsmeow.Client, phone string, instanceId string) (types.JID, bool) {
if client.Store == nil || client.Store.LIDs == nil {
return types.JID{}, false
}
user := utils.LIDCandidate(phone)
if user == "" {
return types.JID{}, false
}
lid := types.NewJID(user, types.HiddenUserServer)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
pn, err := client.Store.LIDs.GetPNForLID(ctx, lid)
if err != nil {
s.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Failed to look up LID %s: %v", instanceId, lid, err)
return types.JID{}, false
}
if pn.IsEmpty() {
return types.JID{}, false
}
return lid, true
}
// checkBRPhoneVariants queries every variant in a single IsOnWhatsApp call and
// returns the JID of the first one that is registered, in the given order.
// Errors are logged and reported as not found so the regular check still runs.
func (s *sendService) checkBRPhoneVariants(client *whatsmeow.Client, variants []string, instanceId string) (string, bool) {
phones := make([]string, len(variants))
for i, v := range variants {
phones[i] = "+" + v
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
resp, err := client.IsOnWhatsApp(ctx, phones)
if err != nil {
s.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Failed to check BR number variants %v: %v", instanceId, variants, err)
return "", false
}
for _, v := range variants {
for _, r := range resp {
if r.IsIn && strings.TrimPrefix(r.Query, "+") == v {
return r.JID.String(), true
}
}
}
// Query not echoed back as sent: any registered result is one of our variants.
for _, r := range resp {
if r.IsIn {
return r.JID.String(), true
}
}
return "", false
}
func findURL(text string) string {
urlRegex := `http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+`
re := regexp.MustCompile(urlRegex)
@@ -2440,7 +2360,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
var message string
if data.Id == "" {
message = s.clientPointer.Get(instance.Id).GenerateMessageID()
message = s.clientPointer[instance.Id].GenerateMessageID()
} else {
message = data.Id
}
@@ -2451,14 +2371,14 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
media = "audio"
}
err := s.clientPointer.Get(instance.Id).SendChatPresence(context.Background(), recipient, types.ChatPresence("composing"), types.ChatPresenceMedia(media))
err := s.clientPointer[instance.Id].SendChatPresence(context.Background(), recipient, types.ChatPresence("composing"), types.ChatPresenceMedia(media))
if err != nil {
return nil, err
}
time.Sleep(time.Duration(data.Delay) * time.Millisecond)
err = s.clientPointer.Get(instance.Id).SendChatPresence(context.Background(), recipient, types.ChatPresence("paused"), types.ChatPresenceMedia(media))
err = s.clientPointer[instance.Id].SendChatPresence(context.Background(), recipient, types.ChatPresence("paused"), types.ChatPresenceMedia(media))
if err != nil {
return nil, err
}
@@ -2711,7 +2631,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
// Only try to get participants for actual groups, not newsletters
if isGroup && !isNewsletter {
if data.MentionAll {
groupInfo, err := s.clientPointer.Get(instance.Id).GetGroupInfo(context.Background(), recipient)
groupInfo, err := s.clientPointer[instance.Id].GetGroupInfo(context.Background(), recipient)
if err != nil {
return nil, err
}
@@ -2850,7 +2770,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
sendExtra.AdditionalNodes = data.AdditionalNodes
}
response, err := s.clientPointer.Get(instance.Id).SendMessage(context.Background(), recipient, msg, sendExtra)
response, err := s.clientPointer[instance.Id].SendMessage(context.Background(), recipient, msg, sendExtra)
if err != nil {
s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error sending message: %v", instance.Id, err)
return nil, err
@@ -2861,7 +2781,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
messageInfo := types.MessageInfo{
MessageSource: types.MessageSource{
Chat: recipient,
Sender: *s.clientPointer.Get(instance.Id).Store.ID,
Sender: *s.clientPointer[instance.Id].Store.ID,
IsFromMe: true,
IsGroup: isGroup,
},
@@ -2915,15 +2835,15 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
sticker := msg.GetStickerMessage()
if img != nil {
data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), img)
data, err = s.clientPointer[instance.Id].Download(context.Background(), img)
} else if audio != nil {
data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), audio)
data, err = s.clientPointer[instance.Id].Download(context.Background(), audio)
} else if document != nil {
data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), document)
data, err = s.clientPointer[instance.Id].Download(context.Background(), document)
} else if video != nil {
data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), video)
data, err = s.clientPointer[instance.Id].Download(context.Background(), video)
} else if sticker != nil {
data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), sticker)
data, err = s.clientPointer[instance.Id].Download(context.Background(), sticker)
webpReader := bytes.NewReader(data)
img, err := webp.Decode(webpReader)
@@ -3446,7 +3366,7 @@ func (s *sendService) sendStatusWebhook(messageSent *MessageSendStruct, instance
}
func NewSendService(
clientPointer *safemap.Map[*whatsmeow.Client],
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
config *config.Config,
loggerWrapper *logger_wrapper.LoggerManager,
+2 -4
View File
@@ -7,17 +7,15 @@ type ServerHandler interface {
}
type serverHandler struct {
version string
}
// ServerOk implements ServerHandler.
func (s *serverHandler) ServerOk(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"status": "ok",
"version": s.version,
})
}
func NewServerHandler(version string) ServerHandler {
return &serverHandler{version: version}
func NewServerHandler() ServerHandler {
return &serverHandler{}
}
+5 -8
View File
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"io"
"net/http"
"time"
@@ -34,7 +33,7 @@ type UserService interface {
}
type userService struct {
clientPointer *safemap.Map[*whatsmeow.Client]
clientPointer map[string]*whatsmeow.Client
whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager
}
@@ -110,7 +109,7 @@ type PrivacyStruct struct {
}
func (u *userService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := u.clientPointer.Get(instanceId)
client := u.clientPointer[instanceId]
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil {
@@ -124,7 +123,7 @@ func (u *userService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second)
client = u.clientPointer.Get(instanceId)
client = u.clientPointer[instanceId]
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId,
client != nil,
@@ -533,9 +532,7 @@ func (u *userService) SetProfileStatus(data *SetProfileStatusStruct, instance *i
return false, err
}
err = client.SetStatusMessage(context.Background(), types.SetStatusInput{
Text: &data.Status,
})
err = client.SetStatusMessage(context.Background(), types.SetStatusInput{Text: &data.Status})
if err != nil {
return false, err
}
@@ -544,7 +541,7 @@ func (u *userService) SetProfileStatus(data *SetProfileStatusStruct, instance *i
}
func NewUserService(
clientPointer *safemap.Map[*whatsmeow.Client],
clientPointer map[string]*whatsmeow.Client,
whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager,
) UserService {
-72
View File
@@ -187,71 +187,6 @@ func formatBRNumber(jid string) string {
return jid
}
// BRPhoneVariants returns both forms of a Brazilian mobile number — with and
// without the 9th digit — with the received form first, or nil when the number
// is not a Brazilian mobile.
//
// Accounts created before the 9th digit rollout are still registered without
// it (e.g. 554291389691), newer ones with it (5542991389691). No fixed rule
// derived from the DDD is right for every account, so callers should ask
// WhatsApp which of the two exists.
func BRPhoneVariants(number string) []string {
if strings.Contains(number, "@") {
if !strings.HasSuffix(number, "@"+whatsmeow_types.DefaultUserServer) {
return nil
}
number = strings.Split(number, "@")[0]
}
number = strings.Split(number, ":")[0]
digits := strings.Map(func(r rune) rune {
if r >= '0' && r <= '9' {
return r
}
return -1
}, number)
// 55 + DDD (11-99, never starting with 0) + subscriber
if !strings.HasPrefix(digits, "55") || len(digits) < 12 || digits[2] == '0' {
return nil
}
switch len(digits) {
case 13:
if digits[4] == '9' {
return []string{digits, digits[:4] + digits[5:]}
}
case 12:
// 8-digit mobile numbers start with 6, 7, 8 or 9; landlines with 2-5
if digits[4] >= '6' {
return []string{digits, digits[:4] + "9" + digits[4:]}
}
}
return nil
}
// LIDCandidate returns the user part of number when it could be a LID sent as
// a phone number ("255284433936406", "[email protected]"), or ""
// when it has another server, a device suffix or non-digit characters.
func LIDCandidate(number string) string {
if strings.Contains(number, "@") {
if !strings.HasSuffix(number, "@"+whatsmeow_types.DefaultUserServer) {
return ""
}
number = strings.Split(number, "@")[0]
}
number = strings.TrimPrefix(strings.TrimSpace(number), "+")
if len(number) < 8 {
return ""
}
for _, r := range number {
if r < '0' || r > '9' {
return ""
}
}
return number
}
// ParseJID parses a number string into a WhatsApp JID with validation
func ParseJID(arg string) (whatsmeow_types.JID, bool) {
if arg == "" {
@@ -272,13 +207,6 @@ func ParseJID(arg string) (whatsmeow_types.JID, bool) {
return recipient, false
}
// CreateJID keeps the "+" prefix for IsOnWhatsApp, but it is not part of a
// user JID. WhatsApp does not answer queries addressed to "+<number>", so
// they hang until the IQ timeout (upstream #223 / PR #224).
if recipient.Server == whatsmeow_types.DefaultUserServer {
recipient.User = strings.TrimPrefix(recipient.User, "+")
}
if recipient.User == "" && !strings.Contains(jidString, "@broadcast") {
logger.LogError("Invalid JID. No user specified: %s", jidString)
return recipient, false
+2 -53
View File
@@ -284,13 +284,13 @@ func TestParseJID(t *testing.T) {
name: "Valid phone number",
input: "15551234567",
expectOk: true,
expectJID: "[email protected]",
expectJID: "+[email protected]",
},
{
name: "Valid BR number",
input: "5531987654321",
expectOk: true,
expectJID: "[email protected]",
expectJID: "+[email protected]",
},
{
name: "Valid group ID",
@@ -384,54 +384,3 @@ func TestCanonicalJID(t *testing.T) {
})
}
}
func TestBRPhoneVariants(t *testing.T) {
tests := []struct {
name string
input string
want []string
}{
{"13 digits with 9", "5542991389691", []string{"5542991389691", "554291389691"}},
{"12 digits without 9", "554291389691", []string{"554291389691", "5542991389691"}},
{"plus and JID suffix", "[email protected]", []string{"5511987654321", "551187654321"}},
{"formatted", "+55 (42) 99138-9691", []string{"5542991389691", "554291389691"}},
{"landline", "554232221234", nil},
{"not Brazil", "15551234567", nil},
{"group", "[email protected]", nil},
{"lid", "255284433936406@lid", nil},
{"13 digits without 9 after DDD", "5542891389691", nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := BRPhoneVariants(tt.input)
if len(got) != len(tt.want) {
t.Fatalf("BRPhoneVariants(%q) = %v, want %v", tt.input, got, tt.want)
}
for i := range got {
if got[i] != tt.want[i] {
t.Fatalf("BRPhoneVariants(%q) = %v, want %v", tt.input, got, tt.want)
}
}
})
}
}
func TestLIDCandidate(t *testing.T) {
tests := []struct {
input string
want string
}{
{"255284433936406", "255284433936406"},
{"[email protected]", "255284433936406"},
{"255284433936406@lid", ""},
{"[email protected]", ""},
{"255284433936406:[email protected]", ""},
{"+55 (42) 99138-9691", ""},
{"1234", ""},
}
for _, tt := range tests {
if got := LIDCandidate(tt.input); got != tt.want {
t.Errorf("LIDCandidate(%q) = %q, want %q", tt.input, got, tt.want)
}
}
}
@@ -1,84 +1,70 @@
package whatsmeow_service
import (
"context"
"os"
"path/filepath"
"sync"
"testing"
"github.com/evolution-foundation/evolution-go/pkg/config"
"go.mau.fi/whatsmeow/proto/waAdv"
"go.mau.fi/whatsmeow/store/sqlstore"
"go.mau.fi/whatsmeow/types"
_ "modernc.org/sqlite"
"github.com/evolution-foundation/evolution-go/pkg/config"
)
func TestSharedAuthContainerRetryAndConcurrentReuse(t *testing.T) {
root := t.TempDir()
w := whatsmeowService{config: &config.Config{}, exPath: root, authStore: &sharedSQLStore{}}
t.Cleanup(func() {
if w.authStore.sqliteDB != nil {
if err := w.authStore.sqliteDB.Close(); err != nil {
t.Errorf("close auth store: %v", err)
// Exercised through SQLite only. Closing ownDB on the Upgrade error path is not
// covered: the handle is local to getAuthContainer.
func TestGetAuthContainerRetryAndReuse(t *testing.T) {
// TempDirs first: cleanups run LIFO, so reset closes the *sql.DB before
// RemoveAll, which fails on Windows while the file is still open.
badPath := filepath.Join(t.TempDir(), "does-not-exist")
goodPath := t.TempDir()
reset := func() {
sharedAuthContainerMu.Lock()
if sharedAuthContainer != nil {
_ = sharedAuthContainer.Close()
sharedAuthContainer = nil
}
sharedAuthContainerMu.Unlock()
}
})
if _, err := w.getSharedSQLStoreContainer(); err == nil {
t.Fatal("expected failure before dbdata exists")
reset()
t.Cleanup(reset)
// SQLite does not create missing directories, so Upgrade fails here.
bad := whatsmeowService{
config: &config.Config{},
exPath: badPath,
}
if err := os.Mkdir(filepath.Join(root, "dbdata"), 0o755); err != nil {
if _, err := bad.getAuthContainer(); err == nil {
t.Fatal("expected an error for a missing directory, got nil")
}
sharedAuthContainerMu.Lock()
if sharedAuthContainer != nil {
sharedAuthContainerMu.Unlock()
t.Fatalf("failed container should not be memoized (sharedAuthContainer = %#v)", sharedAuthContainer)
}
sharedAuthContainerMu.Unlock()
// The DSN expects a dbdata subdirectory.
if err := os.MkdirAll(filepath.Join(goodPath, "dbdata"), 0o755); err != nil {
t.Fatal(err)
}
const callers = 16
containers := make([]*sqlstore.Container, callers)
errs := make([]error, callers)
var wg sync.WaitGroup
for i := range callers {
wg.Add(1)
go func() {
defer wg.Done()
containers[i], errs[i] = w.getSharedSQLStoreContainer()
}()
good := whatsmeowService{
config: &config.Config{},
exPath: goodPath,
}
wg.Wait()
for i := range callers {
if errs[i] != nil || containers[i] == nil {
t.Fatalf("caller %d could not retry: %v", i, errs[i])
}
if containers[i] != containers[0] {
t.Fatalf("caller %d opened a different container", i)
}
}
if got := w.authStore.sqliteDB.Stats().MaxOpenConnections; got != 1 {
t.Fatalf("SQLite connection limit = %d, want 1", got)
}
// Persist a paired-device record and reopen the existing schema as on restart.
device := containers[0].NewDevice()
jid := types.NewJID("5511999999999", types.DefaultUserServer)
device.ID = &jid
device.Account = &waAdv.ADVSignedDeviceIdentity{
Details: []byte("test device"),
AccountSignature: make([]byte, 64),
AccountSignatureKey: make([]byte, 32),
DeviceSignature: make([]byte, 64),
}
if err := device.Save(context.Background()); err != nil {
t.Fatalf("save session: %v", err)
}
if err := w.authStore.sqliteDB.Close(); err != nil {
t.Fatal(err)
}
w.authStore = &sharedSQLStore{}
reopened, err := w.getSharedSQLStoreContainer()
c1, err := good.getAuthContainer()
if err != nil {
t.Fatalf("reopen existing auth database: %v", err)
t.Fatalf("retry after a failure should succeed instead of returning a cached error: %v", err)
}
restored, err := reopened.GetDevice(context.Background(), jid)
if err != nil || restored == nil {
t.Fatalf("restore session: device=%v err=%v", restored, err)
if c1 == nil {
t.Fatal("nil container after success")
}
if restored.RegistrationID != device.RegistrationID || *restored.NoiseKey.Pub != *device.NoiseKey.Pub {
t.Fatal("session keys changed after reopening")
c2, err := good.getAuthContainer()
if err != nil {
t.Fatalf("second call failed: %v", err)
}
if c1 != c2 {
t.Fatal("container was not reused; expected the shared instance")
}
}
+95 -286
View File
@@ -7,7 +7,6 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"image/png"
"io"
"math/rand"
@@ -28,7 +27,6 @@ import (
"go.mau.fi/whatsmeow/appstate"
"go.mau.fi/whatsmeow/proto/waCompanionReg"
"go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/proto/waWa6"
"go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/store/sqlstore"
"go.mau.fi/whatsmeow/types"
@@ -84,10 +82,10 @@ type whatsmeowService struct {
labelRepository label_repository.LabelRepository
pollService poll_service.PollService // NOVO: Serviço de enquetes
config *config.Config
killChannel *safemap.Map[chan bool]
killChannel map[string](chan bool)
userInfoCache *cache.Cache
clientPointer *safemap.Map[*whatsmeow.Client]
myClientPointer *safemap.Map[*MyClient]
clientPointer map[string]*whatsmeow.Client
myClientPointer map[string]*MyClient
rabbitmqProducer producer_interfaces.Producer
webhookProducer producer_interfaces.Producer
websocketProducer producer_interfaces.Producer
@@ -98,17 +96,8 @@ type whatsmeowService struct {
natsProducer producer_interfaces.Producer
loggerWrapper *logger_wrapper.LoggerManager
passkeyCeremony *ceremony.Store
// authStore is heap-allocated so its mutex is shared by value-receiver methods.
authStore *sharedSQLStore
}
// sharedSQLStore holds the process-wide whatsmeow sqlstore.Container for PostgresAuthDB
// (or the sqlite fallback). Cache only success; never Close on instance disconnect.
type sharedSQLStore struct {
mu sync.Mutex
container *sqlstore.Container
sqliteDB *sql.DB // kept alive when not using PostgresAuthDB
}
type MyClient struct {
service WhatsmeowService
WAClient *whatsmeow.Client
@@ -125,9 +114,9 @@ type MyClient struct {
messageRepository message_repository.MessageRepository
labelRepository label_repository.LabelRepository
pollService poll_service.PollService // NOVO: Serviço de enquetes
clientPointer *safemap.Map[*whatsmeow.Client]
myClientPointer *safemap.Map[*MyClient]
killChannel *safemap.Map[chan bool]
clientPointer map[string]*whatsmeow.Client
myClientPointer map[string]*MyClient
killChannel map[string](chan bool)
userInfoCache *cache.Cache
config *config.Config
historySyncID int32
@@ -181,22 +170,11 @@ type ProxyConfig struct {
Username string `json:"username"`
}
// reconnectsInProgress holds the instance IDs with a ReconnectClient running. Two Disconnected events for
// the same instance in the same second used to run two reconnects concurrently and dereference a client the
// other one had just removed, killing the whole process (upstream issue #188).
var reconnectsInProgress sync.Map
func (w whatsmeowService) ReconnectClient(instanceId string) error {
if _, running := reconnectsInProgress.LoadOrStore(instanceId, struct{}{}); running {
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Reconnection already in progress, skipping duplicate request", instanceId)
return nil
}
defer reconnectsInProgress.Delete(instanceId)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Starting reconnection process - simulating restart", instanceId)
// Passo 1: Limpar conexão existente se houver
if client, exists := w.clientPointer.Lookup(instanceId); exists && client != nil {
if client, exists := w.clientPointer[instanceId]; exists {
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Disconnecting existing client", instanceId)
// Desconectar o cliente WebSocket
@@ -206,7 +184,7 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
}
// Remover event handler se existir
if mycli, ok := w.myClientPointer.Lookup(instanceId); ok {
if mycli, ok := w.myClientPointer[instanceId]; ok {
if mycli.eventHandlerID != 0 {
client.RemoveEventHandler(mycli.eventHandlerID)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Event handler removed", instanceId)
@@ -218,16 +196,19 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Cleaning up resources", instanceId)
// Enviar sinal de kill se o canal existir
if killChan, exists := w.killChannel.Lookup(instanceId); exists {
if safemap.TrySendTimeout(killChan, true, 0) {
if killChan, exists := w.killChannel[instanceId]; exists {
select {
case killChan <- true:
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill signal sent", instanceId)
default:
// Canal pode estar bloqueado, continua
}
}
// Remover das estruturas
w.clientPointer.Delete(instanceId)
w.myClientPointer.Delete(instanceId)
w.killChannel.Delete(instanceId)
delete(w.clientPointer, instanceId)
delete(w.myClientPointer, instanceId)
delete(w.killChannel, instanceId)
// Limpar cache de userInfo para esta instância
if instance, err := w.instanceRepository.GetInstanceByID(instanceId); err == nil {
@@ -319,190 +300,81 @@ func (w whatsmeowService) ForceUpdateJid(instanceId string, number string) error
return nil
}
// getSharedSQLStoreContainer returns the process-wide whatsmeow sqlstore.Container.
// PostgresAuthDB reuses the pooled authDB from initPostgresAuthDB (Upgrade once).
// The Users/GORM database is intentionally separate and never passed here.
func (w whatsmeowService) getSharedSQLStoreContainer() (*sqlstore.Container, error) {
if w.authStore == nil {
return nil, fmt.Errorf("shared sqlstore not initialized")
// Shared by every StartClient: a container per call opens a pool that is never
// closed. Only success is memoized, so a failed creation is retried next call.
var (
sharedAuthContainer *sqlstore.Container
sharedAuthContainerMu sync.Mutex
)
func (w whatsmeowService) getAuthContainer() (*sqlstore.Container, error) {
sharedAuthContainerMu.Lock()
defer sharedAuthContainerMu.Unlock()
if sharedAuthContainer != nil {
return sharedAuthContainer, nil
}
w.authStore.mu.Lock()
defer w.authStore.mu.Unlock()
if w.authStore.container != nil {
return w.authStore.container, nil
}
return w.createSharedSQLStoreContainer()
}
// Called with authStore.mu held. A failed upgrade is retried by the next caller.
func (w whatsmeowService) createSharedSQLStoreContainer() (*sqlstore.Container, error) {
var dbLog waLog.Logger
if w.config.WaDebug != "" {
dbLog = waLog.Stdout("Database", w.config.WaDebug, true)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
var container *sqlstore.Container
var ownDB *sql.DB
if w.config.PostgresAuthDB != "" {
// Reuse the pool main.go opened and capped; a second pool on the same
// DSN would raise the connection ceiling.
if w.authDB == nil {
return nil, fmt.Errorf("postgres auth DB handle is nil")
}
container := sqlstore.NewWithDB(w.authDB, "postgres", dbLog)
if err := container.Upgrade(ctx); err != nil {
// Do not Close authDB — owned by main.
return nil, fmt.Errorf("failed to upgrade database: %w", err)
}
w.authStore.container = container
return container, nil
return nil, fmt.Errorf("POSTGRES_AUTH_DB is set but the auth database pool was not initialized")
}
container = sqlstore.NewWithDB(w.authDB, "postgres", dbLog)
} else {
dsn := fmt.Sprintf("file:%s/dbdata/main.db?_pragma=foreign_keys(1)&_busy_timeout=5000&cache=shared&mode=rwc&_journal_mode=WAL", w.exPath)
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, fmt.Errorf("failed to open sqlite auth store: %w", err)
return nil, fmt.Errorf("failed to open auth database: %w", err)
}
// Process-wide cap shared by all instances. Fix the DSN before raising it:
// modernc ignores _journal_mode and _busy_timeout, so WAL is never enabled.
db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
db.SetConnMaxLifetime(5 * time.Minute)
db.SetConnMaxIdleTime(1 * time.Minute)
container := sqlstore.NewWithDB(db, "sqlite", dbLog)
ownDB = db
container = sqlstore.NewWithDB(db, "sqlite", dbLog)
}
// Upgrade runs under the mutex: without a deadline, a server that accepts TCP
// but never answers would stall every StartClient behind it.
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
if err := container.Upgrade(ctx); err != nil {
if closeErr := db.Close(); closeErr != nil {
return nil, fmt.Errorf("failed to upgrade database: %w; close sqlite auth store: %v", err, closeErr)
// Close only what this call opened; the Postgres pool belongs to main.
if ownDB != nil {
_ = ownDB.Close()
}
return nil, fmt.Errorf("failed to upgrade database: %w", err)
return nil, fmt.Errorf("failed to upgrade auth database: %w", err)
}
w.authStore.sqliteDB = db
w.authStore.container = container
sharedAuthContainer = container
return container, nil
}
// ============================================================================
// Backoff for the reconnect loop.
//
// THE LOOP: an instance whose device was logged out from the phone spins
// forever. Disconnected -> ReconnectClient -> the instance comes up with no
// session -> emits a QR -> nobody scans -> max QR count -> forced logout ->
// Disconnected again. Measured in production: 110 reconnects and 1135 QR codes
// in 50 minutes from a single instance, and it only stopped when a human looked.
//
// Nothing in the current code counts those restarts, because from
// ReconnectClient's point of view every turn SUCCEEDS — the instance really does
// come up. What fails afterwards is the pairing, which nobody was measuring.
//
// THE SHAPE: the first reconnectFreeAttempts restarts inside the window go
// straight through — that is the good case, a healthy instance that lost its
// websocket and must come back within seconds. Past that the loop turns into a
// growing wait, and the instance keeps trying: this is a backoff, not a
// give-up. An instance with a valid session still heals on its own; what is
// lost is the hammering.
//
// NOTE: only one goroutine waits per instance (the scheduled flag). Without it
// every Disconnected arriving during the wait would stack another one, and the
// backoff would become the very loop it was written to stop.
// ============================================================================
const (
reconnectWindow = 15 * time.Minute // restarts inside this window count together
reconnectFreeAttempts = 5 // how many go through with no wait
)
// The ladder of waits. The last step repeats indefinitely.
var reconnectBackoff = []time.Duration{5 * time.Minute, 15 * time.Minute, 30 * time.Minute}
type reconnectState struct {
restarts int
since time.Time
step int
scheduled bool
}
var (
reconnectMu sync.Mutex
reconnectTrack = map[string]*reconnectState{}
)
// reconnectAllowed reports whether this instance may restart right now.
//
// (true, 0) — go ahead, normal path
// (false, d) — wait d and then try; this goroutine owns the wait
// (false, -1) — another goroutine is already waiting for this instance; give up
func reconnectAllowed(instanceID string) (bool, time.Duration) {
reconnectMu.Lock()
defer reconnectMu.Unlock()
now := time.Now()
st := reconnectTrack[instanceID]
if st == nil || now.Sub(st.since) > reconnectWindow {
reconnectTrack[instanceID] = &reconnectState{restarts: 1, since: now}
return true, 0
}
if st.scheduled {
return false, -1
}
st.restarts++
if st.restarts <= reconnectFreeAttempts {
return true, 0
}
d := reconnectBackoff[len(reconnectBackoff)-1]
if st.step < len(reconnectBackoff) {
d = reconnectBackoff[st.step]
st.step++
}
st.scheduled = true
return false, d
}
// reconnectWaitDone puts the instance back in line once its wait is over.
func reconnectWaitDone(instanceID string) {
reconnectMu.Lock()
if st := reconnectTrack[instanceID]; st != nil {
st.scheduled = false
}
reconnectMu.Unlock()
}
// reconnectSucceeded clears the state — called when the instance actually
// connects. Without it the backoff would inherit the count of a problem that is
// already solved.
func reconnectSucceeded(instanceID string) {
reconnectMu.Lock()
delete(reconnectTrack, instanceID)
reconnectMu.Unlock()
}
// clientsStarting holds the instance IDs whose StartClient is between entry and registering the new client in
// clientPointer. Without it, a second StartClient in that window (e.g. GET /instance/qr right after
// POST /instance/connect, which starts the client in a goroutine) sees no client and starts another one
// (upstream PR #239).
var clientsStarting sync.Map
func (w whatsmeowService) StartClient(cd *ClientData) {
if _, starting := clientsStarting.LoadOrStore(cd.Instance.Id, struct{}{}); starting {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Client start already in progress, skipping duplicate start", cd.Instance.Id)
return
}
registered := false
defer func() {
if !registered {
clientsStarting.Delete(cd.Instance.Id)
}
}()
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Starting websocket connection to Whatsapp for user '%s'", cd.Instance.Id)
var deviceStore *store.Device
var err error
if w.clientPointer.Get(cd.Instance.Id) != nil {
if w.clientPointer.Get(cd.Instance.Id).IsConnected() {
if w.clientPointer[cd.Instance.Id] != nil {
if w.clientPointer[cd.Instance.Id].IsConnected() {
return
}
}
container, err := w.getSharedSQLStoreContainer()
container, err := w.getAuthContainer()
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to create container: %v", cd.Instance.Id, err)
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to get auth container: %v", cd.Instance.Id, err)
return
}
@@ -544,10 +416,19 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
store.DeviceProps.RequireFullSync = proto.Bool(true)
if w.config.WhatsappVersionMajor != 0 && w.config.WhatsappVersionMinor != 0 && w.config.WhatsappVersionPatch != 0 {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Setting whatsapp version from config to %d.%d.%d", cd.Instance.Id, w.config.WhatsappVersionMajor, w.config.WhatsappVersionMinor, w.config.WhatsappVersionPatch)
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Setting whatsapp version to %d.%d.%d", cd.Instance.Id, w.config.WhatsappVersionMajor, w.config.WhatsappVersionMinor, w.config.WhatsappVersionPatch)
version.Major = w.config.WhatsappVersionMajor
if err == nil {
store.DeviceProps.Version.Primary = proto.Uint32(uint32(version.Major))
}
version.Minor = w.config.WhatsappVersionMinor
if err == nil {
store.DeviceProps.Version.Secondary = proto.Uint32(uint32(version.Minor))
}
version.Patch = w.config.WhatsappVersionPatch
if err == nil {
store.DeviceProps.Version.Tertiary = proto.Uint32(uint32(version.Patch))
}
} else {
// Try to fetch version from WhatsApp Web
webVersion, err := fetchWhatsAppWebVersion()
@@ -556,24 +437,11 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
} else {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Setting whatsapp version from web to %d.%d.%d", cd.Instance.Id, webVersion.Major, webVersion.Minor, webVersion.Patch)
version = *webVersion
}
}
if version.Major != 0 && version.Minor != 0 && version.Patch != 0 {
store.DeviceProps.Version.Primary = proto.Uint32(uint32(version.Major))
store.DeviceProps.Version.Secondary = proto.Uint32(uint32(version.Minor))
store.DeviceProps.Version.Tertiary = proto.Uint32(uint32(version.Patch))
waVer := store.WAVersionContainer{uint32(version.Major), uint32(version.Minor), uint32(version.Patch)}
store.SetWAVersion(waVer)
if store.BaseClientPayload != nil && store.BaseClientPayload.UserAgent != nil {
store.BaseClientPayload.UserAgent.AppVersion = &waWa6.ClientPayload_UserAgent_AppVersion{
Primary: proto.Uint32(uint32(version.Major)),
Secondary: proto.Uint32(uint32(version.Minor)),
Tertiary: proto.Uint32(uint32(version.Patch)),
}
}
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Applied WhatsApp handshake version %d.%d.%d", cd.Instance.Id, version.Major, version.Minor, version.Patch)
}
// 🔒 FIX: Sempre criar logger, mesmo que WaDebug esteja vazio
// Usar "INFO" como nível mínimo para garantir que logs importantes apareçam
@@ -584,10 +452,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
clientLog := waLog.Stdout("Client", minLevel, true)
client := whatsmeow.NewClient(deviceStore, clientLog)
w.clientPointer.Set(cd.Instance.Id, client)
// Registered: later callers see this client, and the restart below (which re-enters StartClient) must not be blocked.
clientsStarting.Delete(cd.Instance.Id)
registered = true
w.clientPointer[cd.Instance.Id] = client
if cd.IsProxy {
var proxyConfig ProxyConfig
@@ -675,7 +540,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
mycli.eventHandlerID = mycli.WAClient.AddEventHandler(mycli.myEventHandler)
// Armazena o MyClient no map para permitir atualizações posteriores
w.myClientPointer.Set(cd.Instance.Id, mycli)
w.myClientPointer[cd.Instance.Id] = mycli
if client.Store.ID != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Already logged in with JID: %s", cd.Instance.Id, client.Store.ID.String())
@@ -749,12 +614,12 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
for {
select {
case <-w.killChannel.Get(cd.Instance.Id):
case <-w.killChannel[cd.Instance.Id]:
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Received kill signal for user '%s'", cd.Instance.Id)
client.Disconnect()
w.clientPointer.Delete(cd.Instance.Id)
w.myClientPointer.Delete(cd.Instance.Id)
delete(w.clientPointer, cd.Instance.Id)
delete(w.myClientPointer, cd.Instance.Id)
// Limpar cache de userInfo para esta instância
w.userInfoCache.Delete(cd.Instance.Token)
@@ -799,14 +664,6 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)
}
// Without a paired device (QR timed out, logged out, or the phone removed this device) a restart would
// only create a new device and cycle QR codes forever. Stop here; the next /instance/connect or
// /instance/qr starts a fresh client (upstream PR #240).
if client.Store.ID == nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] No paired device; not restarting client", cd.Instance.Id)
return
}
// restart client
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Restarting client", cd.Instance.Id)
w.StartClient(cd)
@@ -837,7 +694,7 @@ func schedulePresenceUpdates(mycli *MyClient) {
randomInterval := time.Duration(1+rand.Intn(3)) * time.Hour
ticker = time.NewTicker(randomInterval)
case <-mycli.killChannel.Get(mycli.userID):
case <-mycli.killChannel[mycli.userID]:
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Received kill signal, stopping presence updates", mycli.userID)
return // Encerra a goroutine quando receber sinal de kill
}
@@ -1031,10 +888,8 @@ func (mycli *MyClient) teardownQR(reason string, forceLogout bool) {
// maps (it is the single writer for this instance). Blocking send mirrors
// the original timeout branch so the signal is never dropped.
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] QR timeout — signaling kill channel", instanceID)
if killChan, exists := mycli.killChannel.Lookup(instanceID); exists {
if !safemap.TrySend(killChan, true) {
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] Kill channel already closed (instance deleted)", instanceID)
}
if killChan, exists := mycli.killChannel[instanceID]; exists {
killChan <- true
}
}
@@ -1060,9 +915,6 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
}
}
case *events.Connected, *events.PushNameSetting:
// A real connection ends the loop, so the backoff counter dies here.
// Without this, a drop tomorrow would inherit today's restarts.
reconnectSucceeded(mycli.userID)
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] events.Connected to Whatsapp for user '%s'", mycli.userID, mycli.WAClient.Store.PushName)
if len(mycli.WAClient.Store.PushName) > 0 {
doWebhook = true
@@ -1095,7 +947,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
// jid, ok := utils.ParseJID(mycli.WAClient.Store.ID.ToNonAD().User)
// if ok {
// profilePicUrl, err := mycli.clientPointer.Get(mycli.userID).GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{
// profilePicUrl, err := mycli.clientPointer[mycli.userID].GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{
// Preview: false,
// })
// if err != nil {
@@ -1465,7 +1317,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
fmt.Printf("[POLL DEBUG] ✅ mycli.WAClient is initialized: %s\n", mycli.WAClient.Store.ID)
}
decrypted, err := mycli.clientPointer.Get(mycli.userID).DecryptPollVote(context.Background(), evt)
decrypted, err := mycli.clientPointer[mycli.userID].DecryptPollVote(context.Background(), evt)
if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decrypt vote: %v", mycli.userID, err)
} else {
@@ -2005,27 +1857,6 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
doWebhook = true
postMap["event"] = "Archive"
// postMap["data"] still holds the raw event at this point, so the type
// assertion below panicked on every Archive event. Same marshal/unmarshal
// step every other case in this switch already does.
if postMap["data"] != nil {
jsonBytes, err := json.Marshal(postMap["data"])
if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to marshal postMap['data']: %v", mycli.userID, err)
return
}
var parsed map[string]interface{}
if err := json.Unmarshal(jsonBytes, &parsed); err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to unmarshal postMap['data'] to map[string]interface{}: %v", mycli.userID, err)
return
}
postMap["data"] = parsed
} else {
postMap["data"] = make(map[string]interface{})
}
dataMap := postMap["data"].(map[string]interface{})
dataMap["JID"] = evt.JID
dataMap["Timestamp"] = evt.Timestamp
@@ -2106,7 +1937,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
}
// Agora mata o canal DEPOIS de enviar o evento
safemap.TrySend(mycli.killChannel.Get(mycli.userID), true)
mycli.killChannel[mycli.userID] <- true
case *events.ChatPresence:
doWebhook = true
postMap["event"] = "ChatPresence"
@@ -2193,20 +2024,6 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
// Trigger instance restart via websocket-capable service (non-blocking)
go func(instanceID string) {
mycli.loggerWrapper.GetLogger(instanceID).LogInfo("[%s] Disconnected detected, restarting instance", instanceID)
if allowed, wait := reconnectAllowed(instanceID); !allowed {
if wait < 0 {
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] a reconnect is already scheduled — this event will not open another", instanceID)
return
}
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] reconnect loop detected: more than %d restarts in %s. Next attempt in %s. If the device was logged out from the phone, only a new QR scan will fix it.", instanceID, reconnectFreeAttempts, reconnectWindow, wait)
if err := mycli.instanceRepository.UpdateConnected(instanceID, false, fmt.Sprintf("Reconnect backing off — next attempt in %s", wait)); err != nil {
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] could not record the backoff reason: %v", instanceID, err)
}
time.Sleep(wait)
reconnectWaitDone(instanceID)
}
if err := mycli.service.ReconnectClient(instanceID); err != nil {
mycli.loggerWrapper.GetLogger(instanceID).LogError("[%s] Failed to restart instance: %v", instanceID, err)
}
@@ -2605,7 +2422,7 @@ func (w whatsmeowService) StartInstance(instanceId string) error {
}
}
w.killChannel.Set(instance.Id, make(chan bool))
w.killChannel[instance.Id] = make(chan bool)
clientData := &ClientData{
Instance: instance,
@@ -2841,14 +2658,7 @@ func fetchWhatsAppWebVersion() (*clientVersion, error) {
return cachedWebVersion, nil
}
req, err := http.NewRequest("GET", "https://web.whatsapp.com/sw.js", nil)
if err != nil {
return nil, fmt.Errorf("failed to create request for WhatsApp Web version: %v", err)
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
httpClient := &http.Client{Timeout: 10 * time.Second}
resp, err := httpClient.Do(req)
resp, err := http.Get("https://web.whatsapp.com/sw.js")
if err != nil {
return nil, fmt.Errorf("failed to fetch WhatsApp Web version: %v", err)
}
@@ -2913,7 +2723,7 @@ func (w whatsmeowService) UpdateInstanceSettings(instanceId string) error {
}
// Verifica se o MyClient existe
myClient, exists := w.myClientPointer.Lookup(instanceId)
myClient, exists := w.myClientPointer[instanceId]
if !exists {
w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId)
return fmt.Errorf("instance %s not found in runtime", instanceId)
@@ -2972,7 +2782,7 @@ func (w whatsmeowService) UpdateInstanceAdvancedSettings(instanceId string) erro
}
// Verifica se o MyClient existe
myClient, exists := w.myClientPointer.Lookup(instanceId)
myClient, exists := w.myClientPointer[instanceId]
if !exists {
w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId)
return fmt.Errorf("instance %s not found in runtime", instanceId)
@@ -2992,19 +2802,19 @@ func (w whatsmeowService) ClearInstanceCache(instanceId string, token string) er
w.userInfoCache.Delete(token)
// Limpar myClientPointer se existir
if _, exists := w.myClientPointer.Lookup(instanceId); exists {
w.myClientPointer.Delete(instanceId)
if _, exists := w.myClientPointer[instanceId]; exists {
delete(w.myClientPointer, instanceId)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] MyClient pointer cleared", instanceId)
}
// Limpar clientPointer se existir
if _, exists := w.clientPointer.Lookup(instanceId); exists {
w.clientPointer.Delete(instanceId)
if _, exists := w.clientPointer[instanceId]; exists {
delete(w.clientPointer, instanceId)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client pointer cleared", instanceId)
}
// Limpar killChannel se existir
if killChan, exists := w.killChannel.Lookup(instanceId); exists {
if killChan, exists := w.killChannel[instanceId]; exists {
select {
case killChan <- true:
// Canal recebeu o sinal
@@ -3012,7 +2822,7 @@ func (w whatsmeowService) ClearInstanceCache(instanceId string, token string) er
// Canal pode estar bloqueado, apenas fecha
}
close(killChan)
w.killChannel.Delete(instanceId)
delete(w.killChannel, instanceId)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill channel cleared", instanceId)
}
@@ -3026,8 +2836,8 @@ func NewWhatsmeowService(
messageRepository message_repository.MessageRepository,
labelRepository label_repository.LabelRepository,
config *config.Config,
killChannel *safemap.Map[chan bool],
clientPointer *safemap.Map[*whatsmeow.Client],
killChannel map[string](chan bool),
clientPointer map[string]*whatsmeow.Client,
rabbitmqProducer producer_interfaces.Producer,
webhookProducer producer_interfaces.Producer,
websocketProducer producer_interfaces.Producer,
@@ -3050,7 +2860,7 @@ func NewWhatsmeowService(
killChannel: killChannel,
userInfoCache: cache.New(5*time.Minute, 10*time.Minute),
clientPointer: clientPointer,
myClientPointer: safemap.New[*MyClient](),
myClientPointer: make(map[string]*MyClient),
rabbitmqProducer: rabbitmqProducer,
webhookProducer: webhookProducer,
websocketProducer: websocketProducer,
@@ -3061,7 +2871,6 @@ func NewWhatsmeowService(
natsProducer: natsProducer,
loggerWrapper: loggerWrapper,
passkeyCeremony: ceremony.NewStore(),
authStore: &sharedSQLStore{},
}
}
@@ -3079,7 +2888,7 @@ func (w *whatsmeowService) PasskeyCeremonyStore() *ceremony.Store {
// SubmitPasskeyResponse forwards the browser's WebAuthn assertion to WhatsApp
// for the given instance. Called by POST /passkey-ceremony/{token}/response.
func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.WebAuthnResponse) error {
client, ok := w.clientPointer.Lookup(instanceId)
client, ok := w.clientPointer[instanceId]
if !ok || client == nil {
return fmt.Errorf("no active client for instance %s", instanceId)
}
@@ -3098,7 +2907,7 @@ func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.
// ConfirmPasskey finishes the pairing after the user verified the code.
// Called by POST /passkey-ceremony/{token}/confirm.
func (w *whatsmeowService) ConfirmPasskey(instanceId string) error {
client, ok := w.clientPointer.Lookup(instanceId)
client, ok := w.clientPointer[instanceId]
if !ok || client == nil {
return fmt.Errorf("no active client for instance %s", instanceId)
}
-75
View File
@@ -1,75 +0,0 @@
# Script de Verificacao de Atualizacoes do Upstream (PowerShell)
param (
[string]$UpstreamUrl = "https://github.com/evolution-foundation/evolution-go.git"
)
$dateStr = Get-Date -Format "yyyy-MM-dd_HHmmss"
$reportFile = "relatorio_atualizacao_$dateStr.md"
Write-Host "=== Iniciando Auditoria de Atualizacoes do Upstream ($dateStr) ==="
$remotes = git remote
if ($remotes -notcontains "upstream") {
git remote add upstream $UpstreamUrl
}
git fetch upstream --tags
$localHead = (git rev-parse HEAD).Trim()
$upstreamMain = (git rev-parse upstream/main).Trim()
$newCommits = git log HEAD..upstream/main --oneline -n 15
$newCommitCount = (git rev-list --count HEAD..upstream/main).Trim()
$latestLocalTag = git describe --tags --abbrev=0 2>$null
if (-not $latestLocalTag) { $latestLocalTag = "0.7.2" }
$latestUpstreamTag = ((git tag -l --sort=-v:refname | Select-Object -First 1) + "").Trim()
$localWhatsmeow = ((Get-Content go.mod | Select-String "go.mau.fi/whatsmeow") -replace "^\s*go.mau.fi/whatsmeow\s+", "").Trim()
$impactNotice = if ([int]$newCommitCount -gt 0) {
"WARNING: Novidades detectadas no upstream ($newCommitCount novos commits). Recomenda-se abrir branch de teste em maintenance/sync-upstream."
} else {
"OK: Ambiente alinhado. Nao ha novos commits pendentes na branch principal do upstream."
}
$commitsBlock = if ($newCommits) { $newCommits -join "`r`n" } else { "Nenhum commit novo detectado." }
$sb = New-Object System.Text.StringBuilder
[void]$sb.AppendLine("# Relatorio de Monitoramento de Atualizacoes — Upstream EvoGO")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("- Data da Auditoria: $(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')")
[void]$sb.AppendLine("- Commit Local Base: $localHead")
[void]$sb.AppendLine("- Tag Local Recente: $latestLocalTag")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## 1. Estado da Branch Principal (Upstream Main)")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("- Commit Upstream Main: $upstreamMain")
[void]$sb.AppendLine("- Commits a frente no upstream: $newCommitCount")
[void]$sb.AppendLine("- Ultima Tag Upstream: $latestUpstreamTag")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("### Commits Recentes no Upstream:")
[void]$sb.AppendLine('```')
[void]$sb.AppendLine($commitsBlock)
[void]$sb.AppendLine('```')
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## 2. Dependencia Central (Whatsmeow)")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("- Versao Whatsmeow no go.mod local: $localWhatsmeow")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("")
[void]$sb.AppendLine("## 3. Analise de Impacto e Conflitos")
[void]$sb.AppendLine("")
[void]$sb.AppendLine($impactNotice)
[void]$sb.AppendLine("")
[void]$sb.AppendLine("---")
[void]$sb.AppendLine("*Relatorio gerado pelo script de monitoramento EvoGO.*")
[System.IO.File]::WriteAllText((Join-Path (Get-Location) $reportFile), $sb.ToString(), [System.Text.Encoding]::UTF8)
Write-Host "Relatorio gerado com sucesso em: $reportFile"
Get-Content $reportFile
-67
View File
@@ -1,67 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
REPORT_DATE=$(date +%Y-%m-%d_%H%M%S)
REPORT_FILE="relatorio_atualizacao_${REPORT_DATE}.md"
echo "=== Iniciando Auditoria de Atualizacoes do Upstream (${REPORT_DATE}) ==="
# 1. Configurar ou garantir remoto upstream
if ! git remote | grep -q "^upstream$"; then
git remote add upstream https://github.com/evolution-foundation/evolution-go.git
fi
git fetch upstream --tags
LOCAL_HEAD=$(git rev-parse HEAD)
UPSTREAM_MAIN=$(git rev-parse upstream/main)
UPSTREAM_DEV=$(git rev-parse upstream/develop 2>/dev/null || echo "N/A")
NEW_COMMITS_COUNT=$(git rev-list --count HEAD..upstream/main 2>/dev/null || echo 0)
NEW_COMMITS_LIST=$(git log HEAD..upstream/main --oneline -n 15 2>/dev/null || echo "Nenhum commit novo.")
LATEST_LOCAL_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "nenhuma")
LATEST_UPSTREAM_TAG=$(git tag -l --sort=-v:refname | head -n 1)
# Whatsmeow version comparison
LOCAL_WHATSMEOW=$(grep "go.mau.fi/whatsmeow" go.mod | awk '{print $2}' || echo "N/A")
cat << EOF > "${REPORT_FILE}"
# Relatorio de Monitoramento de Atualizacoes — Upstream EvoGO
**Data da Auditoria:** $(date '+%d/%m/%Y %H:%M:%S')
**Commit Local Base:** \`${LOCAL_HEAD}\`
**Tag Local Recente:** \`${LATEST_LOCAL_TAG}\`
---
## 1. Estado da Branch Principal (Upstream Main)
- **Commit Upstream Main:** \`${UPSTREAM_MAIN}\`
- **Commits a frente do upstream:** ${NEW_COMMITS_COUNT}
- **Ultima Tag Upstream:** \`${LATEST_UPSTREAM_TAG}\`
### Commits Recentes no Upstream:
\`\`\`
${NEW_COMMITS_LIST}
\`\`\`
---
## 2. Dependencia Central (Whatsmeow)
- **Versao Whatsmeow no go.mod local:** \`${LOCAL_WHATSMEOW}\`
---
## 3. Analise de Impacto e Conflitos
$([ "$NEW_COMMITS_COUNT" -gt 0 ] && echo "⚠ **Novidades detectadas no upstream!** Recomenda-se abrir branch de analise em \`maintenance/sync-upstream\`." || echo "✓ **Ambiente alinhado.** Nao ha novos commits pendentes na branch principal do upstream.")
---
*Relatorio gerado automaticamente pelo pipeline de monitoramento EvoGO.*
EOF
echo "Relatorio gerado em: ${REPORT_FILE}"
cat "${REPORT_FILE}"
-208
View File
@@ -1,208 +0,0 @@
#!/usr/bin/env bash
# Incorpora o upstream oficial na nossa distribuicao SEM sobrescrever nada nosso.
#
# Fluxo (idempotente, seguro para rodar todo dia):
# 1. fetch upstream/main + tags
# 2. fast-forward de origin/upstream-sync (push sem force: se nao for ff, falha e abre issue)
# 3. merge upstream/main -> branch maintenance/sync-upstream-<sha> criada a partir de maintained-develop
# - conflito -> aborta, abre Issue listando os arquivos em conflito
# - limpo -> go build / vet / test, push da branch e PR para maintained-develop
# 4. verifica se ha versao mais nova do go.mau.fi/whatsmeow e abre Issue de aviso
#
# maintained-develop e maintained-stable NUNCA recebem push deste script.
# Opcional: AUTO_MERGE=true faz merge automatico do PR em maintained-develop quando
# build e testes passam (nunca em maintained-stable).
#
# Variaveis: GITEA_URL, REPO (owner/name), GITEA_TOKEN, UPSTREAM_URL, BASE_BRANCH, AUTO_MERGE
set -euo pipefail
GITEA_URL="${GITEA_URL:-https://git.jf.eng.br}"
REPO="${REPO:-jfeng/EvoGO}"
UPSTREAM_URL="${UPSTREAM_URL:-https://github.com/evolution-foundation/evolution-go.git}"
UPSTREAM_BRANCH="${UPSTREAM_BRANCH:-main}"
BASE_BRANCH="${BASE_BRANCH:-maintained-develop}"
MIRROR_BRANCH="${MIRROR_BRANCH:-upstream-sync}"
AUTO_MERGE="${AUTO_MERGE:-false}"
API="${GITEA_URL%/}/api/v1/repos/${REPO}"
log() { echo "[upstream-sync] $*"; }
api() { # api METHOD PATH [JSON]
local method="$1" path="$2" data="${3:-}"
if [ -z "${GITEA_TOKEN:-}" ]; then
log "GITEA_TOKEN ausente; chamada ${method} ${path} ignorada"
return 1
fi
if [ -n "$data" ]; then
curl -fsS -X "$method" -H "Authorization: token ${GITEA_TOKEN}" -H "Content-Type: application/json" \
--data "$data" "${API}${path}"
else
curl -fsS -X "$method" -H "Authorization: token ${GITEA_TOKEN}" "${API}${path}"
fi
}
json_payload() { # json_payload key=file|key=@string ... -> JSON object
python3 - "$@" <<'PY'
import json, sys
out = {}
for arg in sys.argv[1:]:
k, v = arg.split("=", 1)
if v.startswith("@"):
out[k] = v[1:]
else:
out[k] = open(v, encoding="utf-8").read()
print(json.dumps(out))
PY
}
open_issue_once() { # open_issue_once TITLE BODY_FILE
local title="$1" body_file="$2" existing
existing=$(api GET "/issues?state=open&type=issues&limit=50" | python3 -c "
import json,sys
t=sys.argv[1]
print(next((str(i['number']) for i in json.load(sys.stdin) if i['title']==t),''))" "$title" || true)
if [ -n "$existing" ]; then
log "Issue ja aberta (#${existing}): ${title}"
return 0
fi
api POST "/issues" "$(json_payload "title=@${title}" "body=${body_file}")" >/dev/null && log "Issue aberta: ${title}"
}
git config user.name >/dev/null || git config user.name "EvoGO Upstream Bot"
git config user.email >/dev/null || git config user.email "[email protected]"
git remote get-url upstream >/dev/null 2>&1 || git remote add upstream "$UPSTREAM_URL"
git fetch --quiet upstream "$UPSTREAM_BRANCH" --tags
git fetch --quiet origin
UP_SHA=$(git rev-parse "upstream/${UPSTREAM_BRANCH}")
UP_SHORT=$(git rev-parse --short=7 "$UP_SHA")
REPORT=$(mktemp)
# --- 1. espelho upstream-sync (fast-forward apenas) -----------------------------
if git rev-parse --verify --quiet "origin/${MIRROR_BRANCH}" >/dev/null; then
if git merge-base --is-ancestor "$UP_SHA" "origin/${MIRROR_BRANCH}"; then
log "${MIRROR_BRANCH} ja contem upstream ${UP_SHORT}"
elif git merge-base --is-ancestor "origin/${MIRROR_BRANCH}" "$UP_SHA"; then
git push origin "${UP_SHA}:refs/heads/${MIRROR_BRANCH}"
log "${MIRROR_BRANCH} avancada (fast-forward) para ${UP_SHORT}"
else
printf '%s\n' "A branch \`${MIRROR_BRANCH}\` divergiu de \`upstream/${UPSTREAM_BRANCH}\` (${UP_SHORT})." \
"" "Nao foi feito push forcado. Verifique se o upstream reescreveu historico antes de prosseguir." > "$REPORT"
open_issue_once "upstream-sync: ${MIRROR_BRANCH} divergiu do upstream" "$REPORT" || true
exit 1
fi
else
git push origin "${UP_SHA}:refs/heads/${MIRROR_BRANCH}"
fi
# Tags do upstream (sem force: tags locais com mesmo nome nunca sao sobrescritas)
git push --quiet origin --tags 2>/dev/null || log "algumas tags nao foram enviadas (ja existem com outro alvo)"
# --- 2. ha algo novo para incorporar? ----------------------------------------------
if git merge-base --is-ancestor "$UP_SHA" "origin/${BASE_BRANCH}"; then
log "${BASE_BRANCH} ja incorpora upstream ${UP_SHORT}; nada a fazer"
else
SYNC_BRANCH="maintenance/sync-upstream-${UP_SHORT}"
if git rev-parse --verify --quiet "origin/${SYNC_BRANCH}" >/dev/null; then
log "branch ${SYNC_BRANCH} ja existe (PR pendente); nada a fazer"
else
NEW_COMMITS=$(git log --oneline --no-merges "origin/${BASE_BRANCH}..${UP_SHA}" | head -50)
SENSITIVE=$(git diff --stat "$(git merge-base "origin/${BASE_BRANCH}" "$UP_SHA")" "$UP_SHA" -- \
Dockerfile docker-compose* .env.example go.mod pkg/core cmd LICENSE NOTICE TRADEMARKS.md || true)
git checkout --quiet -B "$SYNC_BRANCH" "origin/${BASE_BRANCH}"
if ! git merge --no-ff --no-edit -m "sync: merge upstream ${UPSTREAM_BRANCH} ${UP_SHORT} into ${BASE_BRANCH}" "$UP_SHA"; then
CONFLICTS=$(git diff --name-only --diff-filter=U)
git merge --abort
{
echo "O merge automatico de \`upstream/${UPSTREAM_BRANCH}\` (${UP_SHORT}) em \`${BASE_BRANCH}\` gerou conflitos."
echo; echo "## Arquivos em conflito"; echo '```'; echo "$CONFLICTS"; echo '```'
echo; echo "## Commits novos do upstream"; echo '```'; echo "$NEW_COMMITS"; echo '```'
echo; echo "## Como resolver"
echo '```bash'
echo "git fetch origin && git fetch upstream"
echo "git checkout -b ${SYNC_BRANCH} origin/${BASE_BRANCH}"
echo "git merge upstream/${UPSTREAM_BRANCH} # resolver conflitos preservando as correcoes EvoGO"
echo "go build ./... && go vet ./... && go test ./..."
echo "git push origin ${SYNC_BRANCH} # e abrir PR para ${BASE_BRANCH}"
echo '```'
echo; echo "Veja docs/maintenance/UPSTREAM_SYNC.md."
} > "$REPORT"
open_issue_once "upstream-sync: conflito ao incorporar upstream ${UP_SHORT}" "$REPORT" || true
exit 0
fi
TEST_STATUS="nao executado (Go indisponivel)"
TESTS_OK=false
if command -v go >/dev/null 2>&1; then
if go build ./... > /tmp/sync-build.log 2>&1 && go vet ./... >> /tmp/sync-build.log 2>&1 \
&& go test ./... >> /tmp/sync-build.log 2>&1; then
TEST_STATUS="OK (go build, go vet, go test)"
TESTS_OK=true
else
TEST_STATUS="FALHOU — ver log abaixo"
fi
fi
git push --quiet origin "$SYNC_BRANCH"
{
echo "Incorporacao automatica de \`upstream/${UPSTREAM_BRANCH}\` (${UP_SHORT}) em \`${BASE_BRANCH}\`."
echo
echo "O merge foi feito por cima da nossa branch: todas as correcoes EvoGO continuam presentes."
echo
echo "**Build/testes:** ${TEST_STATUS}"
echo; echo "## Commits novos do upstream"; echo '```'; echo "$NEW_COMMITS"; echo '```'
if [ -n "$SENSITIVE" ]; then
echo; echo "## Arquivos sensiveis alterados (revisar com atencao)"; echo '```'; echo "$SENSITIVE"; echo '```'
fi
if [ "$TESTS_OK" != true ] && [ -f /tmp/sync-build.log ]; then
echo; echo "## Log de build/testes (final)"; echo '```'; tail -60 /tmp/sync-build.log; echo '```'
fi
echo; echo "## Checklist antes do merge"
echo "- [ ] Revisar commits e arquivos sensiveis"
echo "- [ ] Verificar mudancas de schema (whatsmeow / SQLite / Postgres)"
echo "- [ ] Testar imagem de homologacao (docs/maintenance/WHATSAPP_COMPATIBILITY.md)"
} > "$REPORT"
PR_JSON=$(api POST "/pulls" "$(json_payload "title=@sync: incorporar upstream ${UP_SHORT}" \
"head=@${SYNC_BRANCH}" "base=@${BASE_BRANCH}" "body=${REPORT}")" || true)
PR_NUMBER=$(printf '%s' "$PR_JSON" | python3 -c "import json,sys
try: print(json.load(sys.stdin)['number'])
except Exception: print('')")
log "PR aberto: #${PR_NUMBER:-?}"
if [ "$AUTO_MERGE" = "true" ] && [ "$TESTS_OK" = true ] && [ -n "$PR_NUMBER" ]; then
api POST "/pulls/${PR_NUMBER}/merge" '{"Do":"merge","delete_branch_after_merge":true}' >/dev/null \
&& log "PR #${PR_NUMBER} mesclado automaticamente em ${BASE_BRANCH}"
fi
fi
fi
# --- 3. whatsmeow mais novo disponivel? -------------------------------------------
if command -v go >/dev/null 2>&1; then
git checkout --quiet "origin/${BASE_BRANCH}"
CUR_WM=$(awk '$1=="go.mau.fi/whatsmeow"{print $2}' go.mod)
LATEST_WM=$(GOFLAGS=-mod=mod go list -m -f '{{.Version}}' go.mau.fi/whatsmeow@latest 2>/dev/null || true)
if [ -n "$LATEST_WM" ] && [ -n "$CUR_WM" ] && [ "$LATEST_WM" != "$CUR_WM" ]; then
{
echo "Ha uma versao mais nova de \`go.mau.fi/whatsmeow\`."
echo
echo "- Atual (${BASE_BRANCH}): \`${CUR_WM}\`"
echo "- Mais recente: \`${LATEST_WM}\`"
echo
echo "Defasagem do whatsmeow e a principal causa do erro **Client outdated (405)**."
echo "Atualize em uma branch \`maintenance/whatsmeow-<data>\`:"
echo '```bash'
echo "go get go.mau.fi/whatsmeow@latest && go mod tidy"
echo "go build ./... && go vet ./... && go test ./..."
echo '```'
} > "$REPORT"
open_issue_once "whatsmeow: atualizacao disponivel (${LATEST_WM})" "$REPORT" || true
else
log "whatsmeow em dia (${CUR_WM})"
fi
fi
rm -f "$REPORT"
log "concluido"