Author SHA1 Message Date
jfeng fd7fc29d11 fix(ci): require explicit latest promotion on manual tag builds
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 2m55s
Docker - Promover latest / Promover release para latest (push) Failing after 4m50s
Docker - Build e Publicacao / Build, Scan e Publicacao (push) Successful in 3m25s
2026-11-13 22:03:35 -03:00
jfeng 406fcc2e52 fix(auth): adopt upstream 0.7.3 retry and publish verified latest 2026-11-13 21:51:08 -03:00
jfengandClaude Opus 5.5 b140fdb390 fix(send): send to known LIDs passed as phone numbers; expose version
Docker - Build e Publicacao / Build, Scan e Publicacao (push) Successful in 2m28s
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 3m58s
Docker - Promover latest / Promover release para latest (push) Successful in 4m39s
Integrations that store the contact's LID as its number (255284433936406)
failed with 'no LID found for [email protected]'. When the number
is not a registered phone and the instance's LID store maps it to a phone
number, send to <number>@lid instead.

GET /server/ok now also returns the running version, so a deployment can be
checked without reading the startup log.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 08:15:58 -03:00
jfengandClaude Opus 5.5 c9511a636e ci: retry registry login, pull and push
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 1m48s
A transient timeout on the registry token endpoint failed the publication of
v0.7.2-evogo.2 (run 482) after the image had already been built and scanned.
Login, pull and push now retry up to 5 times with linear backoff.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 07:52:15 -03:00
jfengandClaude Opus 5.5 5b71495e93 fix(send): resolve Brazilian 9th digit by asking WhatsApp for both variants
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 2m42s
Docker - Build e Publicacao / Build, Scan e Publicacao (push) Successful in 1m23s
Accounts created before the 9th digit rollout are still registered without it
(554291389691), newer ones with it (5542991389691). The DDD-based rewrite in
CreateJID cannot be right for every account, and the existence check queried
only the number as received, so sends to 5542991389691 failed for an account
registered as 554291389691.

validateAndCheckUserExists now queries both forms in one IsOnWhatsApp call and
uses the registered one (received form first). Non-Brazilian numbers, groups,
LIDs and landlines follow the previous path unchanged. Related: upstream
issue #214 / PR #208.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:11:49 -03:00
jfengandClaude Opus 5.5 03d619bb55 ci: promote last v* release in maintained-stable to :latest without rebuilding
CI - Validacao Go / Validar Codigo e Testes (push) Successful in 4m8s
Docker - Build e Publicacao / Build, Scan e Publicacao (push) Successful in 2m42s
Docker - Promover latest / Promover release para latest (push) Successful in 2m18s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:40:58 -03:00
14 changed files with 526 additions and 34 deletions

No files matched your search

