-
Notifications
You must be signed in to change notification settings - Fork 0
feat(audit): sessão Maestro 2026-05-12 — RLS 100%, FK órfãos limpos, guardas anti-órfão #147
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| # 📥 Contrato de Leitura do Inbox | ||
|
|
||
| > **Última atualização:** 2026-05-12 | ||
| > **Aplicabilidade:** qualquer código sob `src/components/inbox/**`, `src/hooks/inbox/**`, `src/pages/Inbox*` e `src/features/inbox/**` | ||
| > **Enforced by:** `eslint.config.js` (`no-restricted-imports` na "Inbox read zone") | ||
|
|
||
| --- | ||
|
|
||
| ## 🎯 Objetivo | ||
|
|
||
| Centralizar **toda** leitura do Inbox em uma única camada para preservar 4 invariantes: | ||
|
|
||
| 1. **Origem única de verdade:** dados do Inbox vêm do **FATOR X** (banco externo), não da Evolution API. | ||
| 2. **Resiliência:** circuit breaker, retry e proxy estão na camada `lib/externalProxy.ts` — pular essa camada quebra essa rede de proteção. | ||
| 3. **Performance:** chamadas à Evolution API são lentas e contam contra rate-limit do provedor — usadas só para ações pontuais. | ||
| 4. **Auditoria:** todas leituras passam por um caminho instrumentado (`queryExternalProxy`). | ||
|
|
||
| Quando esta regra é violada, o resultado típico é: UI carrega lenta, intermitente, sem retry, sem fallback, e gera ruído nos rate-limits do WhatsApp. | ||
|
|
||
| --- | ||
|
|
||
| ## ✅ Caminhos permitidos | ||
|
|
||
| | Quero... | Use | NÃO use | | ||
| |---|---|---| | ||
| | Listar threads/conversas do Inbox | `queryExternalProxy()` + hooks do `features/inbox` | chamar `evolution-api/find-chats` direto | | ||
| | Listar mensagens de uma thread | `queryExternalProxy()` + hooks do `features/inbox` | `evolution-api/list-messages` / `find-messages` | | ||
| | Procurar contato/conversa | Hook canônico em `features/inbox` | `evolution-api/find*` direto | | ||
| | **Enviar** mensagem | `externalMessageSender` (`src/lib/`) | `evolution-api/send-*` direto | | ||
| | Status realtime (online/typing) | Subscribe via `Realtime` no `features/inbox` | polling cru | | ||
|
|
||
| ### Resumo em uma frase | ||
|
|
||
| > **"Inbox lê via `queryExternalProxy → external-db-proxy`. Para envio, usa `externalMessageSender`. Evolution API só serve para ações específicas (números, presence, status), nunca para popular UI."** | ||
|
|
||
| --- | ||
|
|
||
| ## ❌ Imports proibidos (e motivo) | ||
|
|
||
| Configurado em `eslint.config.js` — Inbox Read Zone (~linhas 80-110): | ||
|
|
||
| ```js | ||
| { | ||
| files: [ | ||
| "src/components/inbox/**/*.{ts,tsx}", | ||
| "src/hooks/inbox/**/*.{ts,tsx}", | ||
| "src/pages/Inbox*.{ts,tsx}", | ||
| ], | ||
| rules: { | ||
| "no-restricted-imports": ["error", { patterns: [ | ||
| { group: ["**/evolution-api/**/find*"], message: "..." }, | ||
| { group: ["**/evolution-api/**/list-messages*"], message: "..." }, | ||
| { group: ["**/evolution-api/**/find-messages*"], message: "..." }, | ||
| { group: ["**/evolution-api/**/find-chats*"], message: "..." }, | ||
| ] }], | ||
| }, | ||
| } | ||
| ``` | ||
|
|
||
| | Padrão proibido | Motivo | | ||
| |---|---| | ||
| | `**/evolution-api/**/find*` | Pode pular o proxy, ignora cache + circuit breaker | | ||
| | `**/evolution-api/**/list-messages*` | Mesmo motivo + lento sob volume | | ||
| | `**/evolution-api/**/find-messages*` | Idem | | ||
| | `**/evolution-api/**/find-chats*` | Idem | | ||
| | `**/features/*/**` (deep import) | Encapsulamento — use entry point da feature | | ||
| | `../../*`, `../../../*` (deep relative) | Use alias `@/features/...` | | ||
|
|
||
| --- | ||
|
|
||
| ## 🔁 Fluxo correto | ||
|
|
||
| ``` | ||
| ┌──────────────────┐ queryExternalProxy() ┌──────────────────┐ | ||
| │ Inbox UI (React)│ ─────────────────────────────────► │ external-db-proxy │ | ||
| │ │ (com retry, circuit breaker) │ (Edge Function) │ | ||
| └──────────────────┘ └────────┬─────────┘ | ||
| │ | ||
| ▼ | ||
| ┌───────────────┐ | ||
| │ FATOR X (DB) │ | ||
| └───────────────┘ | ||
| ``` | ||
|
|
||
| Para **envio:** | ||
|
|
||
| ``` | ||
| ┌──────────────────┐ externalMessageSender ┌────────────────────┐ | ||
| │ Inbox UI (React)│ ──────────────────────────► │ evolution-sender │ | ||
| │ │ │ (Edge Function) │ | ||
| └──────────────────┘ └─────────┬──────────┘ | ||
| │ | ||
| ▼ | ||
| ┌──────────────┐ | ||
| │ Evolution API│ | ||
| └──────────────┘ | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 🧪 Como propor mudança no contrato | ||
|
|
||
| 1. **Abra uma issue** descrevendo o caso de uso (ex.: "preciso ler dados X que hoje não estão no proxy") | ||
| 2. **Discuta** em PR se o caso cabe em `queryExternalProxy` (adicionar novo endpoint) ou se justifica exceção | ||
| 3. **PR de mudança** precisa atualizar 3 coisas juntas: | ||
| - A regra em `eslint.config.js` | ||
| - Este documento | ||
| - Hook/lib novo (se aplicável) | ||
| 4. **Aprovação** exige revisão de quem mantém `lib/externalProxy.ts` | ||
|
|
||
| --- | ||
|
|
||
| ## 🔎 FAQ | ||
|
|
||
| ### "Estou refatorando um componente antigo e preciso usar `evolution-api/find-chats` temporariamente." | ||
|
|
||
| Não. Use o hook do `features/inbox` ou estenda-o. Se o hook não cobre o caso, abra issue antes de fazer o workaround. Workaround se acumula e vira regressão de arquitetura. | ||
|
|
||
| ### "E para testes?" | ||
|
|
||
| Testes E2E (`e2e/**`, `tests/e2e/**`) **podem** chamar Evolution API direto — é parte do que o teste valida. A regra está restrita à zona de produção do Inbox. | ||
|
|
||
| ### "Preciso buscar UM dado pontual (ex.: avatar de número desconhecido)." | ||
|
|
||
| Endpoints fora do conjunto proibido (`find*`, `list-messages*`, `find-messages*`, `find-chats*`) são permitidos — por exemplo, `evolution-api/check-numbers`, `evolution-api/fetch-whatsapp-avatar`. Mas considere primeiro se isso deveria estar no proxy. | ||
|
|
||
| ### "ESLint está mentindo: o erro fala desse doc, mas o doc não existe." | ||
|
|
||
| Não está mais! Você está lendo ele agora 😉. Se mesmo assim alguma coisa parece quebrada, abra issue. | ||
|
|
||
| --- | ||
|
|
||
| ## 📚 Referências | ||
|
|
||
| - `eslint.config.js` — Inbox read zone (regra que aponta para este doc) | ||
| - `src/lib/externalProxy.ts` — implementação do `queryExternalProxy` e circuit breaker | ||
| - `src/lib/evolutionCircuitBreaker.ts` — circuit breaker | ||
| - `src/lib/evolutionSendRetry.ts` — retry de envio | ||
| - `src/features/inbox/` — feature canônica do Inbox | ||
|
|
||
| --- | ||
|
|
||
| *Este contrato foi escrito em 2026-05-12 como parte da remediação P1.5 do AUDIT.md. Antes disso, a mensagem do ESLint apontava para um documento inexistente — o que confundia mais do que ajudava.* |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Adding this CI gate makes the pipeline fail on the current repository state, because
scripts/check-references.tsvalidatespackage.jsonscript targets andpackage.jsonstill containsperf:budget/perf:budget:baselinepointing toscripts/check-performance-budget.mjs, which is not present. As a result, every PR run will fail at this new step before lint/build/tests.Useful? React with 👍 / 👎.