Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0379082181 | ||
|
|
e02441fc4e | ||
|
|
abaac8eb93 | ||
|
|
4998ab3d45 | ||
|
|
74389cc8de | ||
|
|
c33b4d98fd | ||
|
|
fc35d72029 | ||
|
|
3fce4dbcca | ||
|
|
0c4ac7d9a9 | ||
|
|
a5f7e1c98a | ||
|
|
a0c74485b8 | ||
|
|
a4add7cc5e | ||
|
|
3cc5192b7b | ||
|
|
87a354aee8 |
No files matched your search
@@ -1,11 +1,19 @@
|
||||
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:
|
||||
push:
|
||||
branches:
|
||||
- maintained-stable
|
||||
tags:
|
||||
- 'v*.*.*'
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
publish_image:
|
||||
@@ -14,14 +22,23 @@ on:
|
||||
default: false
|
||||
required: true
|
||||
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
|
||||
default: ''
|
||||
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:
|
||||
build_docker:
|
||||
name: Build e Verificacao Docker
|
||||
name: Build, Scan e Publicacao
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
@@ -31,44 +48,72 @@ jobs:
|
||||
- name: Obter Versao e Commit SHA
|
||||
id: meta
|
||||
run: |
|
||||
VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
|
||||
COMMIT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "commit_sha=${COMMIT_SHA}" >> $GITHUB_OUTPUT
|
||||
echo "image_tag=${VERSION}-${COMMIT_SHA}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Configurar Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
if [ "${{ github.ref_type }}" = "tag" ]; then
|
||||
VERSION="${{ github.ref_name }}"
|
||||
VERSION="${VERSION#v}"
|
||||
PUBLISH=true
|
||||
else
|
||||
VERSION="${{ github.event.inputs.target_tag }}"
|
||||
[ -n "$VERSION" ] || VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
|
||||
PUBLISH="${{ github.event.inputs.publish_image == 'true' }}"
|
||||
fi
|
||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
echo "commit_sha=${COMMIT_SHA}" >> "$GITHUB_OUTPUT"
|
||||
echo "image_tag=${VERSION}-${COMMIT_SHA}" >> "$GITHUB_OUTPUT"
|
||||
echo "publish=${PUBLISH}" >> "$GITHUB_OUTPUT"
|
||||
echo "Versao: ${VERSION} | Commit: ${COMMIT_SHA} | Publicar: ${PUBLISH}"
|
||||
|
||||
- name: Construir Imagem Docker Local
|
||||
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: |
|
||||
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)
|
||||
if: ${{ github.event.inputs.publish_image == 'true' || github.event.inputs.publish_image == true }}
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.jf.eng.br
|
||||
username: ${{ secrets.REGISTRY_USER || github.actor }}
|
||||
password: ${{ secrets.REGISTRY_TOKEN || secrets.GITEA_TOKEN }}
|
||||
- name: Testar Inicializacao do Container
|
||||
run: |
|
||||
# O binario precisa subir e falhar apenas por falta de banco/config,
|
||||
# nunca por erro de link (CGO/libwebp/libjpeg) ou arquivo ausente.
|
||||
set +e
|
||||
timeout 20 docker run --rm evogo:ci-${{ steps.meta.outputs.commit_sha }} > /tmp/run.log 2>&1
|
||||
set -e
|
||||
tail -20 /tmp/run.log
|
||||
if grep -qiE "error while loading shared libraries|exec format error|exec /app/server" /tmp/run.log; then
|
||||
echo "Falha ao iniciar o binario dentro da imagem"; exit 1
|
||||
fi
|
||||
docker run --rm --entrypoint sh evogo:ci-${{ steps.meta.outputs.commit_sha }} -c 'test -x /app/server && test -d /app/manager/dist && cat /app/VERSION'
|
||||
|
||||
- name: Publicar Imagens no Registry (apenas com aprovacao expressa)
|
||||
if: ${{ github.event.inputs.publish_image == 'true' || github.event.inputs.publish_image == true }}
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: |
|
||||
git.jf.eng.br/jfeng/evogo:${{ steps.meta.outputs.image_tag }}
|
||||
git.jf.eng.br/jfeng/evogo:${{ steps.meta.outputs.version }}
|
||||
build-args: |
|
||||
VERSION=${{ steps.meta.outputs.image_tag }}
|
||||
- name: Verificar Vulnerabilidades (Trivy, nao bloqueante)
|
||||
continue-on-error: true
|
||||
run: |
|
||||
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest \
|
||||
image --severity HIGH,CRITICAL --ignore-unfixed --no-progress \
|
||||
evogo:ci-${{ steps.meta.outputs.commit_sha }}
|
||||
|
||||
- name: Login no Gitea Package Registry
|
||||
if: steps.meta.outputs.publish == 'true'
|
||||
run: |
|
||||
USER="${{ secrets.REGISTRY_USER }}"
|
||||
[ -n "$USER" ] || USER="${{ github.actor }}"
|
||||
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
|
||||
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
|
||||
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
|
||||
@@ -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:
|
||||
schedule:
|
||||
# Executa diariamente as 04:00 UTC (01:00 BRT)
|
||||
# Diariamente as 04:00 UTC (01:00 BRT)
|
||||
- cron: '0 4 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: upstream-sync
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
check_upstream:
|
||||
name: Verificar Atualizacoes do Upstream e Whatsmeow
|
||||
sync:
|
||||
name: Incorporar upstream e verificar whatsmeow
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout do Repositorio
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: maintained-develop
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.GITEA_TOKEN }}
|
||||
|
||||
- name: Executar Script de Verificacao
|
||||
id: check
|
||||
run: |
|
||||
bash scripts/check-upstream-updates.sh
|
||||
|
||||
- name: Salvar Relatorio como Artefato
|
||||
uses: actions/upload-artifact@v4
|
||||
- name: Configurar Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
name: relatorio-upstream-${{ github.run_id }}
|
||||
path: relatorio_atualizacao_*.md
|
||||
go-version-file: go.mod
|
||||
|
||||
- name: Instalar Dependencias de Sistema
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq --no-install-recommends libjpeg-dev libwebp-dev
|
||||
|
||||
- name: Sincronizar com o upstream
|
||||
env:
|
||||
GITEA_URL: ${{ github.server_url }}
|
||||
REPO: ${{ github.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
# Defina a variavel de repositorio AUTO_MERGE_UPSTREAM=true para mesclar
|
||||
# automaticamente em maintained-develop quando build e testes passarem.
|
||||
AUTO_MERGE: ${{ vars.AUTO_MERGE_UPSTREAM || 'false' }}
|
||||
run: |
|
||||
git config user.name "EvoGO Upstream Bot"
|
||||
git config user.email "[email protected]"
|
||||
bash scripts/upstream-sync.sh
|
||||
@@ -18,6 +18,36 @@
|
||||
- **Migração automática do banco de autenticação** — o schema do whatsmeow sobe
|
||||
de v14 para v16 (`companion_meta_nonce`, `wasa_root_secret_id`). Roda sozinho
|
||||
ao abrir o container; testado com banco SQLite v14 existente.
|
||||
- **Build quebrado após o fix 405** — `whatsmeow.go` referenciava `waProto`
|
||||
(pacote inexistente); `ClientPayload_UserAgent_AppVersion` vem de
|
||||
`go.mau.fi/whatsmeow/proto/waWa6`.
|
||||
|
||||
### 🛡️ 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
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"database/sql"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"log"
|
||||
"net/http"
|
||||
"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 {
|
||||
killChannel := make(map[string](chan bool))
|
||||
clientPointer := make(map[string]*whatsmeow.Client)
|
||||
killChannel := safemap.New[chan bool]()
|
||||
clientPointer := safemap.New[*whatsmeow.Client]()
|
||||
|
||||
loggerWrapper := logger_wrapper.NewLoggerManager(config)
|
||||
|
||||
|
||||
@@ -82,11 +82,32 @@ docker build \
|
||||
|
||||
O pipeline é orquestrado via `.gitea/workflows/docker-build.yml`:
|
||||
|
||||
1. **Trigger em Pull Requests ou Push em develop:**
|
||||
- Executa `go vet` e `go test`.
|
||||
- Executa `docker build` para garantir que a imagem compila sem erros.
|
||||
- **Não faz push** para o registry.
|
||||
2. **Trigger em Tag ou Push em `maintained-stable`:**
|
||||
- Constrói a imagem multiplataforma (`linux/amd64`, `linux/arm64`).
|
||||
- Gera tag imutável associada ao commit.
|
||||
- Requer aprovação ou execução via `workflow_dispatch` para publicação em produção.
|
||||
1. **Push em `maintained-stable`:** build da imagem (`linux/amd64`), teste de
|
||||
inicialização do binário e scan Trivy (HIGH/CRITICAL, não bloqueante).
|
||||
**Não publica.**
|
||||
2. **Push de tag `v<versão>` (release aprovado):** mesmo build/teste/scan e
|
||||
publicação de:
|
||||
- `git.jf.eng.br/jfeng/evogo:<versão>-<sha7>` (imutável)
|
||||
- `git.jf.eng.br/jfeng/evogo:<versão>`
|
||||
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>`.
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
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:
|
||||
|
||||
@@ -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:**
|
||||
- Origem: `maintenance/sync-upstream-<nova-versao>`
|
||||
|
||||
@@ -3,6 +3,7 @@ package call_service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
@@ -18,7 +19,7 @@ type CallService interface {
|
||||
}
|
||||
|
||||
type callService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
@@ -29,7 +30,7 @@ type RejectCallStruct struct {
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
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",
|
||||
instanceId,
|
||||
client != nil,
|
||||
@@ -83,7 +84,7 @@ func (c *callService) RejectCall(data *RejectCallStruct, instance *instance_mode
|
||||
}
|
||||
|
||||
func NewCallService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) CallService {
|
||||
|
||||
@@ -3,6 +3,7 @@ package chat_service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
@@ -25,7 +26,7 @@ type ChatService interface {
|
||||
}
|
||||
|
||||
type chatService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
@@ -40,7 +41,7 @@ type HistorySyncRequestStruct struct {
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
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",
|
||||
instanceId,
|
||||
client != nil,
|
||||
@@ -244,7 +245,7 @@ func (c *chatService) HistorySyncRequest(data *HistorySyncRequestStruct, instanc
|
||||
}
|
||||
|
||||
func NewChatService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) ChatService {
|
||||
|
||||
@@ -3,6 +3,7 @@ package community_service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
@@ -21,7 +22,7 @@ type CommunityService interface {
|
||||
}
|
||||
|
||||
type communityService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
@@ -36,7 +37,7 @@ type AddParticipantStruct struct {
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
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",
|
||||
instanceId,
|
||||
client != nil,
|
||||
@@ -157,7 +158,7 @@ func (c *communityService) CommunityRemove(data *AddParticipantStruct, instance
|
||||
}
|
||||
|
||||
func NewCommunityService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) CommunityService {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
|
||||
"github.com/gomessguii/logger"
|
||||
"github.com/nats-io/nats.go"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type natsProducer struct {
|
||||
@@ -20,6 +21,15 @@ func NewNatsProducer(
|
||||
natsGlobalEvents []string,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) producer_interfaces.Producer {
|
||||
if strings.TrimSpace(url) == "" {
|
||||
return &natsProducer{
|
||||
conn: nil,
|
||||
natsGlobalEnabled: false,
|
||||
natsGlobalEvents: nil,
|
||||
loggerWrapper: loggerWrapper,
|
||||
}
|
||||
}
|
||||
|
||||
conn, err := nats.Connect(url)
|
||||
if err != nil {
|
||||
logger.LogError("Failed to connect to NATS: %v", err)
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -14,92 +14,131 @@ var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
logger.LogInfo("Verificando origem da conexão WebSocket")
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
||||
// client wraps a connection together with its own write mutex.
|
||||
//
|
||||
// gorilla/websocket permits only one concurrent writer per connection, and
|
||||
// events are dispatched from independent goroutines (see the `go CallWebhook`
|
||||
// calls in the whatsmeow event handler), so two events arriving at once used to
|
||||
// race on the same socket. Serialising per connection removes that.
|
||||
type client struct {
|
||||
conn *websocket.Conn
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (c *client) writeJSON(v interface{}) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.conn.WriteJSON(v)
|
||||
}
|
||||
|
||||
type websocketProducer struct {
|
||||
clients map[string]*websocket.Conn // conexões específicas por instância
|
||||
broadcast []*websocket.Conn // conexões que recebem todos os eventos
|
||||
// clients holds every connection subscribed to a given instance. This is a
|
||||
// slice, not a single connection: previously a second subscriber replaced the
|
||||
// first, so opening the UI in two tabs silently cut delivery to the older one,
|
||||
// and either tab disconnecting removed the whole instance entry.
|
||||
clients map[string][]*client
|
||||
broadcast []*client
|
||||
clientsMux sync.RWMutex
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
|
||||
func NewWebsocketProducer(loggerWrapper *logger_wrapper.LoggerManager) *websocketProducer {
|
||||
return &websocketProducer{
|
||||
clients: make(map[string]*websocket.Conn),
|
||||
broadcast: make([]*websocket.Conn, 0),
|
||||
clientsMux: sync.RWMutex{},
|
||||
clients: make(map[string][]*client),
|
||||
broadcast: make([]*client, 0),
|
||||
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) {
|
||||
logger.LogInfo("Iniciando upgrade da conexão WebSocket")
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
logger.LogError("Erro ao fazer upgrade da conexão websocket: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
logger.LogInfo("Conexão WebSocket estabelecida com sucesso")
|
||||
|
||||
c := &client{conn: conn}
|
||||
if instanceId == "" {
|
||||
producer.AddBroadcastClient(conn)
|
||||
producer.addBroadcastClient(c)
|
||||
} 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() {
|
||||
for {
|
||||
_, _, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
defer func() {
|
||||
if instanceId == "" {
|
||||
producer.RemoveBroadcastClient(conn)
|
||||
producer.removeBroadcastClient(c)
|
||||
} else {
|
||||
producer.RemoveClient(instanceId)
|
||||
producer.removeClient(instanceId, c)
|
||||
}
|
||||
conn.Close()
|
||||
break
|
||||
_ = conn.Close()
|
||||
}()
|
||||
for {
|
||||
if _, _, err := conn.ReadMessage(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (p *websocketProducer) AddBroadcastClient(conn *websocket.Conn) {
|
||||
func (p *websocketProducer) addBroadcastClient(c *client) {
|
||||
p.clientsMux.Lock()
|
||||
defer p.clientsMux.Unlock()
|
||||
p.broadcast = append(p.broadcast, conn)
|
||||
logger.LogInfo("Cliente broadcast websocket adicionado")
|
||||
p.broadcast = append(p.broadcast, c)
|
||||
n := len(p.broadcast)
|
||||
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()
|
||||
defer p.clientsMux.Unlock()
|
||||
for i, c := range p.broadcast {
|
||||
if c == conn {
|
||||
p.broadcast = append(p.broadcast[:i], p.broadcast[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
logger.LogInfo("Cliente broadcast websocket removido")
|
||||
p.broadcast = drop(p.broadcast, c)
|
||||
n := len(p.broadcast)
|
||||
p.clientsMux.Unlock()
|
||||
logger.LogInfo("Cliente broadcast websocket removido (total: %d)", n)
|
||||
}
|
||||
|
||||
func (p *websocketProducer) AddClient(instanceID string, conn *websocket.Conn) {
|
||||
func (p *websocketProducer) addClient(instanceID string, c *client) {
|
||||
p.clientsMux.Lock()
|
||||
defer p.clientsMux.Unlock()
|
||||
p.clients[instanceID] = conn
|
||||
p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket adicionado para instância: %s", instanceID)
|
||||
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) {
|
||||
func (p *websocketProducer) removeClient(instanceID string, c *client) {
|
||||
p.clientsMux.Lock()
|
||||
defer p.clientsMux.Unlock()
|
||||
remaining := drop(p.clients[instanceID], c)
|
||||
if len(remaining) == 0 {
|
||||
delete(p.clients, instanceID)
|
||||
p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket removido para instância: %s", instanceID)
|
||||
} else {
|
||||
p.clients[instanceID] = remaining
|
||||
}
|
||||
p.clientsMux.Unlock()
|
||||
p.loggerWrapper.GetLogger(instanceID).LogInfo(
|
||||
"Cliente websocket removido para instância: %s (restantes: %d)", instanceID, len(remaining))
|
||||
}
|
||||
|
||||
// drop returns a new slice without target. It allocates rather than filtering in
|
||||
// place, so a snapshot taken by a concurrent Produce can never observe a mutated
|
||||
// backing array.
|
||||
func drop(list []*client, target *client) []*client {
|
||||
out := make([]*client, 0, len(list))
|
||||
for _, c := range list {
|
||||
if c != target {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
|
||||
// Snapshot under the lock, then write outside it: a slow or half-open socket
|
||||
// must not block other instances' deliveries.
|
||||
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
|
||||
if client, exists := p.clients[instanceID]; exists {
|
||||
err := client.WriteJSON(message)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem websocket para %s: %v", instanceID, err)
|
||||
// Não remove o cliente aqui pois estamos com o RLock
|
||||
return err
|
||||
}
|
||||
p.loggerWrapper.GetLogger(instanceID).LogInfo("Mensagem websocket enviada com sucesso para instância %s na fila %s", instanceID, queueName)
|
||||
}
|
||||
|
||||
// Envia para todos os clientes broadcast
|
||||
for _, conn := range p.broadcast {
|
||||
err := conn.WriteJSON(message)
|
||||
if err != nil {
|
||||
p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem broadcast websocket: %v", err)
|
||||
continue
|
||||
var failed []*client
|
||||
for _, c := range targets {
|
||||
if err := c.writeJSON(message); err != nil {
|
||||
p.loggerWrapper.GetLogger(instanceID).LogError(
|
||||
"Erro ao enviar mensagem websocket para %s: %v", instanceID, err)
|
||||
failed = append(failed, c)
|
||||
}
|
||||
}
|
||||
|
||||
if len(failed) > 0 {
|
||||
p.clientsMux.Lock()
|
||||
for _, c := range failed {
|
||||
if remaining := drop(p.clients[instanceID], c); len(remaining) == 0 {
|
||||
delete(p.clients, instanceID)
|
||||
} else {
|
||||
p.clients[instanceID] = remaining
|
||||
}
|
||||
p.broadcast = drop(p.broadcast, c)
|
||||
}
|
||||
p.clientsMux.Unlock()
|
||||
}
|
||||
|
||||
if n := len(targets) - len(failed); n > 0 {
|
||||
p.loggerWrapper.GetLogger(instanceID).LogInfo(
|
||||
"Mensagem websocket enviada para %d cliente(s) da instância %s na fila %s", n, instanceID, queueName)
|
||||
}
|
||||
|
||||
// Deliberately nil even when a write failed. sendToQueueOrWebhook aborts the
|
||||
// remaining producers on error, so reporting a dead browser tab here would
|
||||
// silently suppress RabbitMQ/NATS/webhook delivery for the same event.
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -37,7 +38,7 @@ type GroupService interface {
|
||||
}
|
||||
|
||||
type groupService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
@@ -117,7 +118,7 @@ type UpdateGroupRequestParticipantsStruct struct {
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
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",
|
||||
instanceId,
|
||||
client != nil,
|
||||
@@ -641,7 +642,7 @@ func (g *groupService) UpdateGroupRequestParticipants(data *UpdateGroupRequestPa
|
||||
}
|
||||
|
||||
func NewGroupService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) GroupService {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
@@ -50,8 +51,8 @@ type InstanceService interface {
|
||||
type instances struct {
|
||||
instanceRepository instance_repository.InstanceRepository
|
||||
config *config.Config
|
||||
killChannel map[string](chan bool)
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
killChannel *safemap.Map[chan bool]
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
@@ -124,7 +125,7 @@ type ForceReconnectStruct struct {
|
||||
|
||||
func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
|
||||
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)
|
||||
|
||||
if client == nil {
|
||||
@@ -138,7 +139,7 @@ func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client,
|
||||
logger.LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
client = i.clientPointer[instanceId]
|
||||
client = i.clientPointer.Get(instanceId)
|
||||
logger.LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",
|
||||
instanceId,
|
||||
client != nil,
|
||||
@@ -242,7 +243,7 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
|
||||
}
|
||||
|
||||
// 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)
|
||||
err = i.whatsmeowService.UpdateInstanceSettings(instance.Id)
|
||||
@@ -258,7 +259,7 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
|
||||
if !isInstanceRunning {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting new client instance", instance.Id)
|
||||
|
||||
i.killChannel[instance.Id] = make(chan bool)
|
||||
i.killChannel.Set(instance.Id, make(chan bool))
|
||||
|
||||
clientData := &whatsmeow_service.ClientData{
|
||||
Instance: instance,
|
||||
@@ -288,8 +289,8 @@ func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instanc
|
||||
// logger.LogInfo("Waiting 1 seconds")
|
||||
// time.Sleep(1000 * time.Millisecond)
|
||||
|
||||
// if i.clientPointer[instance.Id] != nil {
|
||||
// if !i.clientPointer[instance.Id].IsConnected() {
|
||||
// if i.clientPointer.Get(instance.Id) != nil {
|
||||
// if !i.clientPointer.Get(instance.Id).IsConnected() {
|
||||
// return instance, "", "", fmt.Errorf("failed to connect")
|
||||
// }
|
||||
// } else {
|
||||
@@ -317,12 +318,14 @@ func (i instances) Disconnect(instance *instance_model.Instance) (*instance_mode
|
||||
if client.IsConnected() {
|
||||
if client.IsLoggedIn() {
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
|
||||
i.killChannel[instance.Id] <- true
|
||||
safemap.TrySend(i.killChannel.Get(instance.Id), true)
|
||||
|
||||
instance.Events = ""
|
||||
|
||||
err := i.instanceRepository.Update(instance)
|
||||
if err != nil {
|
||||
// Do not clear instance.Events on disconnect (upstream PR #187): an
|
||||
// empty events string makes CallWebhook drop every webhook after the
|
||||
// instance reconnects.
|
||||
instance.Connected = false
|
||||
instance.DisconnectReason = "Disconnected by API"
|
||||
if err := i.instanceRepository.UpdateConnected(instance.Id, false, instance.DisconnectReason); err != nil {
|
||||
return instance, err
|
||||
}
|
||||
|
||||
@@ -352,13 +355,10 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
|
||||
return instance, err
|
||||
}
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
i.clientPointer.Delete(instance.Id)
|
||||
i.killChannel.Delete(instance.Id)
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Logout successful", instance.Id)
|
||||
return instance, nil
|
||||
@@ -367,13 +367,10 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
|
||||
if client.IsConnected() {
|
||||
client.Disconnect()
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
i.clientPointer.Delete(instance.Id)
|
||||
i.killChannel.Delete(instance.Id)
|
||||
|
||||
i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)
|
||||
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) {
|
||||
client := i.clientPointer[instance.Id]
|
||||
client := i.clientPointer.Get(instance.Id)
|
||||
|
||||
if client == nil {
|
||||
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) {
|
||||
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
|
||||
if client == nil || client.IsLoggedIn() {
|
||||
@@ -435,7 +432,7 @@ func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, erro
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
// Verificar novamente se há cliente
|
||||
client = i.clientPointer[instance.Id]
|
||||
client = i.clientPointer.Get(instance.Id)
|
||||
if client != nil && client.IsLoggedIn() {
|
||||
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) {
|
||||
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.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.
|
||||
// PairPhone must be called after the QR event is received per whatsmeow docs.
|
||||
time.Sleep(3 * time.Second)
|
||||
client = i.clientPointer[instance.Id]
|
||||
client = i.clientPointer.Get(instance.Id)
|
||||
if client == nil {
|
||||
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 {
|
||||
if client := i.clientPointer[instance.Id]; client != nil {
|
||||
if client := i.clientPointer.Get(instance.Id); client != nil {
|
||||
instance.Connected = client.IsLoggedIn()
|
||||
} else {
|
||||
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
|
||||
if client := i.clientPointer[instance.Id]; client != nil {
|
||||
if client := i.clientPointer.Get(instance.Id); client != nil {
|
||||
instance.Connected = client.IsLoggedIn()
|
||||
} else {
|
||||
instance.Connected = false
|
||||
@@ -587,18 +584,18 @@ func (i instances) Delete(id string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if i.clientPointer[instance.Id] != nil && i.clientPointer[instance.Id].IsConnected() {
|
||||
if i.clientPointer[instance.Id].IsLoggedIn() {
|
||||
i.clientPointer[instance.Id].Logout(context.Background())
|
||||
if i.clientPointer.Get(instance.Id) != nil && i.clientPointer.Get(instance.Id).IsConnected() {
|
||||
if i.clientPointer.Get(instance.Id).IsLoggedIn() {
|
||||
i.clientPointer.Get(instance.Id).Logout(context.Background())
|
||||
}
|
||||
i.clientPointer[instance.Id].Disconnect()
|
||||
i.clientPointer.Get(instance.Id).Disconnect()
|
||||
}
|
||||
|
||||
// Limpar todos os recursos da instância antes de deletar
|
||||
delete(i.clientPointer, instance.Id)
|
||||
if i.killChannel[instance.Id] != nil {
|
||||
close(i.killChannel[instance.Id])
|
||||
delete(i.killChannel, instance.Id)
|
||||
i.clientPointer.Delete(instance.Id)
|
||||
if i.killChannel.Get(instance.Id) != nil {
|
||||
close(i.killChannel.Get(instance.Id))
|
||||
i.killChannel.Delete(instance.Id)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -713,7 +710,7 @@ func (i instances) ForceReconnect(instanceId string, number string) error {
|
||||
|
||||
subscribedEvents := strings.Split(instance.Events, ",")
|
||||
|
||||
i.killChannel[instance.Id] = make(chan bool)
|
||||
i.killChannel.Set(instance.Id, make(chan bool))
|
||||
|
||||
clientData := &whatsmeow_service.ClientData{
|
||||
Instance: instance,
|
||||
@@ -735,29 +732,26 @@ func (i instances) ForceReconnect(instanceId string, number string) error {
|
||||
}
|
||||
}
|
||||
|
||||
if i.clientPointer[instance.Id] != nil {
|
||||
client := i.clientPointer[instance.Id]
|
||||
if i.clientPointer.Get(instance.Id) != nil {
|
||||
client := i.clientPointer.Get(instance.Id)
|
||||
client.Disconnect()
|
||||
|
||||
select {
|
||||
case i.killChannel[instance.Id] <- true:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
safemap.TrySendTimeout(i.killChannel.Get(instance.Id), true, 5*time.Second)
|
||||
|
||||
delete(i.clientPointer, instance.Id)
|
||||
delete(i.killChannel, instance.Id)
|
||||
i.clientPointer.Delete(instance.Id)
|
||||
i.killChannel.Delete(instance.Id)
|
||||
}
|
||||
|
||||
go i.whatsmeowService.StartClient(clientData)
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
if i.clientPointer[instance.Id] != nil {
|
||||
if !i.clientPointer[instance.Id].IsConnected() {
|
||||
if i.clientPointer.Get(instance.Id) != nil {
|
||||
if !i.clientPointer.Get(instance.Id).IsConnected() {
|
||||
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")
|
||||
}
|
||||
} else {
|
||||
@@ -912,8 +906,8 @@ func (i instances) UpdateAdvancedSettings(instanceId string, settings *instance_
|
||||
|
||||
func NewInstanceService(
|
||||
instanceRepository instance_repository.InstanceRepository,
|
||||
killChannel map[string](chan bool),
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
killChannel *safemap.Map[chan bool],
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
config *config.Config,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
|
||||
@@ -3,6 +3,7 @@ package label_service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
@@ -25,7 +26,7 @@ type LabelService interface {
|
||||
}
|
||||
|
||||
type labelService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
labelRepository label_repository.LabelRepository
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
@@ -50,7 +51,7 @@ type EditLabelStruct struct {
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
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",
|
||||
instanceId,
|
||||
client != nil,
|
||||
@@ -226,7 +227,7 @@ func (l *labelService) GetLabels(instance *instance_model.Instance) ([]label_mod
|
||||
}
|
||||
|
||||
func NewLabelService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
labelRepository label_repository.LabelRepository,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -35,7 +36,7 @@ type MessageService interface {
|
||||
}
|
||||
|
||||
type messageService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
messageRepository message_repository.MessageRepository
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
@@ -95,7 +96,7 @@ type MessageSendStruct struct {
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
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",
|
||||
instanceId,
|
||||
client != nil,
|
||||
@@ -526,7 +527,7 @@ func (m *messageService) EditMessage(data *EditMessageStruct, instance *instance
|
||||
}
|
||||
|
||||
func NewMessageService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
messageRepository message_repository.MessageRepository,
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
|
||||
@@ -3,6 +3,7 @@ package newsletter_service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"time"
|
||||
|
||||
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
|
||||
@@ -22,7 +23,7 @@ type NewsletterService interface {
|
||||
}
|
||||
|
||||
type newsletterService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
@@ -47,7 +48,7 @@ type GetNewsletterMessagesStruct struct {
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
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",
|
||||
instanceId,
|
||||
client != nil,
|
||||
@@ -195,7 +196,7 @@ func (n *newsletterService) GetNewsletterMessages(data *GetNewsletterMessagesStr
|
||||
}
|
||||
|
||||
func NewNewsletterService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) NewsletterService {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
@@ -53,7 +54,7 @@ type SendService interface {
|
||||
}
|
||||
|
||||
type sendService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
config *config.Config
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
@@ -380,7 +381,7 @@ type MessageSendStruct struct {
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
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",
|
||||
instanceId,
|
||||
client != nil,
|
||||
@@ -2360,7 +2361,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
|
||||
|
||||
var message string
|
||||
if data.Id == "" {
|
||||
message = s.clientPointer[instance.Id].GenerateMessageID()
|
||||
message = s.clientPointer.Get(instance.Id).GenerateMessageID()
|
||||
} else {
|
||||
message = data.Id
|
||||
}
|
||||
@@ -2371,14 +2372,14 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
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 {
|
||||
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
|
||||
if isGroup && !isNewsletter {
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
@@ -2770,7 +2771,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
|
||||
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 {
|
||||
s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error sending message: %v", instance.Id, err)
|
||||
return nil, err
|
||||
@@ -2781,7 +2782,7 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
|
||||
messageInfo := types.MessageInfo{
|
||||
MessageSource: types.MessageSource{
|
||||
Chat: recipient,
|
||||
Sender: *s.clientPointer[instance.Id].Store.ID,
|
||||
Sender: *s.clientPointer.Get(instance.Id).Store.ID,
|
||||
IsFromMe: true,
|
||||
IsGroup: isGroup,
|
||||
},
|
||||
@@ -2835,15 +2836,15 @@ func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.
|
||||
sticker := msg.GetStickerMessage()
|
||||
|
||||
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 {
|
||||
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 {
|
||||
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 {
|
||||
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 {
|
||||
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)
|
||||
img, err := webp.Decode(webpReader)
|
||||
@@ -3366,7 +3367,7 @@ func (s *sendService) sendStatusWebhook(messageSent *MessageSendStruct, instance
|
||||
}
|
||||
|
||||
func NewSendService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
config *config.Config,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
@@ -33,7 +34,7 @@ type UserService interface {
|
||||
}
|
||||
|
||||
type userService struct {
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
}
|
||||
@@ -109,7 +110,7 @@ type PrivacyStruct struct {
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
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",
|
||||
instanceId,
|
||||
client != nil,
|
||||
@@ -543,7 +544,7 @@ func (u *userService) SetProfileStatus(data *SetProfileStatusStruct, instance *i
|
||||
}
|
||||
|
||||
func NewUserService(
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
whatsmeowService whatsmeow_service.WhatsmeowService,
|
||||
loggerWrapper *logger_wrapper.LoggerManager,
|
||||
) UserService {
|
||||
|
||||
@@ -207,6 +207,13 @@ func ParseJID(arg string) (whatsmeow_types.JID, bool) {
|
||||
return recipient, false
|
||||
}
|
||||
|
||||
// CreateJID keeps the "+" prefix for IsOnWhatsApp, but it is not part of a
|
||||
// user JID. WhatsApp does not answer queries addressed to "+<number>", so
|
||||
// they hang until the IQ timeout (upstream #223 / PR #224).
|
||||
if recipient.Server == whatsmeow_types.DefaultUserServer {
|
||||
recipient.User = strings.TrimPrefix(recipient.User, "+")
|
||||
}
|
||||
|
||||
if recipient.User == "" && !strings.Contains(jidString, "@broadcast") {
|
||||
logger.LogError("Invalid JID. No user specified: %s", jidString)
|
||||
return recipient, false
|
||||
|
||||
@@ -284,13 +284,13 @@ func TestParseJID(t *testing.T) {
|
||||
name: "Valid phone number",
|
||||
input: "15551234567",
|
||||
expectOk: true,
|
||||
expectJID: "+[email protected]",
|
||||
expectJID: "[email protected]",
|
||||
},
|
||||
{
|
||||
name: "Valid BR number",
|
||||
input: "5531987654321",
|
||||
expectOk: true,
|
||||
expectJID: "+[email protected]",
|
||||
expectJID: "[email protected]",
|
||||
},
|
||||
{
|
||||
name: "Valid group ID",
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/evolution-foundation/evolution-go/pkg/safemap"
|
||||
"image/png"
|
||||
"io"
|
||||
"math/rand"
|
||||
@@ -28,6 +29,7 @@ import (
|
||||
"go.mau.fi/whatsmeow/appstate"
|
||||
"go.mau.fi/whatsmeow/proto/waCompanionReg"
|
||||
"go.mau.fi/whatsmeow/proto/waE2E"
|
||||
"go.mau.fi/whatsmeow/proto/waWa6"
|
||||
"go.mau.fi/whatsmeow/store"
|
||||
"go.mau.fi/whatsmeow/store/sqlstore"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
@@ -83,10 +85,10 @@ type whatsmeowService struct {
|
||||
labelRepository label_repository.LabelRepository
|
||||
pollService poll_service.PollService // NOVO: Serviço de enquetes
|
||||
config *config.Config
|
||||
killChannel map[string](chan bool)
|
||||
killChannel *safemap.Map[chan bool]
|
||||
userInfoCache *cache.Cache
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
myClientPointer map[string]*MyClient
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
myClientPointer *safemap.Map[*MyClient]
|
||||
rabbitmqProducer producer_interfaces.Producer
|
||||
webhookProducer producer_interfaces.Producer
|
||||
websocketProducer producer_interfaces.Producer
|
||||
@@ -97,8 +99,18 @@ type whatsmeowService struct {
|
||||
natsProducer producer_interfaces.Producer
|
||||
loggerWrapper *logger_wrapper.LoggerManager
|
||||
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 {
|
||||
service WhatsmeowService
|
||||
WAClient *whatsmeow.Client
|
||||
@@ -115,9 +127,9 @@ type MyClient struct {
|
||||
messageRepository message_repository.MessageRepository
|
||||
labelRepository label_repository.LabelRepository
|
||||
pollService poll_service.PollService // NOVO: Serviço de enquetes
|
||||
clientPointer map[string]*whatsmeow.Client
|
||||
myClientPointer map[string]*MyClient
|
||||
killChannel map[string](chan bool)
|
||||
clientPointer *safemap.Map[*whatsmeow.Client]
|
||||
myClientPointer *safemap.Map[*MyClient]
|
||||
killChannel *safemap.Map[chan bool]
|
||||
userInfoCache *cache.Cache
|
||||
config *config.Config
|
||||
historySyncID int32
|
||||
@@ -171,11 +183,22 @@ type ProxyConfig struct {
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// reconnectsInProgress holds the instance IDs with a ReconnectClient running. Two Disconnected events for
|
||||
// the same instance in the same second used to run two reconnects concurrently and dereference a client the
|
||||
// other one had just removed, killing the whole process (upstream issue #188).
|
||||
var reconnectsInProgress sync.Map
|
||||
|
||||
func (w whatsmeowService) ReconnectClient(instanceId string) error {
|
||||
if _, running := reconnectsInProgress.LoadOrStore(instanceId, struct{}{}); running {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Reconnection already in progress, skipping duplicate request", instanceId)
|
||||
return nil
|
||||
}
|
||||
defer reconnectsInProgress.Delete(instanceId)
|
||||
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Starting reconnection process - simulating restart", instanceId)
|
||||
|
||||
// Passo 1: Limpar conexão existente se houver
|
||||
if client, exists := w.clientPointer[instanceId]; exists {
|
||||
if client, exists := w.clientPointer.Lookup(instanceId); exists && client != nil {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Disconnecting existing client", instanceId)
|
||||
|
||||
// Desconectar o cliente WebSocket
|
||||
@@ -185,7 +208,7 @@ func (w whatsmeowService) ReconnectClient(instanceId string) error {
|
||||
}
|
||||
|
||||
// Remover event handler se existir
|
||||
if mycli, ok := w.myClientPointer[instanceId]; ok {
|
||||
if mycli, ok := w.myClientPointer.Lookup(instanceId); ok {
|
||||
if mycli.eventHandlerID != 0 {
|
||||
client.RemoveEventHandler(mycli.eventHandlerID)
|
||||
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)
|
||||
|
||||
// Enviar sinal de kill se o canal existir
|
||||
if killChan, exists := w.killChannel[instanceId]; exists {
|
||||
select {
|
||||
case killChan <- true:
|
||||
if killChan, exists := w.killChannel.Lookup(instanceId); exists {
|
||||
if safemap.TrySendTimeout(killChan, true, 0) {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill signal sent", instanceId)
|
||||
default:
|
||||
// Canal pode estar bloqueado, continua
|
||||
}
|
||||
}
|
||||
|
||||
// Remover das estruturas
|
||||
delete(w.clientPointer, instanceId)
|
||||
delete(w.myClientPointer, instanceId)
|
||||
delete(w.killChannel, instanceId)
|
||||
w.clientPointer.Delete(instanceId)
|
||||
w.myClientPointer.Delete(instanceId)
|
||||
w.killChannel.Delete(instanceId)
|
||||
|
||||
// Limpar cache de userInfo para esta instância
|
||||
if instance, err := w.instanceRepository.GetInstanceByID(instanceId); err == nil {
|
||||
@@ -301,38 +321,181 @@ func (w whatsmeowService) ForceUpdateJid(instanceId string, number string) error
|
||||
return nil
|
||||
}
|
||||
|
||||
// getSharedSQLStoreContainer returns the process-wide whatsmeow sqlstore.Container.
|
||||
// PostgresAuthDB reuses the pooled authDB from initPostgresAuthDB (Upgrade once).
|
||||
// The Users/GORM database is intentionally separate and never passed here.
|
||||
func (w whatsmeowService) getSharedSQLStoreContainer() (*sqlstore.Container, error) {
|
||||
if w.authStore == nil {
|
||||
return nil, fmt.Errorf("shared sqlstore not initialized")
|
||||
}
|
||||
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) {
|
||||
|
||||
if _, starting := clientsStarting.LoadOrStore(cd.Instance.Id, struct{}{}); starting {
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Client start already in progress, skipping duplicate start", cd.Instance.Id)
|
||||
return
|
||||
}
|
||||
registered := false
|
||||
defer func() {
|
||||
if !registered {
|
||||
clientsStarting.Delete(cd.Instance.Id)
|
||||
}
|
||||
}()
|
||||
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Starting websocket connection to Whatsapp for user '%s'", cd.Instance.Id)
|
||||
|
||||
var deviceStore *store.Device
|
||||
var err error
|
||||
|
||||
if w.clientPointer[cd.Instance.Id] != nil {
|
||||
if w.clientPointer[cd.Instance.Id].IsConnected() {
|
||||
if w.clientPointer.Get(cd.Instance.Id) != nil {
|
||||
if w.clientPointer.Get(cd.Instance.Id).IsConnected() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var container *sqlstore.Container
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
container, err := w.getSharedSQLStoreContainer()
|
||||
if err != nil {
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to create container: %v", cd.Instance.Id, err)
|
||||
return
|
||||
@@ -398,7 +561,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
|
||||
waVer := store.WAVersionContainer{uint32(version.Major), uint32(version.Minor), uint32(version.Patch)}
|
||||
store.SetWAVersion(waVer)
|
||||
if store.BaseClientPayload != nil && store.BaseClientPayload.UserAgent != nil {
|
||||
store.BaseClientPayload.UserAgent.AppVersion = &waProto.ClientPayload_UserAgent_AppVersion{
|
||||
store.BaseClientPayload.UserAgent.AppVersion = &waWa6.ClientPayload_UserAgent_AppVersion{
|
||||
Primary: proto.Uint32(uint32(version.Major)),
|
||||
Secondary: proto.Uint32(uint32(version.Minor)),
|
||||
Tertiary: proto.Uint32(uint32(version.Patch)),
|
||||
@@ -416,7 +579,10 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
|
||||
clientLog := waLog.Stdout("Client", minLevel, true)
|
||||
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 {
|
||||
var proxyConfig ProxyConfig
|
||||
@@ -504,7 +670,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
|
||||
mycli.eventHandlerID = mycli.WAClient.AddEventHandler(mycli.myEventHandler)
|
||||
|
||||
// Armazena o MyClient no map para permitir atualizações posteriores
|
||||
w.myClientPointer[cd.Instance.Id] = mycli
|
||||
w.myClientPointer.Set(cd.Instance.Id, mycli)
|
||||
|
||||
if client.Store.ID != nil {
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Already logged in with JID: %s", cd.Instance.Id, client.Store.ID.String())
|
||||
@@ -578,12 +744,12 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
|
||||
|
||||
for {
|
||||
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)
|
||||
client.Disconnect()
|
||||
|
||||
delete(w.clientPointer, cd.Instance.Id)
|
||||
delete(w.myClientPointer, cd.Instance.Id)
|
||||
w.clientPointer.Delete(cd.Instance.Id)
|
||||
w.myClientPointer.Delete(cd.Instance.Id)
|
||||
|
||||
// Limpar cache de userInfo para esta instância
|
||||
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)
|
||||
}
|
||||
|
||||
// Without a paired device (QR timed out, logged out, or the phone removed this device) a restart would
|
||||
// only create a new device and cycle QR codes forever. Stop here; the next /instance/connect or
|
||||
// /instance/qr starts a fresh client (upstream PR #240).
|
||||
if client.Store.ID == nil {
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] No paired device; not restarting client", cd.Instance.Id)
|
||||
return
|
||||
}
|
||||
|
||||
// restart client
|
||||
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Restarting client", cd.Instance.Id)
|
||||
w.StartClient(cd)
|
||||
@@ -658,7 +832,7 @@ func schedulePresenceUpdates(mycli *MyClient) {
|
||||
randomInterval := time.Duration(1+rand.Intn(3)) * time.Hour
|
||||
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)
|
||||
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
|
||||
// the original timeout branch so the signal is never dropped.
|
||||
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] QR timeout — signaling kill channel", instanceID)
|
||||
if killChan, exists := mycli.killChannel[instanceID]; exists {
|
||||
killChan <- true
|
||||
if killChan, exists := mycli.killChannel.Lookup(instanceID); exists {
|
||||
if !safemap.TrySend(killChan, true) {
|
||||
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] Kill channel already closed (instance deleted)", instanceID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -879,6 +1055,9 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
|
||||
}
|
||||
}
|
||||
case *events.Connected, *events.PushNameSetting:
|
||||
// A real connection ends the loop, so the backoff counter dies here.
|
||||
// Without this, a drop tomorrow would inherit today's restarts.
|
||||
reconnectSucceeded(mycli.userID)
|
||||
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] events.Connected to Whatsapp for user '%s'", mycli.userID, mycli.WAClient.Store.PushName)
|
||||
if len(mycli.WAClient.Store.PushName) > 0 {
|
||||
doWebhook = true
|
||||
@@ -911,7 +1090,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
|
||||
|
||||
// jid, ok := utils.ParseJID(mycli.WAClient.Store.ID.ToNonAD().User)
|
||||
// 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,
|
||||
// })
|
||||
// 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)
|
||||
}
|
||||
|
||||
decrypted, err := mycli.clientPointer[mycli.userID].DecryptPollVote(context.Background(), evt)
|
||||
decrypted, err := mycli.clientPointer.Get(mycli.userID).DecryptPollVote(context.Background(), evt)
|
||||
if err != nil {
|
||||
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decrypt vote: %v", mycli.userID, err)
|
||||
} else {
|
||||
@@ -1821,6 +2000,27 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
|
||||
doWebhook = true
|
||||
postMap["event"] = "Archive"
|
||||
|
||||
// postMap["data"] still holds the raw event at this point, so the type
|
||||
// assertion below panicked on every Archive event. Same marshal/unmarshal
|
||||
// step every other case in this switch already does.
|
||||
if postMap["data"] != nil {
|
||||
jsonBytes, err := json.Marshal(postMap["data"])
|
||||
if err != nil {
|
||||
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to marshal postMap['data']: %v", mycli.userID, err)
|
||||
return
|
||||
}
|
||||
|
||||
var parsed map[string]interface{}
|
||||
if err := json.Unmarshal(jsonBytes, &parsed); err != nil {
|
||||
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to unmarshal postMap['data'] to map[string]interface{}: %v", mycli.userID, err)
|
||||
return
|
||||
}
|
||||
|
||||
postMap["data"] = parsed
|
||||
} else {
|
||||
postMap["data"] = make(map[string]interface{})
|
||||
}
|
||||
|
||||
dataMap := postMap["data"].(map[string]interface{})
|
||||
dataMap["JID"] = evt.JID
|
||||
dataMap["Timestamp"] = evt.Timestamp
|
||||
@@ -1901,7 +2101,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
|
||||
}
|
||||
|
||||
// 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:
|
||||
doWebhook = true
|
||||
postMap["event"] = "ChatPresence"
|
||||
@@ -1988,6 +2188,20 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
|
||||
// Trigger instance restart via websocket-capable service (non-blocking)
|
||||
go func(instanceID string) {
|
||||
mycli.loggerWrapper.GetLogger(instanceID).LogInfo("[%s] Disconnected detected, restarting instance", instanceID)
|
||||
|
||||
if allowed, wait := reconnectAllowed(instanceID); !allowed {
|
||||
if wait < 0 {
|
||||
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] a reconnect is already scheduled — this event will not open another", instanceID)
|
||||
return
|
||||
}
|
||||
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] reconnect loop detected: more than %d restarts in %s. Next attempt in %s. If the device was logged out from the phone, only a new QR scan will fix it.", instanceID, reconnectFreeAttempts, reconnectWindow, wait)
|
||||
if err := mycli.instanceRepository.UpdateConnected(instanceID, false, fmt.Sprintf("Reconnect backing off — next attempt in %s", wait)); err != nil {
|
||||
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] could not record the backoff reason: %v", instanceID, err)
|
||||
}
|
||||
time.Sleep(wait)
|
||||
reconnectWaitDone(instanceID)
|
||||
}
|
||||
|
||||
if err := mycli.service.ReconnectClient(instanceID); err != nil {
|
||||
mycli.loggerWrapper.GetLogger(instanceID).LogError("[%s] Failed to restart instance: %v", instanceID, err)
|
||||
}
|
||||
@@ -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{
|
||||
Instance: instance,
|
||||
@@ -2694,7 +2908,7 @@ func (w whatsmeowService) UpdateInstanceSettings(instanceId string) error {
|
||||
}
|
||||
|
||||
// Verifica se o MyClient existe
|
||||
myClient, exists := w.myClientPointer[instanceId]
|
||||
myClient, exists := w.myClientPointer.Lookup(instanceId)
|
||||
if !exists {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId)
|
||||
return fmt.Errorf("instance %s not found in runtime", instanceId)
|
||||
@@ -2753,7 +2967,7 @@ func (w whatsmeowService) UpdateInstanceAdvancedSettings(instanceId string) erro
|
||||
}
|
||||
|
||||
// Verifica se o MyClient existe
|
||||
myClient, exists := w.myClientPointer[instanceId]
|
||||
myClient, exists := w.myClientPointer.Lookup(instanceId)
|
||||
if !exists {
|
||||
w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId)
|
||||
return fmt.Errorf("instance %s not found in runtime", instanceId)
|
||||
@@ -2773,19 +2987,19 @@ func (w whatsmeowService) ClearInstanceCache(instanceId string, token string) er
|
||||
w.userInfoCache.Delete(token)
|
||||
|
||||
// Limpar myClientPointer se existir
|
||||
if _, exists := w.myClientPointer[instanceId]; exists {
|
||||
delete(w.myClientPointer, instanceId)
|
||||
if _, exists := w.myClientPointer.Lookup(instanceId); exists {
|
||||
w.myClientPointer.Delete(instanceId)
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] MyClient pointer cleared", instanceId)
|
||||
}
|
||||
|
||||
// Limpar clientPointer se existir
|
||||
if _, exists := w.clientPointer[instanceId]; exists {
|
||||
delete(w.clientPointer, instanceId)
|
||||
if _, exists := w.clientPointer.Lookup(instanceId); exists {
|
||||
w.clientPointer.Delete(instanceId)
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client pointer cleared", instanceId)
|
||||
}
|
||||
|
||||
// Limpar killChannel se existir
|
||||
if killChan, exists := w.killChannel[instanceId]; exists {
|
||||
if killChan, exists := w.killChannel.Lookup(instanceId); exists {
|
||||
select {
|
||||
case killChan <- true:
|
||||
// Canal recebeu o sinal
|
||||
@@ -2793,7 +3007,7 @@ func (w whatsmeowService) ClearInstanceCache(instanceId string, token string) er
|
||||
// Canal pode estar bloqueado, apenas fecha
|
||||
}
|
||||
close(killChan)
|
||||
delete(w.killChannel, instanceId)
|
||||
w.killChannel.Delete(instanceId)
|
||||
w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill channel cleared", instanceId)
|
||||
}
|
||||
|
||||
@@ -2807,8 +3021,8 @@ func NewWhatsmeowService(
|
||||
messageRepository message_repository.MessageRepository,
|
||||
labelRepository label_repository.LabelRepository,
|
||||
config *config.Config,
|
||||
killChannel map[string](chan bool),
|
||||
clientPointer map[string]*whatsmeow.Client,
|
||||
killChannel *safemap.Map[chan bool],
|
||||
clientPointer *safemap.Map[*whatsmeow.Client],
|
||||
rabbitmqProducer producer_interfaces.Producer,
|
||||
webhookProducer producer_interfaces.Producer,
|
||||
websocketProducer producer_interfaces.Producer,
|
||||
@@ -2831,7 +3045,7 @@ func NewWhatsmeowService(
|
||||
killChannel: killChannel,
|
||||
userInfoCache: cache.New(5*time.Minute, 10*time.Minute),
|
||||
clientPointer: clientPointer,
|
||||
myClientPointer: make(map[string]*MyClient),
|
||||
myClientPointer: safemap.New[*MyClient](),
|
||||
rabbitmqProducer: rabbitmqProducer,
|
||||
webhookProducer: webhookProducer,
|
||||
websocketProducer: websocketProducer,
|
||||
@@ -2842,6 +3056,7 @@ func NewWhatsmeowService(
|
||||
natsProducer: natsProducer,
|
||||
loggerWrapper: loggerWrapper,
|
||||
passkeyCeremony: ceremony.NewStore(),
|
||||
authStore: &sharedSQLStore{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2859,7 +3074,7 @@ func (w *whatsmeowService) PasskeyCeremonyStore() *ceremony.Store {
|
||||
// SubmitPasskeyResponse forwards the browser's WebAuthn assertion to WhatsApp
|
||||
// for the given instance. Called by POST /passkey-ceremony/{token}/response.
|
||||
func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.WebAuthnResponse) error {
|
||||
client, ok := w.clientPointer[instanceId]
|
||||
client, ok := w.clientPointer.Lookup(instanceId)
|
||||
if !ok || client == nil {
|
||||
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.
|
||||
// Called by POST /passkey-ceremony/{token}/confirm.
|
||||
func (w *whatsmeowService) ConfirmPasskey(instanceId string) error {
|
||||
client, ok := w.clientPointer[instanceId]
|
||||
client, ok := w.clientPointer.Lookup(instanceId)
|
||||
if !ok || client == nil {
|
||||
return fmt.Errorf("no active client for instance %s", instanceId)
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
Reference in new issue
Block a user