Author SHA1 Message Date
jfengandClaude Opus 5.5 0379082181 ci: daily upstream merge with PR/issue, tag-based image publishing
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 3m33s
Docker - Build e Publicacao / Build, Scan e Publicacao (push) Successful in 3m48s
- scripts/upstream-sync.sh + upstream-sync-check.yml: fast-forward upstream-sync,
  merge upstream into maintenance/sync-upstream-<sha> from maintained-develop,
  build/vet/test, open PR (or Issue on conflict), warn on newer whatsmeow.
  Optional AUTO_MERGE_UPSTREAM repo variable; maintained-stable never touched.
- docker-build.yml: publish git.jf.eng.br/jfeng/evogo:<version> and
  <version>-<sha7> on tag v*, startup smoke test, non-blocking Trivy scan,
  :latest only on explicit promote_latest.
- CHANGELOG and maintenance docs updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:12:32 -03:00
jfengandClaude Opus 5.5 e02441fc4e style: gofmt files touched by the community fixes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:12:30 -03:00
jfengandClaude Opus 5.5 abaac8eb93 fix(build): import waWa6 for ClientPayload_UserAgent_AppVersion
maintained-develop (after PR #1) did not compile: whatsmeow.go referenced an
undefined waProto package. The AppVersion type lives in
go.mau.fi/whatsmeow/proto/waWa6. Also gofmt the file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:12:27 -03:00
jfengandClaude Opus 5.5 4998ab3d45 fix(whatsmeow): harden client lifecycle against duplicate starts and races
- Skip a second StartClient while one is starting (adapted from upstream PR #239).
- Do not restart a client without a paired device; it would cycle QR codes
  forever (adapted from upstream PR #240).
- Serialize ReconnectClient per instance and nil-check the client: two
  Disconnected events in the same second dereferenced a removed client and
  killed the whole process (upstream issue #188).
- safemap.TrySend / TrySendTimeout: kill-channel sends no longer panic with
  "send on closed channel" when the instance is deleted during QR handling
  (upstream issue #222).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 12:04:18 -03:00
jfengandClaude Opus 5.5 74389cc8de fix(instance): do not clear event subscriptions on disconnect
Adapted from upstream PR #187 (guipratiko). Clearing instance.Events left the
instance with an empty events string after reconnecting, so CallWebhook dropped
every webhook.

Also send kill signals through safemap.TrySend/TrySendTimeout so a channel
closed by a concurrent instance delete no longer panics the process
(upstream issue #222).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 12:04:16 -03:00
jfengandClaude Opus 5.5 c33b4d98fd fix(utils): strip plus prefix from user JIDs in ParseJID
Adapted from upstream PR #224 (danie1net0). Queries addressed to
"+<number>@s.whatsapp.net" are never answered by WhatsApp and hang until
the IQ timeout (upstream issue #223: /user/info and /user/avatar hang 75s).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 12:04:14 -03:00
EcoosUP fc35d72029 fix(whatsmeow): back off the reconnect loop instead of spinning forever
An instance whose device was logged out from the phone never stops restarting:

    Disconnected -> ReconnectClient -> instance comes up with no session
    -> QR -> nobody scans -> max QR count -> forced logout -> Disconnected

Measured in production: 110 reconnects and 1135 QR codes in 50 minutes from a
single instance, stopping only when a human noticed.

Nothing counted those restarts, because from ReconnectClient's point of view
every turn succeeds — the instance really does come up. What fails afterwards is
the pairing, and nobody was measuring that.

The first 5 restarts inside a 15 minute window still go straight through: that
is the good case, a healthy instance that lost its websocket and has to return
within seconds. Past that the loop becomes a growing wait (5, 15, 30 minutes)
and the instance keeps trying — a backoff, not a give-up.

Only one goroutine waits per instance. Without that guard, every Disconnected
arriving during the wait would stack another one and the backoff would become
the loop it was written to stop.

(cherry picked from commit 3b52f1c457406dc2540f7e17467b6c30e9304f7b)
2026-11-09 12:01:35 -03:00
Guilherme Souza 3fce4dbcca fix(whatsmeow): share one sqlstore.Container for auth DB
StartClient called sqlstore.New on every instance start, opening a new
*sql.DB and re-running Upgrade against PostgresAuthDB. A few parallel
QR/reconnects saturated PgBouncer (75 = 60+15) with bad connection.

Reuse the pooled authDB from initPostgresAuthDB via NewWithDB + Upgrade
once (sync.Once on a heap-allocated sharedSQLStore so value-receiver
StartClient is safe). Users/GORM DB stays separate. Do not Close the
shared container on disconnect — main owns authDB.

(cherry picked from commit f2a73c715a286aefa5c10fa8521dccc7efa56581)
2026-11-09 12:01:15 -03:00
EcoosUP 0c4ac7d9a9 fix(concurrency): guard the three shared maps with a mutex
clientPointer, myClientPointer and killChannel are created once at startup and
passed by reference into eleven packages. All of them read and wrote those plain
Go maps from different goroutines, with no synchronisation.

Go does not tolerate that: 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: the process died inside StartClient while five instances
were connecting at once. The orchestrator restarted it within seconds, but every
number was offline in the meantime, and it repeats on any restart that brings up
more than a couple of instances together.

The three maps become safemap.Map[T], a generic wrapper over a RWMutex. It lives
in its own package because MyClient is defined in pkg/whatsmeow/service, and
putting the type there would create an import cycle with the ten packages that
receive the maps.

98 call sites changed across 12 files, with the compiler as the judge: anything
missed is a build error, not a silent bug.

Tests: with -race, a plain map running the same exercise reports DATA RACE and
fails, while safemap.Map passes. Both halves verified.

(cherry picked from commit 3860fa278dc2b901705ffbddbed5cf59d70a85e4)
2026-11-09 12:01:08 -03:00
prakash-dev-code a5f7e1c98a fix(websocket): deliver events to every subscriber of an instance
The websocket producer kept a single connection per instance in
`clients map[string]*websocket.Conn`. Registering a second subscriber
silently replaced the first, and `RemoveClient` deleted the whole instance
entry when either one disconnected. Consuming events in two browser tabs
therefore delivered to only the most recent one, and closing that tab cut
delivery for the remaining subscriber too.

Changes:

- `clients` becomes `map[string][]*client`. Deregistration now matches the
  specific connection instead of removing the instance entry, so sibling
  subscribers keep receiving events.
- Each connection carries its own write mutex. Events are dispatched from
  independent goroutines (the `go CallWebhook` calls in the whatsmeow event
  handler) and gorilla/websocket permits only one concurrent writer per
  connection, so two simultaneous events could interleave writes on the
  same socket.
- `Produce` snapshots the subscriber list under the read lock and performs
  writes outside it, so a slow or half-open socket no longer blocks
  deliveries for other instances.
- Failed writes prune the dead connection, and `Produce` now returns nil.
  `sendToQueueOrWebhook` aborts the remaining producers when one returns an
  error, so a closed browser tab previously suppressed RabbitMQ, NATS and
  webhook delivery for that same event.

Verified with two concurrent subscribers on one instance: both receive
identical event streams, and disconnecting one leaves the other unaffected.

(cherry picked from commit 1db4408244fe75b39c2b4e1bbb8e681679dd7dae)
2026-11-09 12:01:02 -03:00
lojanica a0c74485b8 test(nats): refactor tests and add global events state assertion
(cherry picked from commit 1860110296ea775734752be8a40b93726c34ff27)
2026-11-09 12:01:00 -03:00
root a4add7cc5e fix: skip NATS connection when URL is empty
(cherry picked from commit a3c05b41717bc652ef7736cc2c2b22c4eaed0f5d)
2026-11-09 12:01:00 -03:00
EcoosUP 3cc5192b7b fix(whatsmeow): Archive event panics before reaching the webhook
The Archive case asserts postMap["data"] to map[string]interface{}, but at that
point it still holds the raw *events.Archive. The assertion panics on every
archive event:

    Event handler panicked while handling a *events.Archive:
    interface conversion: interface {} is *events.Archive,
    not map[string]interface {}

whatsmeow recovers the panic and logs it, so nothing crashes — the event simply
never reaches the webhook, silently.

Every other case in this switch marshals and unmarshals postMap["data"] into a
map before asserting. Archive was the only one missing that step. Six call sites
do the assertion; the other five are already guarded.

(cherry picked from commit 16c4be6e9a0ae8a0bbc41f8b2790a362a7a4e2e2)
2026-11-09 12:00:59 -03:00
jfeng 87a354aee8 Merge pull request 'fix: resolver erro Client outdated (405) com whatsmeow atualizado e handshake dinamico' (#1) from fix/client-outdated-405 into maintained-develop
CI - Validacao Go / Validar Codigo e Testes (push) Failing after 2m15s
Reviewed-on: #1
2026-11-09 14:45:05 +00:00
25 changed files with 1192 additions and 297 deletions

No files matched your search

+83 -38
View File
@@ -1,11 +1,19 @@
name: Docker - Build e Publicacao 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)
# :latest so e atualizada com promote_latest=true (manual), nunca automaticamente.
on: on:
push: push:
branches: branches:
- maintained-stable - maintained-stable
tags: tags:
- 'v*.*.*' - 'v*'
workflow_dispatch: workflow_dispatch:
inputs: inputs:
publish_image: publish_image:
@@ -14,14 +22,23 @@ on:
default: false default: false
required: true required: true
target_tag: target_tag:
description: 'Tag semantica para publicacao (ex: 0.7.2)' description: 'Tag semantica para publicacao (ex: 0.7.2-evogo.1). Vazio = arquivo VERSION'
type: string type: string
default: '' default: ''
required: false required: false
promote_latest:
description: 'Tambem atualizar :latest (somente versoes aprovadas em maintained-stable)'
type: boolean
default: false
required: false
env:
REGISTRY: git.jf.eng.br
IMAGE: git.jf.eng.br/jfeng/evogo
jobs: jobs:
build_docker: build_docker:
name: Build e Verificacao Docker name: Build, Scan e Publicacao
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -31,44 +48,72 @@ jobs:
- name: Obter Versao e Commit SHA - name: Obter Versao e Commit SHA
id: meta id: meta
run: | run: |
VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
COMMIT_SHA=$(echo "${{ github.sha }}" | cut -c1-7) COMMIT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
echo "version=${VERSION}" >> $GITHUB_OUTPUT if [ "${{ github.ref_type }}" = "tag" ]; then
echo "commit_sha=${COMMIT_SHA}" >> $GITHUB_OUTPUT VERSION="${{ github.ref_name }}"
echo "image_tag=${VERSION}-${COMMIT_SHA}" >> $GITHUB_OUTPUT VERSION="${VERSION#v}"
PUBLISH=true
- name: Configurar Docker Buildx else
uses: docker/setup-buildx-action@v3 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 - name: Construir Imagem Docker Local
uses: docker/build-push-action@v5
with:
context: .
load: true
tags: evogo:local
build-args: |
VERSION=${{ steps.meta.outputs.image_tag }}
- name: Testar Execucao Basica do Container
run: | run: |
docker run --rm evogo:local --help || echo "Container executou verificacao inicial com sucesso" docker build \
--build-arg VERSION=${{ steps.meta.outputs.image_tag }} \
-t evogo:ci-${{ steps.meta.outputs.commit_sha }} .
- name: Login no Gitea Package Registry (se aprovado) - name: Testar Inicializacao do Container
if: ${{ github.event.inputs.publish_image == 'true' || github.event.inputs.publish_image == true }} run: |
uses: docker/login-action@v3 # O binario precisa subir e falhar apenas por falta de banco/config,
with: # nunca por erro de link (CGO/libwebp/libjpeg) ou arquivo ausente.
registry: git.jf.eng.br set +e
username: ${{ secrets.REGISTRY_USER || github.actor }} timeout 20 docker run --rm evogo:ci-${{ steps.meta.outputs.commit_sha }} > /tmp/run.log 2>&1
password: ${{ secrets.REGISTRY_TOKEN || secrets.GITEA_TOKEN }} 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: Publicar Imagens no Registry (apenas com aprovacao expressa) - name: Verificar Vulnerabilidades (Trivy, nao bloqueante)
if: ${{ github.event.inputs.publish_image == 'true' || github.event.inputs.publish_image == true }} continue-on-error: true
uses: docker/build-push-action@v5 run: |
with: docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest \
context: . image --severity HIGH,CRITICAL --ignore-unfixed --no-progress \
push: true evogo:ci-${{ steps.meta.outputs.commit_sha }}
tags: |
git.jf.eng.br/jfeng/evogo:${{ steps.meta.outputs.image_tag }} - name: Login no Gitea Package Registry
git.jf.eng.br/jfeng/evogo:${{ steps.meta.outputs.version }} if: steps.meta.outputs.publish == 'true'
build-args: | run: |
VERSION=${{ steps.meta.outputs.image_tag }} USER="${{ secrets.REGISTRY_USER }}"
[ -n "$USER" ] || USER="${{ github.actor }}"
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin
- name: Publicar Imagens no Registry
if: steps.meta.outputs.publish == 'true'
run: |
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"
docker push "$IMAGE:$TAG"
echo "Publicado: $IMAGE:$TAG"
done
if [ "${{ github.event.inputs.promote_latest }}" = "true" ]; then
docker tag "$SRC" "$IMAGE:latest"
docker push "$IMAGE:latest"
echo "Publicado: $IMAGE:latest"
fi
- name: Limpeza
if: always()
run: docker image rm -f evogo:ci-${{ steps.meta.outputs.commit_sha }} >/dev/null 2>&1 || true
+37 -13
View File
@@ -1,29 +1,53 @@
name: Monitoramento Diario do Upstream 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: on:
schedule: schedule:
# Executa diariamente as 04:00 UTC (01:00 BRT) # Diariamente as 04:00 UTC (01:00 BRT)
- cron: '0 4 * * *' - cron: '0 4 * * *'
workflow_dispatch: workflow_dispatch:
concurrency:
group: upstream-sync
cancel-in-progress: false
jobs: jobs:
check_upstream: sync:
name: Verificar Atualizacoes do Upstream e Whatsmeow name: Incorporar upstream e verificar whatsmeow
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout do Repositorio - name: Checkout do Repositorio
uses: actions/checkout@v4 uses: actions/checkout@v4
with: with:
ref: maintained-develop
fetch-depth: 0 fetch-depth: 0
token: ${{ secrets.GITEA_TOKEN }}
- name: Executar Script de Verificacao - name: Configurar Go
id: check uses: actions/setup-go@v5
run: |
bash scripts/check-upstream-updates.sh
- name: Salvar Relatorio como Artefato
uses: actions/upload-artifact@v4
with: with:
name: relatorio-upstream-${{ github.run_id }} go-version-file: go.mod
path: relatorio_atualizacao_*.md
- 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
+30
View File
@@ -18,6 +18,36 @@
- **Migração automática do banco de autenticação** — o schema do whatsmeow sobe - **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 de v14 para v16 (`companion_meta_nonce`, `wasa_root_secret_id`). Roda sozinho
ao abrir o container; testado com banco SQLite v14 existente. 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`.
### 🛡️ 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.
## v0.7.2 ## v0.7.2
+3 -2
View File
@@ -5,6 +5,7 @@ import (
"database/sql" "database/sql"
"flag" "flag"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"log" "log"
"net/http" "net/http"
"os" "os"
@@ -83,8 +84,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 { 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 := make(map[string](chan bool)) killChannel := safemap.New[chan bool]()
clientPointer := make(map[string]*whatsmeow.Client) clientPointer := safemap.New[*whatsmeow.Client]()
loggerWrapper := logger_wrapper.NewLoggerManager(config) loggerWrapper := logger_wrapper.NewLoggerManager(config)
+29 -8
View File
@@ -82,11 +82,32 @@ docker build \
O pipeline é orquestrado via `.gitea/workflows/docker-build.yml`: O pipeline é orquestrado via `.gitea/workflows/docker-build.yml`:
1. **Trigger em Pull Requests ou Push em develop:** 1. **Push em `maintained-stable`:** build da imagem (`linux/amd64`), teste de
- Executa `go vet` e `go test`. inicialização do binário e scan Trivy (HIGH/CRITICAL, não bloqueante).
- Executa `docker build` para garantir que a imagem compila sem erros. **Não publica.**
- **Não faz push** para o registry. 2. **Push de tag `v<versão>` (release aprovado):** mesmo build/teste/scan e
2. **Trigger em Tag ou Push em `maintained-stable`:** publicação de:
- Constrói a imagem multiplataforma (`linux/amd64`, `linux/arm64`). - `git.jf.eng.br/jfeng/evogo:<versão>-<sha7>` (imutável)
- Gera tag imutável associada ao commit. - `git.jf.eng.br/jfeng/evogo:<versão>`
- Requer aprovação ou execução via `workflow_dispatch` para publicação em produção. 3. **`workflow_dispatch`:** publica apenas com `publish_image=true`; `:latest`
só com `promote_latest=true`.
### Gerar um release
```bash
git checkout maintained-develop && git pull
git tag -a v0.7.2-evogo.1 -m "EvoGO 0.7.2-evogo.1"
git push origin v0.7.2-evogo.1 # dispara o build e a publicação
```
### 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>`.
+30 -4
View File
@@ -26,7 +26,33 @@ git remote add upstream https://github.com/evolution-foundation/evolution-go.git
--- ---
## 2. Fluxo de Trabalho de Sincronização ## 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. A sincronização **NUNCA** deve sobrescrever diretamente a branch `maintained-stable` ou branches ativas de desenvolvimento sem validação.
@@ -57,7 +83,7 @@ git push origin upstream-sync --tags
--- ---
## 3. Integração e Análise de Impacto ## 4. Integração e Análise de Impacto
### Etapa 4: Criar branch de teste e integração ### 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: A partir de `maintained-develop`, crie uma branch de manutenção específica para a atualização:
@@ -80,7 +106,7 @@ Se houver conflitos:
--- ---
## 4. Validação Pós-Sincronização ## 5. Validação Pós-Sincronização
Antes de propor a integração para as branches mantidas: Antes de propor a integração para as branches mantidas:
@@ -102,7 +128,7 @@ Antes de propor a integração para as branches mantidas:
--- ---
## 5. Promoção para as Branches Oficiais ## 6. Promoção para as Branches Oficiais
1. **Abra um Pull Request no Gitea:** 1. **Abra um Pull Request no Gitea:**
- Origem: `maintenance/sync-upstream-<nova-versao>` - Origem: `maintenance/sync-upstream-<nova-versao>`
+5 -4
View File
@@ -3,6 +3,7 @@ package call_service
import ( import (
"context" "context"
"errors" "errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time" "time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model" instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -18,7 +19,7 @@ type CallService interface {
} }
type callService struct { type callService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -29,7 +30,7 @@ type RejectCallStruct struct {
} }
func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer[instanceId] client := c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -43,7 +44,7 @@ func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = c.clientPointer[instanceId] client = c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -83,7 +84,7 @@ func (c *callService) RejectCall(data *RejectCallStruct, instance *instance_mode
} }
func NewCallService( func NewCallService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) CallService { ) CallService {
+5 -4
View File
@@ -3,6 +3,7 @@ package chat_service
import ( import (
"context" "context"
"errors" "errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time" "time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model" instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -25,7 +26,7 @@ type ChatService interface {
} }
type chatService struct { type chatService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -40,7 +41,7 @@ type HistorySyncRequestStruct struct {
} }
func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer[instanceId] client := c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -54,7 +55,7 @@ func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = c.clientPointer[instanceId] client = c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -244,7 +245,7 @@ func (c *chatService) HistorySyncRequest(data *HistorySyncRequestStruct, instanc
} }
func NewChatService( func NewChatService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) ChatService { ) ChatService {
+5 -4
View File
@@ -3,6 +3,7 @@ package community_service
import ( import (
"context" "context"
"errors" "errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time" "time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model" instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -21,7 +22,7 @@ type CommunityService interface {
} }
type communityService struct { type communityService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -36,7 +37,7 @@ type AddParticipantStruct struct {
} }
func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := c.clientPointer[instanceId] client := c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -50,7 +51,7 @@ func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = c.clientPointer[instanceId] client = c.clientPointer.Get(instanceId)
c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -157,7 +158,7 @@ func (c *communityService) CommunityRemove(data *AddParticipantStruct, instance
} }
func NewCommunityService( func NewCommunityService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) CommunityService { ) CommunityService {
+10
View File
@@ -5,6 +5,7 @@ import (
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger" logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/gomessguii/logger" "github.com/gomessguii/logger"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
"strings"
) )
type natsProducer struct { type natsProducer struct {
@@ -20,6 +21,15 @@ func NewNatsProducer(
natsGlobalEvents []string, natsGlobalEvents []string,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) producer_interfaces.Producer { ) producer_interfaces.Producer {
if strings.TrimSpace(url) == "" {
return &natsProducer{
conn: nil,
natsGlobalEnabled: false,
natsGlobalEvents: nil,
loggerWrapper: loggerWrapper,
}
}
conn, err := nats.Connect(url) conn, err := nats.Connect(url)
if err != nil { if err != nil {
logger.LogError("Failed to connect to NATS: %v", err) logger.LogError("Failed to connect to NATS: %v", err)
+31
View File
@@ -0,0 +1,31 @@
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")
}
})
}
}
+118 -65
View File
@@ -14,92 +14,131 @@ var upgrader = websocket.Upgrader{
ReadBufferSize: 1024, ReadBufferSize: 1024,
WriteBufferSize: 1024, WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { CheckOrigin: func(r *http.Request) bool {
logger.LogInfo("Verificando origem da conexão WebSocket")
return true 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 { type websocketProducer struct {
clients map[string]*websocket.Conn // conexões específicas por instância // clients holds every connection subscribed to a given instance. This is a
broadcast []*websocket.Conn // conexões que recebem todos os eventos // 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
clientsMux sync.RWMutex clientsMux sync.RWMutex
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
func NewWebsocketProducer(loggerWrapper *logger_wrapper.LoggerManager) *websocketProducer { func NewWebsocketProducer(loggerWrapper *logger_wrapper.LoggerManager) *websocketProducer {
return &websocketProducer{ return &websocketProducer{
clients: make(map[string]*websocket.Conn), clients: make(map[string][]*client),
broadcast: make([]*websocket.Conn, 0), broadcast: make([]*client, 0),
clientsMux: sync.RWMutex{},
loggerWrapper: loggerWrapper, loggerWrapper: loggerWrapper,
} }
} }
// ServeWs lida com as requisições de upgrade para websocket // ServeWs upgrades an HTTP request and registers it for the lifetime of the
// connection. An empty instanceId subscribes to every instance's events.
func ServeWs(w http.ResponseWriter, r *http.Request, instanceId string, producer *websocketProducer) { 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) conn, err := upgrader.Upgrade(w, r, nil)
if err != nil { if err != nil {
logger.LogError("Erro ao fazer upgrade da conexão websocket: %v", err) logger.LogError("Erro ao fazer upgrade da conexão websocket: %v", err)
return return
} }
logger.LogInfo("Conexão WebSocket estabelecida com sucesso") c := &client{conn: conn}
if instanceId == "" { if instanceId == "" {
producer.AddBroadcastClient(conn) producer.addBroadcastClient(c)
} else { } else {
producer.AddClient(instanceId, conn) producer.addClient(instanceId, c)
} }
// Goroutine para limpar conexão quando fechada // 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.
go func() { go func() {
defer func() {
if instanceId == "" {
producer.removeBroadcastClient(c)
} else {
producer.removeClient(instanceId, c)
}
_ = conn.Close()
}()
for { for {
_, _, err := conn.ReadMessage() if _, _, err := conn.ReadMessage(); err != nil {
if err != nil { return
if instanceId == "" {
producer.RemoveBroadcastClient(conn)
} else {
producer.RemoveClient(instanceId)
}
conn.Close()
break
} }
} }
}() }()
} }
func (p *websocketProducer) AddBroadcastClient(conn *websocket.Conn) { func (p *websocketProducer) addBroadcastClient(c *client) {
p.clientsMux.Lock() p.clientsMux.Lock()
defer p.clientsMux.Unlock() p.broadcast = append(p.broadcast, c)
p.broadcast = append(p.broadcast, conn) n := len(p.broadcast)
logger.LogInfo("Cliente broadcast websocket adicionado") p.clientsMux.Unlock()
logger.LogInfo("Cliente broadcast websocket adicionado (total: %d)", n)
} }
func (p *websocketProducer) RemoveBroadcastClient(conn *websocket.Conn) { func (p *websocketProducer) removeBroadcastClient(c *client) {
p.clientsMux.Lock() p.clientsMux.Lock()
defer p.clientsMux.Unlock() p.broadcast = drop(p.broadcast, c)
for i, c := range p.broadcast { n := len(p.broadcast)
if c == conn { p.clientsMux.Unlock()
p.broadcast = append(p.broadcast[:i], p.broadcast[i+1:]...) logger.LogInfo("Cliente broadcast websocket removido (total: %d)", n)
break }
func (p *websocketProducer) addClient(instanceID string, c *client) {
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)
}
func (p *websocketProducer) removeClient(instanceID string, c *client) {
p.clientsMux.Lock()
remaining := drop(p.clients[instanceID], c)
if len(remaining) == 0 {
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)
} }
} }
logger.LogInfo("Cliente broadcast websocket removido") return out
}
func (p *websocketProducer) AddClient(instanceID string, conn *websocket.Conn) {
p.clientsMux.Lock()
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) {
p.clientsMux.Lock()
defer p.clientsMux.Unlock()
delete(p.clients, instanceID)
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 { func (p *websocketProducer) Produce(queueName string, payload []byte, instanceID string, _ string) error {
@@ -108,29 +147,43 @@ func (p *websocketProducer) Produce(queueName string, payload []byte, instanceID
"payload": string(payload), "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() p.clientsMux.RLock()
defer p.clientsMux.RUnlock() targets := append([]*client(nil), p.clients[instanceID]...)
targets = append(targets, p.broadcast...)
p.clientsMux.RUnlock()
// Envia para cliente específico da instância var failed []*client
if client, exists := p.clients[instanceID]; exists { for _, c := range targets {
err := client.WriteJSON(message) if err := c.writeJSON(message); err != nil {
if err != nil { p.loggerWrapper.GetLogger(instanceID).LogError(
p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem websocket para %s: %v", instanceID, err) "Erro ao enviar mensagem websocket para %s: %v", instanceID, err)
// Não remove o cliente aqui pois estamos com o RLock failed = append(failed, c)
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 return nil
} }
+5 -4
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"io" "io"
"net/http" "net/http"
"strings" "strings"
@@ -37,7 +38,7 @@ type GroupService interface {
} }
type groupService struct { type groupService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -117,7 +118,7 @@ type UpdateGroupRequestParticipantsStruct struct {
} }
func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := g.clientPointer[instanceId] client := g.clientPointer.Get(instanceId)
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -131,7 +132,7 @@ func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Clie
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = g.clientPointer[instanceId] client = g.clientPointer.Get(instanceId)
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -641,7 +642,7 @@ func (g *groupService) UpdateGroupRequestParticipants(data *UpdateGroupRequestPa
} }
func NewGroupService( func NewGroupService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) GroupService { ) GroupService {
+49 -55
View File
@@ -7,6 +7,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"os" "os"
"path/filepath" "path/filepath"
"slices" "slices"
@@ -50,8 +51,8 @@ type InstanceService interface {
type instances struct { type instances struct {
instanceRepository instance_repository.InstanceRepository instanceRepository instance_repository.InstanceRepository
config *config.Config config *config.Config
killChannel map[string](chan bool) killChannel *safemap.Map[chan bool]
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -124,7 +125,7 @@ type ForceReconnectStruct struct {
func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
logger := i.loggerWrapper.GetLogger(instanceId) logger := i.loggerWrapper.GetLogger(instanceId)
client := i.clientPointer[instanceId] client := i.clientPointer.Get(instanceId)
logger.LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) logger.LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -138,7 +139,7 @@ func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client,
logger.LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) logger.LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = i.clientPointer[instanceId] client = i.clientPointer.Get(instanceId)
logger.LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", logger.LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -242,7 +243,7 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
} }
// Verifica se a instância já está rodando // Verifica se a instância já está rodando
isInstanceRunning := i.clientPointer[instance.Id] != nil isInstanceRunning := i.clientPointer.Get(instance.Id) != nil
// Sincroniza as configurações na instância em execução (se já estiver conectada) // Sincroniza as configurações na instância em execução (se já estiver conectada)
err = i.whatsmeowService.UpdateInstanceSettings(instance.Id) err = i.whatsmeowService.UpdateInstanceSettings(instance.Id)
@@ -258,7 +259,7 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
if !isInstanceRunning { if !isInstanceRunning {
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting new client instance", instance.Id) i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting new client instance", instance.Id)
i.killChannel[instance.Id] = make(chan bool) i.killChannel.Set(instance.Id, make(chan bool))
clientData := &whatsmeow_service.ClientData{ clientData := &whatsmeow_service.ClientData{
Instance: instance, Instance: instance,
@@ -288,8 +289,8 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
// logger.LogInfo("Waiting 1 seconds") // logger.LogInfo("Waiting 1 seconds")
// time.Sleep(1000 * time.Millisecond) // time.Sleep(1000 * time.Millisecond)
// if i.clientPointer[instance.Id] != nil { // if i.clientPointer.Get(instance.Id) != nil {
// if !i.clientPointer[instance.Id].IsConnected() { // if !i.clientPointer.Get(instance.Id).IsConnected() {
// return instance, "", "", fmt.Errorf("failed to connect") // return instance, "", "", fmt.Errorf("failed to connect")
// } // }
// } else { // } else {
@@ -317,12 +318,14 @@ func (i instances) Disconnect(instance *instance_model.Instance) (*instance_mode
if client.IsConnected() { if client.IsConnected() {
if client.IsLoggedIn() { if client.IsLoggedIn() {
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id) i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
i.killChannel[instance.Id] <- true safemap.TrySend(i.killChannel.Get(instance.Id), true)
instance.Events = "" // Do not clear instance.Events on disconnect (upstream PR #187): an
// empty events string makes CallWebhook drop every webhook after the
err := i.instanceRepository.Update(instance) // instance reconnects.
if err != nil { instance.Connected = false
instance.DisconnectReason = "Disconnected by API"
if err := i.instanceRepository.UpdateConnected(instance.Id, false, instance.DisconnectReason); err != nil {
return instance, err return instance, err
} }
@@ -352,13 +355,10 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
return instance, err return instance, err
} }
select { safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
case i.killChannel[instance.Id] <- true:
case <-time.After(5 * time.Second):
}
delete(i.clientPointer, instance.Id) i.clientPointer.Delete(instance.Id)
delete(i.killChannel, instance.Id) i.killChannel.Delete(instance.Id)
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Logout successful", instance.Id) i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Logout successful", instance.Id)
return instance, nil return instance, nil
@@ -367,13 +367,10 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
if client.IsConnected() { if client.IsConnected() {
client.Disconnect() client.Disconnect()
select { safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
case i.killChannel[instance.Id] <- true:
case <-time.After(5 * time.Second):
}
delete(i.clientPointer, instance.Id) i.clientPointer.Delete(instance.Id)
delete(i.killChannel, instance.Id) i.killChannel.Delete(instance.Id)
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id) i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
return instance, nil return instance, nil
@@ -384,7 +381,7 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
} }
func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, error) { func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, error) {
client := i.clientPointer[instance.Id] client := i.clientPointer.Get(instance.Id)
if client == nil { if client == nil {
return &StatusStruct{ return &StatusStruct{
@@ -413,7 +410,7 @@ func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, err
func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, error) { func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, error) {
logger := i.loggerWrapper.GetLogger(instance.Id) logger := i.loggerWrapper.GetLogger(instance.Id)
client := i.clientPointer[instance.Id] client := i.clientPointer.Get(instance.Id)
// Se não há cliente ou o cliente está logado, precisamos iniciar um novo cliente // Se não há cliente ou o cliente está logado, precisamos iniciar um novo cliente
if client == nil || client.IsLoggedIn() { if client == nil || client.IsLoggedIn() {
@@ -435,7 +432,7 @@ func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, erro
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
// Verificar novamente se há cliente // Verificar novamente se há cliente
client = i.clientPointer[instance.Id] client = i.clientPointer.Get(instance.Id)
if client != nil && client.IsLoggedIn() { if client != nil && client.IsLoggedIn() {
return nil, fmt.Errorf("session already logged in") return nil, fmt.Errorf("session already logged in")
} }
@@ -511,7 +508,7 @@ func buildPasskeyOpenURL(token string) string {
func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error) { func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error) {
logger := i.loggerWrapper.GetLogger(instance.Id) logger := i.loggerWrapper.GetLogger(instance.Id)
client := i.clientPointer[instance.Id] client := i.clientPointer.Get(instance.Id)
if client == nil || !client.IsConnected() { if client == nil || !client.IsConnected() {
if client != nil && client.IsLoggedIn() { if client != nil && client.IsLoggedIn() {
@@ -525,7 +522,7 @@ func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*P
// Wait for the WA websocket connection and initial QR generation to establish. // 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. // PairPhone must be called after the QR event is received per whatsmeow docs.
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
client = i.clientPointer[instance.Id] client = i.clientPointer.Get(instance.Id)
if client == nil { if client == nil {
return nil, fmt.Errorf("failed to initialize client for pairing") return nil, fmt.Errorf("failed to initialize client for pairing")
} }
@@ -551,7 +548,7 @@ func (i instances) GetAll() ([]*instance_model.Instance, error) {
} }
for _, instance := range instances { for _, instance := range instances {
if client := i.clientPointer[instance.Id]; client != nil { if client := i.clientPointer.Get(instance.Id); client != nil {
instance.Connected = client.IsLoggedIn() instance.Connected = client.IsLoggedIn()
} else { } else {
instance.Connected = false instance.Connected = false
@@ -570,7 +567,7 @@ func (i instances) Info(instanceId string) (*instance_model.Instance, error) {
} }
// Atualiza o status connected com base no estado real do cliente // Atualiza o status connected com base no estado real do cliente
if client := i.clientPointer[instance.Id]; client != nil { if client := i.clientPointer.Get(instance.Id); client != nil {
instance.Connected = client.IsLoggedIn() instance.Connected = client.IsLoggedIn()
} else { } else {
instance.Connected = false instance.Connected = false
@@ -587,18 +584,18 @@ func (i instances) Delete(id string) error {
return err return err
} }
if i.clientPointer[instance.Id] != nil && i.clientPointer[instance.Id].IsConnected() { if i.clientPointer.Get(instance.Id) != nil && i.clientPointer.Get(instance.Id).IsConnected() {
if i.clientPointer[instance.Id].IsLoggedIn() { if i.clientPointer.Get(instance.Id).IsLoggedIn() {
i.clientPointer[instance.Id].Logout(context.Background()) i.clientPointer.Get(instance.Id).Logout(context.Background())
} }
i.clientPointer[instance.Id].Disconnect() i.clientPointer.Get(instance.Id).Disconnect()
} }
// Limpar todos os recursos da instância antes de deletar // Limpar todos os recursos da instância antes de deletar
delete(i.clientPointer, instance.Id) i.clientPointer.Delete(instance.Id)
if i.killChannel[instance.Id] != nil { if i.killChannel.Get(instance.Id) != nil {
close(i.killChannel[instance.Id]) close(i.killChannel.Get(instance.Id))
delete(i.killChannel, instance.Id) i.killChannel.Delete(instance.Id)
} }
// Limpar cache via whatsmeow service // Limpar cache via whatsmeow service
@@ -697,7 +694,7 @@ func (i instances) RemoveProxy(id string) error {
} }
func (i instances) ForceReconnect(instanceId string, number string) error { func (i instances) ForceReconnect(instanceId string, number string) error {
if i.clientPointer[instanceId].IsConnected() && i.clientPointer[instanceId].IsLoggedIn() { if i.clientPointer.Get(instanceId).IsConnected() && i.clientPointer.Get(instanceId).IsLoggedIn() {
return fmt.Errorf("client already connected") return fmt.Errorf("client already connected")
} }
@@ -713,7 +710,7 @@ func (i instances) ForceReconnect(instanceId string, number string) error {
subscribedEvents := strings.Split(instance.Events, ",") subscribedEvents := strings.Split(instance.Events, ",")
i.killChannel[instance.Id] = make(chan bool) i.killChannel.Set(instance.Id, make(chan bool))
clientData := &whatsmeow_service.ClientData{ clientData := &whatsmeow_service.ClientData{
Instance: instance, Instance: instance,
@@ -735,29 +732,26 @@ func (i instances) ForceReconnect(instanceId string, number string) error {
} }
} }
if i.clientPointer[instance.Id] != nil { if i.clientPointer.Get(instance.Id) != nil {
client := i.clientPointer[instance.Id] client := i.clientPointer.Get(instance.Id)
client.Disconnect() client.Disconnect()
select { safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
case i.killChannel[instance.Id] <- true:
case <-time.After(5 * time.Second):
}
delete(i.clientPointer, instance.Id) i.clientPointer.Delete(instance.Id)
delete(i.killChannel, instance.Id) i.killChannel.Delete(instance.Id)
} }
go i.whatsmeowService.StartClient(clientData) go i.whatsmeowService.StartClient(clientData)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
if i.clientPointer[instance.Id] != nil { if i.clientPointer.Get(instance.Id) != nil {
if !i.clientPointer[instance.Id].IsConnected() { if !i.clientPointer.Get(instance.Id).IsConnected() {
return fmt.Errorf("failed to connect") return fmt.Errorf("failed to connect")
} }
if !i.clientPointer[instance.Id].IsLoggedIn() { if !i.clientPointer.Get(instance.Id).IsLoggedIn() {
return fmt.Errorf("failed to login") return fmt.Errorf("failed to login")
} }
} else { } else {
@@ -912,8 +906,8 @@ func (i instances) UpdateAdvancedSettings(instanceId string, settings *instance_
func NewInstanceService( func NewInstanceService(
instanceRepository instance_repository.InstanceRepository, instanceRepository instance_repository.InstanceRepository,
killChannel map[string](chan bool), killChannel *safemap.Map[chan bool],
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
config *config.Config, config *config.Config,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
+5 -4
View File
@@ -3,6 +3,7 @@ package label_service
import ( import (
"context" "context"
"errors" "errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time" "time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model" instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -25,7 +26,7 @@ type LabelService interface {
} }
type labelService struct { type labelService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
labelRepository label_repository.LabelRepository labelRepository label_repository.LabelRepository
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
@@ -50,7 +51,7 @@ type EditLabelStruct struct {
} }
func (l *labelService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (l *labelService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := l.clientPointer[instanceId] client := l.clientPointer.Get(instanceId)
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -64,7 +65,7 @@ func (l *labelService) ensureClientConnected(instanceId string) (*whatsmeow.Clie
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = l.clientPointer[instanceId] client = l.clientPointer.Get(instanceId)
l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -226,7 +227,7 @@ func (l *labelService) GetLabels(instance *instance_model.Instance) ([]label_mod
} }
func NewLabelService( func NewLabelService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
labelRepository label_repository.LabelRepository, labelRepository label_repository.LabelRepository,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
+5 -4
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"net/http" "net/http"
"os" "os"
"strings" "strings"
@@ -35,7 +36,7 @@ type MessageService interface {
} }
type messageService struct { type messageService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
messageRepository message_repository.MessageRepository messageRepository message_repository.MessageRepository
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
@@ -95,7 +96,7 @@ type MessageSendStruct struct {
} }
func (m *messageService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (m *messageService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := m.clientPointer[instanceId] client := m.clientPointer.Get(instanceId)
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -109,7 +110,7 @@ func (m *messageService) ensureClientConnected(instanceId string) (*whatsmeow.Cl
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = m.clientPointer[instanceId] client = m.clientPointer.Get(instanceId)
m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -526,7 +527,7 @@ func (m *messageService) EditMessage(data *EditMessageStruct, instance *instance
} }
func NewMessageService( func NewMessageService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
messageRepository message_repository.MessageRepository, messageRepository message_repository.MessageRepository,
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
+5 -4
View File
@@ -3,6 +3,7 @@ package newsletter_service
import ( import (
"context" "context"
"errors" "errors"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"time" "time"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model" instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
@@ -22,7 +23,7 @@ type NewsletterService interface {
} }
type newsletterService struct { type newsletterService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -47,7 +48,7 @@ type GetNewsletterMessagesStruct struct {
} }
func (n *newsletterService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (n *newsletterService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := n.clientPointer[instanceId] client := n.clientPointer.Get(instanceId)
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -61,7 +62,7 @@ func (n *newsletterService) ensureClientConnected(instanceId string) (*whatsmeow
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = n.clientPointer[instanceId] client = n.clientPointer.Get(instanceId)
n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -195,7 +196,7 @@ func (n *newsletterService) GetNewsletterMessages(data *GetNewsletterMessagesStr
} }
func NewNewsletterService( func NewNewsletterService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) NewsletterService { ) NewsletterService {
+150
View File
@@ -0,0 +1,150 @@
// 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
@@ -0,0 +1,71 @@
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)
}
}
+16 -15
View File
@@ -8,6 +8,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"image" "image"
"image/jpeg" "image/jpeg"
"image/png" "image/png"
@@ -53,7 +54,7 @@ type SendService interface {
} }
type sendService struct { type sendService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
config *config.Config config *config.Config
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
@@ -380,7 +381,7 @@ type MessageSendStruct struct {
} }
func (s *sendService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (s *sendService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := s.clientPointer[instanceId] client := s.clientPointer.Get(instanceId)
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -394,7 +395,7 @@ func (s *sendService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = s.clientPointer[instanceId] client = s.clientPointer.Get(instanceId)
s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -2360,7 +2361,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
var message string var message string
if data.Id == "" { if data.Id == "" {
message = s.clientPointer[instance.Id].GenerateMessageID() message = s.clientPointer.Get(instance.Id).GenerateMessageID()
} else { } else {
message = data.Id message = data.Id
} }
@@ -2371,14 +2372,14 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
media = "audio" media = "audio"
} }
err := s.clientPointer[instance.Id].SendChatPresence(context.Background(), recipient, types.ChatPresence("composing"), types.ChatPresenceMedia(media)) err := s.clientPointer.Get(instance.Id).SendChatPresence(context.Background(), recipient, types.ChatPresence("composing"), types.ChatPresenceMedia(media))
if err != nil { if err != nil {
return nil, err return nil, err
} }
time.Sleep(time.Duration(data.Delay) * time.Millisecond) time.Sleep(time.Duration(data.Delay) * time.Millisecond)
err = s.clientPointer[instance.Id].SendChatPresence(context.Background(), recipient, types.ChatPresence("paused"), types.ChatPresenceMedia(media)) err = s.clientPointer.Get(instance.Id).SendChatPresence(context.Background(), recipient, types.ChatPresence("paused"), types.ChatPresenceMedia(media))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -2631,7 +2632,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
// Only try to get participants for actual groups, not newsletters // Only try to get participants for actual groups, not newsletters
if isGroup && !isNewsletter { if isGroup && !isNewsletter {
if data.MentionAll { if data.MentionAll {
groupInfo, err := s.clientPointer[instance.Id].GetGroupInfo(context.Background(), recipient) groupInfo, err := s.clientPointer.Get(instance.Id).GetGroupInfo(context.Background(), recipient)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -2770,7 +2771,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
sendExtra.AdditionalNodes = data.AdditionalNodes sendExtra.AdditionalNodes = data.AdditionalNodes
} }
response, err := s.clientPointer[instance.Id].SendMessage(context.Background(), recipient, msg, sendExtra) response, err := s.clientPointer.Get(instance.Id).SendMessage(context.Background(), recipient, msg, sendExtra)
if err != nil { if err != nil {
s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error sending message: %v", instance.Id, err) s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error sending message: %v", instance.Id, err)
return nil, err return nil, err
@@ -2781,7 +2782,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
messageInfo := types.MessageInfo{ messageInfo := types.MessageInfo{
MessageSource: types.MessageSource{ MessageSource: types.MessageSource{
Chat: recipient, Chat: recipient,
Sender: *s.clientPointer[instance.Id].Store.ID, Sender: *s.clientPointer.Get(instance.Id).Store.ID,
IsFromMe: true, IsFromMe: true,
IsGroup: isGroup, IsGroup: isGroup,
}, },
@@ -2835,15 +2836,15 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
sticker := msg.GetStickerMessage() sticker := msg.GetStickerMessage()
if img != nil { if img != nil {
data, err = s.clientPointer[instance.Id].Download(context.Background(), img) data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), img)
} else if audio != nil { } else if audio != nil {
data, err = s.clientPointer[instance.Id].Download(context.Background(), audio) data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), audio)
} else if document != nil { } else if document != nil {
data, err = s.clientPointer[instance.Id].Download(context.Background(), document) data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), document)
} else if video != nil { } else if video != nil {
data, err = s.clientPointer[instance.Id].Download(context.Background(), video) data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), video)
} else if sticker != nil { } else if sticker != nil {
data, err = s.clientPointer[instance.Id].Download(context.Background(), sticker) data, err = s.clientPointer.Get(instance.Id).Download(context.Background(), sticker)
webpReader := bytes.NewReader(data) webpReader := bytes.NewReader(data)
img, err := webp.Decode(webpReader) img, err := webp.Decode(webpReader)
@@ -3366,7 +3367,7 @@ func (s *sendService) sendStatusWebhook(messageSent *MessageSendStruct, instance
} }
func NewSendService( func NewSendService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
config *config.Config, config *config.Config,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
+5 -4
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"io" "io"
"net/http" "net/http"
"time" "time"
@@ -33,7 +34,7 @@ type UserService interface {
} }
type userService struct { type userService struct {
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
whatsmeowService whatsmeow_service.WhatsmeowService whatsmeowService whatsmeow_service.WhatsmeowService
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
} }
@@ -109,7 +110,7 @@ type PrivacyStruct struct {
} }
func (u *userService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) { func (u *userService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := u.clientPointer[instanceId] client := u.clientPointer.Get(instanceId)
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil) u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
if client == nil { if client == nil {
@@ -123,7 +124,7 @@ func (u *userService) ensureClientConnected(instanceId string) (*whatsmeow.Clien
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId) u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
client = u.clientPointer[instanceId] client = u.clientPointer.Get(instanceId)
u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v", u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
instanceId, instanceId,
client != nil, client != nil,
@@ -543,7 +544,7 @@ func (u *userService) SetProfileStatus(data *SetProfileStatusStruct, instance *i
} }
func NewUserService( func NewUserService(
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
whatsmeowService whatsmeow_service.WhatsmeowService, whatsmeowService whatsmeow_service.WhatsmeowService,
loggerWrapper *logger_wrapper.LoggerManager, loggerWrapper *logger_wrapper.LoggerManager,
) UserService { ) UserService {
+7
View File
@@ -207,6 +207,13 @@ func ParseJID(arg string) (whatsmeow_types.JID, bool) {
return recipient, false 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") { if recipient.User == "" && !strings.Contains(jidString, "@broadcast") {
logger.LogError("Invalid JID. No user specified: %s", jidString) logger.LogError("Invalid JID. No user specified: %s", jidString)
return recipient, false return recipient, false
+2 -2
View File
@@ -284,13 +284,13 @@ func TestParseJID(t *testing.T) {
name: "Valid phone number", name: "Valid phone number",
input: "15551234567", input: "15551234567",
expectOk: true, expectOk: true,
expectJID: "+[email protected]", expectJID: "[email protected]",
}, },
{ {
name: "Valid BR number", name: "Valid BR number",
input: "5531987654321", input: "5531987654321",
expectOk: true, expectOk: true,
expectJID: "+[email protected]", expectJID: "[email protected]",
}, },
{ {
name: "Valid group ID", name: "Valid group ID",
+278 -63
View File
@@ -7,6 +7,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/evolution-foundation/evolution-go/pkg/safemap"
"image/png" "image/png"
"io" "io"
"math/rand" "math/rand"
@@ -28,6 +29,7 @@ import (
"go.mau.fi/whatsmeow/appstate" "go.mau.fi/whatsmeow/appstate"
"go.mau.fi/whatsmeow/proto/waCompanionReg" "go.mau.fi/whatsmeow/proto/waCompanionReg"
"go.mau.fi/whatsmeow/proto/waE2E" "go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/proto/waWa6"
"go.mau.fi/whatsmeow/store" "go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/store/sqlstore" "go.mau.fi/whatsmeow/store/sqlstore"
"go.mau.fi/whatsmeow/types" "go.mau.fi/whatsmeow/types"
@@ -83,10 +85,10 @@ type whatsmeowService struct {
labelRepository label_repository.LabelRepository labelRepository label_repository.LabelRepository
pollService poll_service.PollService // NOVO: Serviço de enquetes pollService poll_service.PollService // NOVO: Serviço de enquetes
config *config.Config config *config.Config
killChannel map[string](chan bool) killChannel *safemap.Map[chan bool]
userInfoCache *cache.Cache userInfoCache *cache.Cache
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
myClientPointer map[string]*MyClient myClientPointer *safemap.Map[*MyClient]
rabbitmqProducer producer_interfaces.Producer rabbitmqProducer producer_interfaces.Producer
webhookProducer producer_interfaces.Producer webhookProducer producer_interfaces.Producer
websocketProducer producer_interfaces.Producer websocketProducer producer_interfaces.Producer
@@ -97,8 +99,18 @@ type whatsmeowService struct {
natsProducer producer_interfaces.Producer natsProducer producer_interfaces.Producer
loggerWrapper *logger_wrapper.LoggerManager loggerWrapper *logger_wrapper.LoggerManager
passkeyCeremony *ceremony.Store passkeyCeremony *ceremony.Store
// authStore is heap-allocated so sync.Once works with value-receiver methods like StartClient.
authStore *sharedSQLStore
} }
// sharedSQLStore holds the process-wide whatsmeow sqlstore.Container for PostgresAuthDB
// (or the sqlite fallback). One Upgrade per process; never Close on instance disconnect.
type sharedSQLStore struct {
once sync.Once
container *sqlstore.Container
err error
sqliteDB *sql.DB // kept alive when not using PostgresAuthDB
}
type MyClient struct { type MyClient struct {
service WhatsmeowService service WhatsmeowService
WAClient *whatsmeow.Client WAClient *whatsmeow.Client
@@ -115,9 +127,9 @@ type MyClient struct {
messageRepository message_repository.MessageRepository messageRepository message_repository.MessageRepository
labelRepository label_repository.LabelRepository labelRepository label_repository.LabelRepository
pollService poll_service.PollService // NOVO: Serviço de enquetes pollService poll_service.PollService // NOVO: Serviço de enquetes
clientPointer map[string]*whatsmeow.Client clientPointer *safemap.Map[*whatsmeow.Client]
myClientPointer map[string]*MyClient myClientPointer *safemap.Map[*MyClient]
killChannel map[string](chan bool) killChannel *safemap.Map[chan bool]
userInfoCache *cache.Cache userInfoCache *cache.Cache
config *config.Config config *config.Config
historySyncID int32 historySyncID int32
@@ -171,11 +183,22 @@ type ProxyConfig struct {
Username string `json:"username"` 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 { 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) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Starting reconnection process - simulating restart", instanceId)
// Passo 1: Limpar conexão existente se houver // Passo 1: Limpar conexão existente se houver
if client, exists := w.clientPointer[instanceId]; exists { if client, exists := w.clientPointer.Lookup(instanceId); exists && client != nil {
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Disconnecting existing client", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Disconnecting existing client", instanceId)
// Desconectar o cliente WebSocket // Desconectar o cliente WebSocket
@@ -185,7 +208,7 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
} }
// Remover event handler se existir // Remover event handler se existir
if mycli, ok := w.myClientPointer[instanceId]; ok { if mycli, ok := w.myClientPointer.Lookup(instanceId); ok {
if mycli.eventHandlerID != 0 { if mycli.eventHandlerID != 0 {
client.RemoveEventHandler(mycli.eventHandlerID) client.RemoveEventHandler(mycli.eventHandlerID)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Event handler removed", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Event handler removed", instanceId)
@@ -197,19 +220,16 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Cleaning up resources", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Cleaning up resources", instanceId)
// Enviar sinal de kill se o canal existir // Enviar sinal de kill se o canal existir
if killChan, exists := w.killChannel[instanceId]; exists { if killChan, exists := w.killChannel.Lookup(instanceId); exists {
select { if safemap.TrySendTimeout(killChan, true, 0) {
case killChan <- true:
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill signal sent", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill signal sent", instanceId)
default:
// Canal pode estar bloqueado, continua
} }
} }
// Remover das estruturas // Remover das estruturas
delete(w.clientPointer, instanceId) w.clientPointer.Delete(instanceId)
delete(w.myClientPointer, instanceId) w.myClientPointer.Delete(instanceId)
delete(w.killChannel, instanceId) w.killChannel.Delete(instanceId)
// Limpar cache de userInfo para esta instância // Limpar cache de userInfo para esta instância
if instance, err := w.instanceRepository.GetInstanceByID(instanceId); err == nil { if instance, err := w.instanceRepository.GetInstanceByID(instanceId); err == nil {
@@ -301,38 +321,181 @@ func (w whatsmeowService) ForceUpdateJid(instanceId string, number string) error
return nil 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")
}
w.authStore.once.Do(func() {
var dbLog waLog.Logger
if w.config.WaDebug != "" {
dbLog = waLog.Stdout("Database", w.config.WaDebug, true)
}
ctx := context.Background()
if w.config.PostgresAuthDB != "" {
if w.authDB == nil {
w.authStore.err = fmt.Errorf("postgres auth DB handle is nil")
return
}
container := sqlstore.NewWithDB(w.authDB, "postgres", dbLog)
if err := container.Upgrade(ctx); err != nil {
// Do not Close authDB — owned by main.
w.authStore.err = fmt.Errorf("failed to upgrade database: %w", err)
return
}
w.authStore.container = container
return
}
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 {
w.authStore.err = fmt.Errorf("failed to open sqlite auth store: %w", err)
return
}
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(5 * time.Minute)
db.SetConnMaxIdleTime(1 * time.Minute)
container := sqlstore.NewWithDB(db, "sqlite", dbLog)
if err := container.Upgrade(ctx); err != nil {
_ = db.Close()
w.authStore.err = fmt.Errorf("failed to upgrade database: %w", err)
return
}
w.authStore.sqliteDB = db
w.authStore.container = container
})
return w.authStore.container, w.authStore.err
}
// ============================================================================
// 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) { 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) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Starting websocket connection to Whatsapp for user '%s'", cd.Instance.Id)
var deviceStore *store.Device var deviceStore *store.Device
var err error var err error
if w.clientPointer[cd.Instance.Id] != nil { if w.clientPointer.Get(cd.Instance.Id) != nil {
if w.clientPointer[cd.Instance.Id].IsConnected() { if w.clientPointer.Get(cd.Instance.Id).IsConnected() {
return return
} }
} }
var container *sqlstore.Container container, err := w.getSharedSQLStoreContainer()
if w.config.WaDebug != "" {
dbLog := waLog.Stdout("Database", w.config.WaDebug, true)
if w.config.PostgresAuthDB != "" {
container, err = sqlstore.New(context.Background(), "postgres", w.config.PostgresAuthDB, 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)
container, err = sqlstore.New(context.Background(), "sqlite", dsn, dbLog)
}
} else {
if w.config.PostgresAuthDB != "" {
container, err = sqlstore.New(context.Background(), "postgres", w.config.PostgresAuthDB, nil)
} 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)
container, err = sqlstore.New(context.Background(), "sqlite", dsn, nil)
}
}
if err != nil { 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 create container: %v", cd.Instance.Id, err)
return return
@@ -398,7 +561,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
waVer := store.WAVersionContainer{uint32(version.Major), uint32(version.Minor), uint32(version.Patch)} waVer := store.WAVersionContainer{uint32(version.Major), uint32(version.Minor), uint32(version.Patch)}
store.SetWAVersion(waVer) store.SetWAVersion(waVer)
if store.BaseClientPayload != nil && store.BaseClientPayload.UserAgent != nil { if store.BaseClientPayload != nil && store.BaseClientPayload.UserAgent != nil {
store.BaseClientPayload.UserAgent.AppVersion = &waProto.ClientPayload_UserAgent_AppVersion{ store.BaseClientPayload.UserAgent.AppVersion = &waWa6.ClientPayload_UserAgent_AppVersion{
Primary: proto.Uint32(uint32(version.Major)), Primary: proto.Uint32(uint32(version.Major)),
Secondary: proto.Uint32(uint32(version.Minor)), Secondary: proto.Uint32(uint32(version.Minor)),
Tertiary: proto.Uint32(uint32(version.Patch)), Tertiary: proto.Uint32(uint32(version.Patch)),
@@ -416,7 +579,10 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
clientLog := waLog.Stdout("Client", minLevel, true) clientLog := waLog.Stdout("Client", minLevel, true)
client := whatsmeow.NewClient(deviceStore, clientLog) client := whatsmeow.NewClient(deviceStore, clientLog)
w.clientPointer[cd.Instance.Id] = client 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
if cd.IsProxy { if cd.IsProxy {
var proxyConfig ProxyConfig var proxyConfig ProxyConfig
@@ -504,7 +670,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
mycli.eventHandlerID = mycli.WAClient.AddEventHandler(mycli.myEventHandler) mycli.eventHandlerID = mycli.WAClient.AddEventHandler(mycli.myEventHandler)
// Armazena o MyClient no map para permitir atualizações posteriores // Armazena o MyClient no map para permitir atualizações posteriores
w.myClientPointer[cd.Instance.Id] = mycli w.myClientPointer.Set(cd.Instance.Id, mycli)
if client.Store.ID != nil { 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()) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Already logged in with JID: %s", cd.Instance.Id, client.Store.ID.String())
@@ -578,12 +744,12 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
for { for {
select { select {
case <-w.killChannel[cd.Instance.Id]: case <-w.killChannel.Get(cd.Instance.Id):
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Received kill signal for user '%s'", cd.Instance.Id) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Received kill signal for user '%s'", cd.Instance.Id)
client.Disconnect() client.Disconnect()
delete(w.clientPointer, cd.Instance.Id) w.clientPointer.Delete(cd.Instance.Id)
delete(w.myClientPointer, cd.Instance.Id) w.myClientPointer.Delete(cd.Instance.Id)
// Limpar cache de userInfo para esta instância // Limpar cache de userInfo para esta instância
w.userInfoCache.Delete(cd.Instance.Token) w.userInfoCache.Delete(cd.Instance.Token)
@@ -628,6 +794,14 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID) 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 // restart client
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Restarting client", cd.Instance.Id) w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Restarting client", cd.Instance.Id)
w.StartClient(cd) w.StartClient(cd)
@@ -658,7 +832,7 @@ func schedulePresenceUpdates(mycli *MyClient) {
randomInterval := time.Duration(1+rand.Intn(3)) * time.Hour randomInterval := time.Duration(1+rand.Intn(3)) * time.Hour
ticker = time.NewTicker(randomInterval) ticker = time.NewTicker(randomInterval)
case <-mycli.killChannel[mycli.userID]: case <-mycli.killChannel.Get(mycli.userID):
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Received kill signal, stopping presence updates", 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 return // Encerra a goroutine quando receber sinal de kill
} }
@@ -852,8 +1026,10 @@ func (mycli *MyClient) teardownQR(reason string, forceLogout bool) {
// maps (it is the single writer for this instance). Blocking send mirrors // maps (it is the single writer for this instance). Blocking send mirrors
// the original timeout branch so the signal is never dropped. // the original timeout branch so the signal is never dropped.
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] QR timeout — signaling kill channel", instanceID) mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] QR timeout — signaling kill channel", instanceID)
if killChan, exists := mycli.killChannel[instanceID]; exists { if killChan, exists := mycli.killChannel.Lookup(instanceID); exists {
killChan <- true if !safemap.TrySend(killChan, true) {
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] Kill channel already closed (instance deleted)", instanceID)
}
} }
} }
@@ -879,6 +1055,9 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
} }
} }
case *events.Connected, *events.PushNameSetting: 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) 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 { if len(mycli.WAClient.Store.PushName) > 0 {
doWebhook = true doWebhook = true
@@ -911,7 +1090,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
// jid, ok := utils.ParseJID(mycli.WAClient.Store.ID.ToNonAD().User) // jid, ok := utils.ParseJID(mycli.WAClient.Store.ID.ToNonAD().User)
// if ok { // if ok {
// profilePicUrl, err := mycli.clientPointer[mycli.userID].GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{ // profilePicUrl, err := mycli.clientPointer.Get(mycli.userID).GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{
// Preview: false, // Preview: false,
// }) // })
// if err != nil { // if err != nil {
@@ -1281,7 +1460,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
fmt.Printf("[POLL DEBUG] ✅ mycli.WAClient is initialized: %s\n", mycli.WAClient.Store.ID) fmt.Printf("[POLL DEBUG] ✅ mycli.WAClient is initialized: %s\n", mycli.WAClient.Store.ID)
} }
decrypted, err := mycli.clientPointer[mycli.userID].DecryptPollVote(context.Background(), evt) decrypted, err := mycli.clientPointer.Get(mycli.userID).DecryptPollVote(context.Background(), evt)
if err != nil { if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decrypt vote: %v", mycli.userID, err) mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decrypt vote: %v", mycli.userID, err)
} else { } else {
@@ -1821,6 +2000,27 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
doWebhook = true doWebhook = true
postMap["event"] = "Archive" 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 := postMap["data"].(map[string]interface{})
dataMap["JID"] = evt.JID dataMap["JID"] = evt.JID
dataMap["Timestamp"] = evt.Timestamp dataMap["Timestamp"] = evt.Timestamp
@@ -1901,7 +2101,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
} }
// Agora mata o canal DEPOIS de enviar o evento // Agora mata o canal DEPOIS de enviar o evento
mycli.killChannel[mycli.userID] <- true safemap.TrySend(mycli.killChannel.Get(mycli.userID), true)
case *events.ChatPresence: case *events.ChatPresence:
doWebhook = true doWebhook = true
postMap["event"] = "ChatPresence" postMap["event"] = "ChatPresence"
@@ -1988,6 +2188,20 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
// Trigger instance restart via websocket-capable service (non-blocking) // Trigger instance restart via websocket-capable service (non-blocking)
go func(instanceID string) { go func(instanceID string) {
mycli.loggerWrapper.GetLogger(instanceID).LogInfo("[%s] Disconnected detected, restarting instance", instanceID) 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 { if err := mycli.service.ReconnectClient(instanceID); err != nil {
mycli.loggerWrapper.GetLogger(instanceID).LogError("[%s] Failed to restart instance: %v", instanceID, err) mycli.loggerWrapper.GetLogger(instanceID).LogError("[%s] Failed to restart instance: %v", instanceID, err)
} }
@@ -2386,7 +2600,7 @@ func (w whatsmeowService) StartInstance(instanceId string) error {
} }
} }
w.killChannel[instance.Id] = make(chan bool) w.killChannel.Set(instance.Id, make(chan bool))
clientData := &ClientData{ clientData := &ClientData{
Instance: instance, Instance: instance,
@@ -2694,7 +2908,7 @@ func (w whatsmeowService) UpdateInstanceSettings(instanceId string) error {
} }
// Verifica se o MyClient existe // Verifica se o MyClient existe
myClient, exists := w.myClientPointer[instanceId] myClient, exists := w.myClientPointer.Lookup(instanceId)
if !exists { if !exists {
w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId) 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) return fmt.Errorf("instance %s not found in runtime", instanceId)
@@ -2753,7 +2967,7 @@ func (w whatsmeowService) UpdateInstanceAdvancedSettings(instanceId string) erro
} }
// Verifica se o MyClient existe // Verifica se o MyClient existe
myClient, exists := w.myClientPointer[instanceId] myClient, exists := w.myClientPointer.Lookup(instanceId)
if !exists { if !exists {
w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId) 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) return fmt.Errorf("instance %s not found in runtime", instanceId)
@@ -2773,19 +2987,19 @@ func (w whatsmeowService) ClearInstanceCache(instanceId string, token string) er
w.userInfoCache.Delete(token) w.userInfoCache.Delete(token)
// Limpar myClientPointer se existir // Limpar myClientPointer se existir
if _, exists := w.myClientPointer[instanceId]; exists { if _, exists := w.myClientPointer.Lookup(instanceId); exists {
delete(w.myClientPointer, instanceId) w.myClientPointer.Delete(instanceId)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] MyClient pointer cleared", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] MyClient pointer cleared", instanceId)
} }
// Limpar clientPointer se existir // Limpar clientPointer se existir
if _, exists := w.clientPointer[instanceId]; exists { if _, exists := w.clientPointer.Lookup(instanceId); exists {
delete(w.clientPointer, instanceId) w.clientPointer.Delete(instanceId)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client pointer cleared", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client pointer cleared", instanceId)
} }
// Limpar killChannel se existir // Limpar killChannel se existir
if killChan, exists := w.killChannel[instanceId]; exists { if killChan, exists := w.killChannel.Lookup(instanceId); exists {
select { select {
case killChan <- true: case killChan <- true:
// Canal recebeu o sinal // Canal recebeu o sinal
@@ -2793,7 +3007,7 @@ func (w whatsmeowService) ClearInstanceCache(instanceId string, token string) er
// Canal pode estar bloqueado, apenas fecha // Canal pode estar bloqueado, apenas fecha
} }
close(killChan) close(killChan)
delete(w.killChannel, instanceId) w.killChannel.Delete(instanceId)
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill channel cleared", instanceId) w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill channel cleared", instanceId)
} }
@@ -2807,8 +3021,8 @@ func NewWhatsmeowService(
messageRepository message_repository.MessageRepository, messageRepository message_repository.MessageRepository,
labelRepository label_repository.LabelRepository, labelRepository label_repository.LabelRepository,
config *config.Config, config *config.Config,
killChannel map[string](chan bool), killChannel *safemap.Map[chan bool],
clientPointer map[string]*whatsmeow.Client, clientPointer *safemap.Map[*whatsmeow.Client],
rabbitmqProducer producer_interfaces.Producer, rabbitmqProducer producer_interfaces.Producer,
webhookProducer producer_interfaces.Producer, webhookProducer producer_interfaces.Producer,
websocketProducer producer_interfaces.Producer, websocketProducer producer_interfaces.Producer,
@@ -2831,7 +3045,7 @@ func NewWhatsmeowService(
killChannel: killChannel, killChannel: killChannel,
userInfoCache: cache.New(5*time.Minute, 10*time.Minute), userInfoCache: cache.New(5*time.Minute, 10*time.Minute),
clientPointer: clientPointer, clientPointer: clientPointer,
myClientPointer: make(map[string]*MyClient), myClientPointer: safemap.New[*MyClient](),
rabbitmqProducer: rabbitmqProducer, rabbitmqProducer: rabbitmqProducer,
webhookProducer: webhookProducer, webhookProducer: webhookProducer,
websocketProducer: websocketProducer, websocketProducer: websocketProducer,
@@ -2842,6 +3056,7 @@ func NewWhatsmeowService(
natsProducer: natsProducer, natsProducer: natsProducer,
loggerWrapper: loggerWrapper, loggerWrapper: loggerWrapper,
passkeyCeremony: ceremony.NewStore(), passkeyCeremony: ceremony.NewStore(),
authStore: &sharedSQLStore{},
} }
} }
@@ -2859,7 +3074,7 @@ func (w *whatsmeowService) PasskeyCeremonyStore() *ceremony.Store {
// SubmitPasskeyResponse forwards the browser's WebAuthn assertion to WhatsApp // SubmitPasskeyResponse forwards the browser's WebAuthn assertion to WhatsApp
// for the given instance. Called by POST /passkey-ceremony/{token}/response. // for the given instance. Called by POST /passkey-ceremony/{token}/response.
func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.WebAuthnResponse) error { func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.WebAuthnResponse) error {
client, ok := w.clientPointer[instanceId] client, ok := w.clientPointer.Lookup(instanceId)
if !ok || client == nil { if !ok || client == nil {
return fmt.Errorf("no active client for instance %s", instanceId) return fmt.Errorf("no active client for instance %s", instanceId)
} }
@@ -2878,7 +3093,7 @@ func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.
// ConfirmPasskey finishes the pairing after the user verified the code. // ConfirmPasskey finishes the pairing after the user verified the code.
// Called by POST /passkey-ceremony/{token}/confirm. // Called by POST /passkey-ceremony/{token}/confirm.
func (w *whatsmeowService) ConfirmPasskey(instanceId string) error { func (w *whatsmeowService) ConfirmPasskey(instanceId string) error {
client, ok := w.clientPointer[instanceId] client, ok := w.clientPointer.Lookup(instanceId)
if !ok || client == nil { if !ok || client == nil {
return fmt.Errorf("no active client for instance %s", instanceId) return fmt.Errorf("no active client for instance %s", instanceId)
} }
+208
View File
@@ -0,0 +1,208 @@
#!/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"