+58 -6
View File
@@ -6,7 +6,8 @@ name: Docker - Build e Publicacao
# 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.
# Tags v* aprovadas em maintained-stable tambem promovem :latest apos o push
# das tags imutavel e semantica, evitando a corrida com promote-latest.yml.
on:
push:
@@ -32,6 +33,10 @@ on:
default: false
required: false
concurrency:
group: promote-latest
cancel-in-progress: false
env:
REGISTRY: git.jf.eng.br
IMAGE: git.jf.eng.br/jfeng/evogo
@@ -44,6 +49,36 @@ jobs:
steps:
- name: Checkout do Repositorio
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Validar origem da promocao latest
id: promotion
run: |
PROMOTE=false
if { [ "${{ github.event_name }}" = "push" ] && [ "${{ github.ref_type }}" = "tag" ]; } || [ "${{ github.event.inputs.promote_latest }}" = "true" ]; then
git fetch origin maintained-stable
if git merge-base --is-ancestor HEAD FETCH_HEAD; then
PROMOTE=true
elif [ "${{ github.event.inputs.promote_latest }}" = "true" ]; then
echo "Promocao recusada: commit nao aprovado em maintained-stable"
exit 1
fi
fi
echo "promote=${PROMOTE}" >> "$GITHUB_OUTPUT"
- name: Configurar Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Validar codigo antes da publicacao
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends libjpeg-dev libwebp-dev poppler-utils ffmpeg
go mod verify
go vet ./...
go test -v ./...
- name: Obter Versao e Commit SHA
id: meta
@@ -97,21 +132,38 @@ jobs:
[ -n "$USER" ] || USER="${{ github.actor }}"
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin
# O registry ja estourou timeout pontualmente (run 482); tenta de novo antes de falhar.
for n in 1 2 3 4 5; do
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin && exit 0
echo "Login falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
exit 1
- name: Publicar Imagens no Registry
if: steps.meta.outputs.publish == 'true'
run: |
push() {
for n in 1 2 3 4 5; do
docker push "$1" && return 0
echo "Push de $1 falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
return 1
}
SRC=evogo:ci-${{ steps.meta.outputs.commit_sha }}
for TAG in "${{ steps.meta.outputs.image_tag }}" "${{ steps.meta.outputs.version }}"; do
docker tag "$SRC" "$IMAGE:$TAG"
docker push "$IMAGE:$TAG"
push "$IMAGE:$TAG"
echo "Publicado: $IMAGE:$TAG"
done
if [ "${{ github.event.inputs.promote_latest }}" = "true" ]; then
if [ "${{ steps.promotion.outputs.promote }}" = "true" ]; then
docker tag "$SRC" "$IMAGE:latest"
docker push "$IMAGE:latest"
echo "Publicado: $IMAGE:latest"
push "$IMAGE:latest"
IMMUTABLE_DIGEST=$(docker buildx imagetools inspect "$IMAGE:${{ steps.meta.outputs.image_tag }}" --format '{{json .Manifest.Digest}}')
LATEST_DIGEST=$(docker buildx imagetools inspect "$IMAGE:latest" --format '{{json .Manifest.Digest}}')
[ -n "$IMMUTABLE_DIGEST" ] && [ "$IMMUTABLE_DIGEST" = "$LATEST_DIGEST" ]
echo "Publicado e verificado: $IMAGE:latest = $IMMUTABLE_DIGEST"
fi
- name: Limpeza
+71
View File
@@ -0,0 +1,71 @@
name: Docker - Promover latest
# :latest = ultimo release v* contido em maintained-stable.
# Nao recompila: baixa a imagem imutavel <versao>-<sha7> ja publicada pelo
# docker-build.yml para aquela tag e apenas a re-etiqueta, preservando o digest.
# So roda quando maintained-stable avanca (promocao aprovada) ou manualmente.
on:
push:
branches:
- maintained-stable
workflow_dispatch:
concurrency:
group: promote-latest
cancel-in-progress: false
env:
REGISTRY: git.jf.eng.br
IMAGE: git.jf.eng.br/jfeng/evogo
jobs:
promote:
name: Promover release para latest
runs-on: ubuntu-latest
steps:
- name: Checkout do Repositorio
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Identificar release
id: rel
run: |
git fetch --tags --force
TAG=$(git describe --tags --abbrev=0 --match 'v*' HEAD)
SHA7=$(git rev-list -n1 "$TAG" | cut -c1-7)
VERSION="${TAG#v}"
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
echo "source=${IMAGE}:${VERSION}-${SHA7}" >> "$GITHUB_OUTPUT"
echo "Release: ${TAG} -> ${IMAGE}:${VERSION}-${SHA7}"
- name: Login no Gitea Package Registry
run: |
USER="${{ secrets.REGISTRY_USER }}"
[ -n "$USER" ] || USER="${{ github.actor }}"
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
for n in 1 2 3 4 5; do
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin && exit 0
echo "Login falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
exit 1
- name: Re-etiquetar como latest
run: |
retry() {
for n in 1 2 3 4 5; do
"$@" && return 0
echo "'$*' falhou (tentativa $n/5); nova tentativa em $((n*15))s"
sleep $((n*15))
done
return 1
}
SRC="${{ steps.rel.outputs.source }}"
retry docker pull "$SRC"
docker tag "$SRC" "$IMAGE:latest"
retry docker push "$IMAGE:latest"
echo "Publicado: $IMAGE:latest (mesmo digest de $SRC)"
+25
View File
@@ -2,6 +2,16 @@
## Não lançado
### Manutenção da atualização 0.7.3
- Incorporadas seletivamente as melhorias do upstream 0.7.3: timeout de 60 s
no upgrade do banco de autenticação, nova tentativa após falha e registro
explícito do driver Postgres na configuração.
- SQLite de autenticação limitado a uma conexão compartilhada, evitando
concorrência de escrita; preservadas as correções próprias de envio e reconexão.
- Releases por tag aprovadas em `maintained-stable` passam a publicar `latest`
após as imagens versionadas, com conferência do digest e testes Go no pipeline.
- Sem alteração de dependências, schema ou contratos públicos nesta atualização.
### 🔧 Correções
- **whatsmeow atualizado para 2026-11-02** — a versão fixada na 0.7.2
(commit `b572e5bcb92b`, de 30/06/2026) ficou 125 dias atrás do upstream. O
@@ -22,6 +32,19 @@
(pacote inexistente); `ClientPayload_UserAgent_AppVersion` vem de
`go.mau.fi/whatsmeow/proto/waWa6`.
- **Nono dígito (BR)** — envios para celulares brasileiros consultam no
WhatsApp as duas variantes (com e sem o 9) e usam a que está registrada.
Contas antigas sem o 9 (ex.: `554291389691`) passam a receber mesmo quando o
sistema envia `5542991389691`, e vice-versa (upstream issue #214 / PR #208).
- **LID enviado como número** — quando o `number` não existe como telefone mas
é o LID de um contato já conhecido pela instância (ex.: `255284433936406`),
o envio vai direto para `255284433936406@lid` em vez de falhar com
`no LID found for [email protected]`.
### 🆕 Novidades
- `GET /server/ok` passa a informar a versão em execução
(`{"status":"ok","version":"0.7.2-evogo.3-<sha7>"}`).
### 🛡️ Estabilidade (correções da comunidade incorporadas pelo EvoGO)
- **Crash `concurrent map writes`** — `clientPointer`, `myClientPointer` e
`killChannel` agora são `safemap.Map` com RWMutex (upstream PR #196, issue #203).
@@ -48,6 +71,8 @@
e PR automático; conflitos viram Issue; aviso de whatsmeow desatualizado.
- Publicação da imagem em `git.jf.eng.br/jfeng/evogo` por tag `v*`, com tag
imutável `<versão>-<sha7>` e scan Trivy.
- Login, pull e push no registry com até 5 tentativas — um timeout pontual do
endpoint de token derrubou a publicação da `v0.7.2-evogo.2` (run 482).
## v0.7.2
+1 -1
View File
@@ -1 +1 @@
0.7.2
0.7.3-evogo.1
+1 -1
View File
@@ -239,7 +239,7 @@ func setupRouter(db *gorm.DB, authDB *sql.DB, sqliteDB *sql.DB, config *config.C
label_handler.NewLabelHandler(labelService),
newsletter_handler.NewNewsletterHandler(newsletterService),
pollHandler,
server_handler.NewServerHandler(),
server_handler.NewServerHandler(version),
).AssignRoutes(r)
if config.ConnectOnStartup {
+46 -3
View File
@@ -89,15 +89,20 @@ O pipeline é orquestrado via `.gitea/workflows/docker-build.yml`:
publicação de:
- `git.jf.eng.br/jfeng/evogo:<versão>-<sha7>` (imutável)
- `git.jf.eng.br/jfeng/evogo:<versão>`
Se o commit já estiver em `maintained-stable`, promove também `latest`
e confere seu digest após publicar as imagens versionadas.
3. **`workflow_dispatch`:** publica apenas com `publish_image=true`; `:latest`
só com `promote_latest=true`.
### Gerar um release
```bash
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
# Após validar em maintained-develop e aprovar a promoção do commit:
git checkout maintained-stable
git pull --ff-only
# Integrar o commit validado pelo processo de revisão antes de criar a tag.
git tag -a v0.7.3-evogo.1 -m "EvoGO 0.7.3-evogo.1"
git push origin v0.7.3-evogo.1 # publica versão, tag imutável e latest
```
### Usar no docker-compose
@@ -111,3 +116,41 @@ services:
Como o pacote é privado, o host precisa de `docker login git.jf.eng.br`
(usuário Gitea + token com escopo `read:package`) antes de `docker compose pull`.
Para fixar exatamente o commit testado, use a tag imutável `<versão>-<sha7>`.
### Promover para `:latest`
`.gitea/workflows/promote-latest.yml` roda quando `maintained-stable` avança:
re-etiqueta a imagem imutável do último release `v*` contido na branch
(`<versão>-<sha7>`) como `:latest`, sem recompilar (mesmo digest).
```bash
git checkout maintained-stable
git merge --ff-only v0.7.2-evogo.1
git push origin maintained-stable # dispara a promoção para :latest
```
Rollback de `:latest`: avance/reverta `maintained-stable` para o release
anterior e rode o workflow manualmente, ou fixe a tag de versão no compose.
## Atualização seletiva 0.7.3-evogo.1
Esta release preserva o fork e incorpora apenas as melhorias de inicialização
SQL da 0.7.3. Não altera o whatsmeow, o schema, o licenciamento ou as APIs.
Ordem de publicação: validar a branch de manutenção, integrar em
`maintained-develop`, validar a imagem e sessões em homologação, promover o
commit validado a `maintained-stable` e então criar a tag
`v0.7.3-evogo.1` nesse commit. A publicação exige aprovação humana.
O workflow de build executa vet e testes antes de publicar. Para pushes de tags `v*`
cujo commit esteja em `maintained-stable`, publica as tags semântica e imutável,
promove `latest` e exige que o digest remoto seja igual ao da tag imutável.
A promoção e o build compartilham o grupo de concorrência `promote-latest`.
O workflow manual também exige essa ancestralidade para `promote_latest=true`.
Uma execução verde e a igualdade dos digests são a evidência da publicação;
a existência do YAML não comprova que uma imagem foi publicada.
Rollback: registrar o digest e a tag imutável anteriormente usados por `latest`
antes da promoção. Em caso de regressão, fixar essa imagem no Compose e seguir
[ROLLBACK.md](ROLLBACK.md). Esta alteração não requer migração adicional nem
restauração do banco. Manter o snapshot anterior para recuperação operacional.
+2
View File
@@ -10,6 +10,8 @@ import (
"time"
"github.com/gomessguii/logger"
// Register the auth database driver independently of the WhatsApp service.
_ "github.com/lib/pq"
"gorm.io/driver/postgres"
"gorm.io/gorm"
+13
View File
@@ -0,0 +1,13 @@
package config
import (
"database/sql"
"slices"
"testing"
)
func TestPostgresDriverRegistered(t *testing.T) {
if !slices.Contains(sql.Drivers(), "postgres") {
t.Fatalf("postgres driver not registered: %v", sql.Drivers())
}
}
+79
View File
@@ -531,11 +531,30 @@ func (s *sendService) validateAndCheckUserExists(phone string, formatJid *bool,
return types.NewJID("", types.DefaultUserServer), fmt.Errorf("failed to connect client: %v", err)
}
// Brazilian mobiles: ask WhatsApp for both forms (with and without the 9th
// digit) and use the one that is registered.
if variants := utils.BRPhoneVariants(phone); len(variants) > 1 {
if remoteJID, found := s.checkBRPhoneVariants(client, variants, instance.Id); found {
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Number %s verified as valid WhatsApp user, using remoteJID: %s", instance.Id, phone, remoteJID)
formatJidFalse := false
return validateMessageFields(remoteJID, &formatJidFalse, messageID, participant)
}
}
// Use CheckUser approach: formatJid=false by default
formatJidForCheck := false
// First attempt with formatJid=false
remoteJID, found, err := s.checkSingleUserExists(client, phone, formatJidForCheck, instance.Id)
if err != nil || !found {
// Integrations often store the contact's LID as if it were a phone
// number. If it is a LID this device already knows, send to it directly.
if lid, ok := s.knownLID(client, phone, instance.Id); ok {
s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Number %s is a known LID, sending to %s", instance.Id, phone, lid)
formatJidFalse := false
return validateMessageFields(lid.String(), &formatJidFalse, messageID, participant)
}
}
if err != nil {
s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Failed to check user existence: %v", instance.Id, err)
// Continue with sending even if check fails (network issues, etc.)
@@ -592,6 +611,66 @@ func (s *sendService) checkSingleUserExists(client *whatsmeow.Client, phone stri
return remoteJID, true, nil
}
// knownLID reports whether phone is actually a LID with a phone number mapping
// in the local store, returning it as a @lid JID.
func (s *sendService) knownLID(client *whatsmeow.Client, phone string, instanceId string) (types.JID, bool) {
if client.Store == nil || client.Store.LIDs == nil {
return types.JID{}, false
}
user := utils.LIDCandidate(phone)
if user == "" {
return types.JID{}, false
}
lid := types.NewJID(user, types.HiddenUserServer)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
pn, err := client.Store.LIDs.GetPNForLID(ctx, lid)
if err != nil {
s.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Failed to look up LID %s: %v", instanceId, lid, err)
return types.JID{}, false
}
if pn.IsEmpty() {
return types.JID{}, false
}
return lid, true
}
// checkBRPhoneVariants queries every variant in a single IsOnWhatsApp call and
// returns the JID of the first one that is registered, in the given order.
// Errors are logged and reported as not found so the regular check still runs.
func (s *sendService) checkBRPhoneVariants(client *whatsmeow.Client, variants []string, instanceId string) (string, bool) {
phones := make([]string, len(variants))
for i, v := range variants {
phones[i] = "+" + v
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
resp, err := client.IsOnWhatsApp(ctx, phones)
if err != nil {
s.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Failed to check BR number variants %v: %v", instanceId, variants, err)
return "", false
}
for _, v := range variants {
for _, r := range resp {
if r.IsIn && strings.TrimPrefix(r.Query, "+") == v {
return r.JID.String(), true
}
}
}
// Query not echoed back as sent: any registered result is one of our variants.
for _, r := range resp {
if r.IsIn {
return r.JID.String(), true
}
}
return "", false
}
func findURL(text string) string {
urlRegex := `http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+`
re := regexp.MustCompile(urlRegex)
+4 -2
View File
@@ -7,15 +7,17 @@ type ServerHandler interface {
}
type serverHandler struct {
version string
}
// ServerOk implements ServerHandler.
func (s *serverHandler) ServerOk(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"status": "ok",
"version": s.version,
})
}
func NewServerHandler() ServerHandler {
return &serverHandler{}
func NewServerHandler(version string) ServerHandler {
return &serverHandler{version: version}
}
+65
View File
@@ -187,6 +187,71 @@ func formatBRNumber(jid string) string {
return jid
}
// BRPhoneVariants returns both forms of a Brazilian mobile number — with and
// without the 9th digit — with the received form first, or nil when the number
// is not a Brazilian mobile.
//
// Accounts created before the 9th digit rollout are still registered without
// it (e.g. 554291389691), newer ones with it (5542991389691). No fixed rule
// derived from the DDD is right for every account, so callers should ask
// WhatsApp which of the two exists.
func BRPhoneVariants(number string) []string {
if strings.Contains(number, "@") {
if !strings.HasSuffix(number, "@"+whatsmeow_types.DefaultUserServer) {
return nil
}
number = strings.Split(number, "@")[0]
}
number = strings.Split(number, ":")[0]
digits := strings.Map(func(r rune) rune {
if r >= '0' && r <= '9' {
return r
}
return -1
}, number)
// 55 + DDD (11-99, never starting with 0) + subscriber
if !strings.HasPrefix(digits, "55") || len(digits) < 12 || digits[2] == '0' {
return nil
}
switch len(digits) {
case 13:
if digits[4] == '9' {
return []string{digits, digits[:4] + digits[5:]}
}
case 12:
// 8-digit mobile numbers start with 6, 7, 8 or 9; landlines with 2-5
if digits[4] >= '6' {
return []string{digits, digits[:4] + "9" + digits[4:]}
}
}
return nil
}
// LIDCandidate returns the user part of number when it could be a LID sent as
// a phone number ("255284433936406", "[email protected]"), or ""
// when it has another server, a device suffix or non-digit characters.
func LIDCandidate(number string) string {
if strings.Contains(number, "@") {
if !strings.HasSuffix(number, "@"+whatsmeow_types.DefaultUserServer) {
return ""
}
number = strings.Split(number, "@")[0]
}
number = strings.TrimPrefix(strings.TrimSpace(number), "+")
if len(number) < 8 {
return ""
}
for _, r := range number {
if r < '0' || r > '9' {
return ""
}
}
return number
}
// ParseJID parses a number string into a WhatsApp JID with validation
func ParseJID(arg string) (whatsmeow_types.JID, bool) {
if arg == "" {
+51
View File
@@ -384,3 +384,54 @@ func TestCanonicalJID(t *testing.T) {
})
}
}
func TestBRPhoneVariants(t *testing.T) {
tests := []struct {
name string
input string
want []string
}{
{"13 digits with 9", "5542991389691", []string{"5542991389691", "554291389691"}},
{"12 digits without 9", "554291389691", []string{"554291389691", "5542991389691"}},
{"plus and JID suffix", "[email protected]", []string{"5511987654321", "551187654321"}},
{"formatted", "+55 (42) 99138-9691", []string{"5542991389691", "554291389691"}},
{"landline", "554232221234", nil},
{"not Brazil", "15551234567", nil},
{"group", "[email protected]", nil},
{"lid", "255284433936406@lid", nil},
{"13 digits without 9 after DDD", "5542891389691", nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := BRPhoneVariants(tt.input)
if len(got) != len(tt.want) {
t.Fatalf("BRPhoneVariants(%q) = %v, want %v", tt.input, got, tt.want)
}
for i := range got {
if got[i] != tt.want[i] {
t.Fatalf("BRPhoneVariants(%q) = %v, want %v", tt.input, got, tt.want)
}
}
})
}
}
func TestLIDCandidate(t *testing.T) {
tests := []struct {
input string
want string
}{
{"255284433936406", "255284433936406"},
{"[email protected]", "255284433936406"},
{"255284433936406@lid", ""},
{"[email protected]", ""},
{"255284433936406:[email protected]", ""},
{"+55 (42) 99138-9691", ""},
{"1234", ""},
}
for _, tt := range tests {
if got := LIDCandidate(tt.input); got != tt.want {
t.Errorf("LIDCandidate(%q) = %q, want %q", tt.input, got, tt.want)
}
}
}
@@ -0,0 +1,84 @@
package whatsmeow_service
import (
"context"
"os"
"path/filepath"
"sync"
"testing"
"github.com/evolution-foundation/evolution-go/pkg/config"
"go.mau.fi/whatsmeow/proto/waAdv"
"go.mau.fi/whatsmeow/store/sqlstore"
"go.mau.fi/whatsmeow/types"
_ "modernc.org/sqlite"
)
func TestSharedAuthContainerRetryAndConcurrentReuse(t *testing.T) {
root := t.TempDir()
w := whatsmeowService{config: &config.Config{}, exPath: root, authStore: &sharedSQLStore{}}
t.Cleanup(func() {
if w.authStore.sqliteDB != nil {
if err := w.authStore.sqliteDB.Close(); err != nil {
t.Errorf("close auth store: %v", err)
}
}
})
if _, err := w.getSharedSQLStoreContainer(); err == nil {
t.Fatal("expected failure before dbdata exists")
}
if err := os.Mkdir(filepath.Join(root, "dbdata"), 0o755); err != nil {
t.Fatal(err)
}
const callers = 16
containers := make([]*sqlstore.Container, callers)
errs := make([]error, callers)
var wg sync.WaitGroup
for i := range callers {
wg.Add(1)
go func() {
defer wg.Done()
containers[i], errs[i] = w.getSharedSQLStoreContainer()
}()
}
wg.Wait()
for i := range callers {
if errs[i] != nil || containers[i] == nil {
t.Fatalf("caller %d could not retry: %v", i, errs[i])
}
if containers[i] != containers[0] {
t.Fatalf("caller %d opened a different container", i)
}
}
if got := w.authStore.sqliteDB.Stats().MaxOpenConnections; got != 1 {
t.Fatalf("SQLite connection limit = %d, want 1", got)
}
// Persist a paired-device record and reopen the existing schema as on restart.
device := containers[0].NewDevice()
jid := types.NewJID("5511999999999", types.DefaultUserServer)
device.ID = &jid
device.Account = &waAdv.ADVSignedDeviceIdentity{
Details: []byte("test device"),
AccountSignature: make([]byte, 64),
AccountSignatureKey: make([]byte, 32),
DeviceSignature: make([]byte, 64),
}
if err := device.Save(context.Background()); err != nil {
t.Fatalf("save session: %v", err)
}
if err := w.authStore.sqliteDB.Close(); err != nil {
t.Fatal(err)
}
w.authStore = &sharedSQLStore{}
reopened, err := w.getSharedSQLStoreContainer()
if err != nil {
t.Fatalf("reopen existing auth database: %v", err)
}
restored, err := reopened.GetDevice(context.Background(), jid)
if err != nil || restored == nil {
t.Fatalf("restore session: device=%v err=%v", restored, err)
}
if restored.RegistrationID != device.RegistrationID || *restored.NoiseKey.Pub != *device.NoiseKey.Pub {
t.Fatal("session keys changed after reopening")
}
}
+26 -21
View File
@@ -22,7 +22,6 @@ import (
"golang.org/x/image/webp"
"google.golang.org/protobuf/proto"
_ "github.com/lib/pq"
"github.com/patrickmn/go-cache"
"github.com/skip2/go-qrcode"
"go.mau.fi/whatsmeow"
@@ -99,16 +98,15 @@ 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 is heap-allocated so its mutex is shared by value-receiver methods.
authStore *sharedSQLStore
}
// sharedSQLStore holds the process-wide whatsmeow sqlstore.Container for PostgresAuthDB
// (or the sqlite fallback). One Upgrade per process; never Close on instance disconnect.
// (or the sqlite fallback). Cache only success; never Close on instance disconnect.
type sharedSQLStore struct {
once sync.Once
mu sync.Mutex
container *sqlstore.Container
err error
sqliteDB *sql.DB // kept alive when not using PostgresAuthDB
}
type MyClient struct {
@@ -328,46 +326,53 @@ func (w whatsmeowService) getSharedSQLStoreContainer() (*sqlstore.Container, err
if w.authStore == nil {
return nil, fmt.Errorf("shared sqlstore not initialized")
}
w.authStore.once.Do(func() {
w.authStore.mu.Lock()
defer w.authStore.mu.Unlock()
if w.authStore.container != nil {
return w.authStore.container, nil
}
return w.createSharedSQLStoreContainer()
}
// Called with authStore.mu held. A failed upgrade is retried by the next caller.
func (w whatsmeowService) createSharedSQLStoreContainer() (*sqlstore.Container, error) {
var dbLog waLog.Logger
if w.config.WaDebug != "" {
dbLog = waLog.Stdout("Database", w.config.WaDebug, true)
}
ctx := context.Background()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
if w.config.PostgresAuthDB != "" {
if w.authDB == nil {
w.authStore.err = fmt.Errorf("postgres auth DB handle is nil")
return
return nil, fmt.Errorf("postgres auth DB handle is nil")
}
container := sqlstore.NewWithDB(w.authDB, "postgres", dbLog)
if err := container.Upgrade(ctx); err != nil {
// Do not Close authDB — owned by main.
w.authStore.err = fmt.Errorf("failed to upgrade database: %w", err)
return
return nil, fmt.Errorf("failed to upgrade database: %w", err)
}
w.authStore.container = container
return
return container, nil
}
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
return nil, fmt.Errorf("failed to open sqlite auth store: %w", err)
}
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
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
if closeErr := db.Close(); closeErr != nil {
return nil, fmt.Errorf("failed to upgrade database: %w; close sqlite auth store: %v", err, closeErr)
}
return nil, fmt.Errorf("failed to upgrade database: %w", err)
}
w.authStore.sqliteDB = db
w.authStore.container = container
})
return w.authStore.container, w.authStore.err
return container, nil
}
// ============================================================================