diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 496b6c0..c8663a9 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -134,7 +134,7 @@ jobs:
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Trivy image scan (HIGH/CRITICAL)
- uses: aquasecurity/trivy-action@0.28.0
+ uses: aquasecurity/trivy-action@915b19bbe73b92a6cf82a1bc12b087c9a19a5fe2 # v0.28.0
with:
image-ref: ghcr.io/${{ github.repository }}:${{ github.ref_name }}
format: table
diff --git a/README.md b/README.md
index 1ea9156..def3d1d 100644
--- a/README.md
+++ b/README.md
@@ -1,278 +1,125 @@
-
+# NexusData
-# 🛰️ NexusData
+An event-driven document-processing reference application built with FastAPI, Celery and PostgreSQL.
-**Plataforma Multi-Tenant de Processamento Assíncrono e Inteligente de Documentos (IDP)**
+The API accepts a document-processing request, creates a job and returns `202 Accepted`. A background worker processes the job, records its status and can notify clients through signed webhooks or WebSocket updates. A React dashboard exposes ingestion, job tracking, API keys and webhook management.
-*API orientada a eventos que recebe grandes volumes de dados não estruturados, valida, enfileira, processa em background (workers + IA), persiste o resultado estruturado e notifica os clientes via Webhook ou WebSocket.*
+**Current processing uses a deterministic mock adapter.** External AI providers and semantic search are extension points on the roadmap.
-`Python 3.12+` · `FastAPI` · `SQLAlchemy 2.0 async` · `PostgreSQL` · `Redis` · `RabbitMQ + Celery` · `Docker`
+## Implemented scope
-
+- JWT authentication, API keys with scopes and administrator/user roles.
+- Tenant-scoped access in application services and repositories.
+- Idempotent ingestion, request fingerprint checks and database uniqueness constraints.
+- Background processing with retries and a circuit breaker.
+- HMAC-signed webhook delivery, URL validation and IP pinning.
+- WebSocket job updates and a React/Vite dashboard.
+- Structured logging, Prometheus metrics and OpenTelemetry instrumentation.
+- Alembic migrations, unit tests and database integration tests.
----
+These are implementation features. Deployment readiness, throughput and latency require separate verification.
-## 📌 O Problema
-
-Empresas de jurídico, contabilidade, e-commerce e RH recebem **milhares de arquivos não estruturados por dia** (contratos, notas fiscais, tickets). Elas precisam extrair dados, validar regras de negócio e integrar com outros sistemas. **APIs tradicionais dão _timeout_** ao tentar processar isso de forma síncrona.
-
-## ✅ A Solução
-
-Uma API **assíncrona e orientada a eventos**: a ingestão responde em milissegundos (HTTP `202 Accepted`), o trabalho pesado roda em **workers desacoplados**, e o cliente é notificado quando termina — com resiliência (retry, circuit breaker), isolamento multi-tenant e observabilidade de produção.
-
----
-
-## 🏗️ Arquitetura
+## Architecture
```mermaid
flowchart LR
- subgraph Client["👤 Cliente / Dashboard"]
- UI[React SPA]
- EXT[Integração via API Key]
- end
-
- subgraph API["⚡ API (FastAPI - stateless)"]
- MW[Middlewares
CorrelationId · RateLimit · Security]
- AUTH[Auth JWT / API Key + RBAC]
- ING[POST /documents/process → 202]
- WS[(WebSocket /ws/jobs)]
- end
-
- subgraph Infra["🧱 Estado & Mensageria"]
- PG[(PostgreSQL
tenants · jobs · docs)]
- RD[(Redis
rate limit · idempotência · pub/sub)]
- MQ[(RabbitMQ
filas)]
- end
-
- subgraph Workers["⚙️ Workers (Celery)"]
- W1[process_document
CircuitBreaker + Retry]
- W2[deliver_webhook
HMAC + backoff]
- AI[[IA plugável
mock · Claude · OpenAI]]
- end
-
- UI -->|Bearer JWT| API
- EXT -->|X-API-Key| API
- ING -->|persiste PENDING| PG
- ING -->|publica| MQ
- MW <--> RD
- MQ --> W1 --> AI
- W1 -->|atualiza status| PG
- W1 -->|pub/sub| RD --> WS --> UI
- W1 -->|evento| MQ --> W2 -->|POST assinado| EXT
-```
-
-### Fluxo de uma ingestão (sequência)
-
-```mermaid
-sequenceDiagram
- autonumber
- participant C as Cliente
- participant A as API
- participant DB as PostgreSQL
- participant Q as RabbitMQ
- participant W as Worker
- participant R as Redis→WS
-
- C->>A: POST /documents/process (Idempotency-Key)
- A->>DB: cria Document + Job (PENDING)
- A->>Q: publica job
- A-->>C: 202 Accepted { job_id }
- Q->>W: entrega job
- W->>DB: PROCESSING
- W->>R: push status (WebSocket)
- W->>W: processa (retry/circuit breaker)
- W->>DB: COMPLETED / FAILED
- W->>R: push status final
- W->>C: Webhook POST assinado (HMAC)
- C->>A: GET /jobs/{id} (polling opcional)
+ Client["Client or dashboard"] --> API["FastAPI API"]
+ API --> DB["PostgreSQL"]
+ API --> Queue["RabbitMQ"]
+ Queue --> Worker["Celery worker"]
+ Worker --> Processor["Mock processor"]
+ Worker --> DB
+ Worker --> Redis["Redis"]
+ Redis --> Updates["WebSocket updates"]
+ Worker --> Webhook["Signed webhook"]
```
-### Clean Architecture (dependências apontam para dentro)
-
-```
-presentation ─▶ application ─▶ domain ◀─ infrastructure
- (FastAPI) (use cases) (puro) (SQLAlchemy, Redis, Celery…)
-```
-
-| Camada | Responsabilidade | Depende de |
-|---|---|---|
-| **domain** | Entidades, regras de negócio, máquina de estados do job, interfaces (Protocols) | nada (Python puro) |
-| **application** | Casos de uso, DTOs, _ports_ | domain |
-| **infrastructure** | Implementações concretas dos ports (DB, cache, mensageria, IA, segurança) | domain, application |
-| **presentation** | Rotas HTTP/WS, middlewares, tradução de erros | todas |
-
-> O domínio **não importa** SQLAlchemy, FastAPI, Redis ou Celery. Trocar qualquer tecnologia é uma mudança localizada na infraestrutura + no `Container` (composition root).
-
----
-
-## 🔐 Segurança (defesa em profundidade)
-
-> *"Não deve ser porque uma pessoa tem acesso ao código que consegue hackear o sistema."* — nada de segredo no código; a segurança vem de design, não de obscuridade.
-
-- **Senhas com Argon2id** (vencedor da PHC), verificação em tempo constante e _rehash_ transparente.
-- **JWT endurecido**: algoritmo **fixo** na decodificação (bloqueia `alg=none`/confusion), claims obrigatórias (`exp`, `iat`, `nbf`, `sub`, `tid`, `type`), `aud`/`iss` verificados, `jti` por token.
-- **Isolamento multi-tenant** garantido em 3 camadas: middleware/auth → serviço (checagem explícita) → repositório (queries sempre escopadas por `tenant_id`). 404 (não 403) em recursos de outro tenant, para não revelar existência.
-- **RBAC** (Admin/User) + **API Keys com escopos** (privilégio mínimo). Segredo da API key exibido **uma única vez**; só o hash é persistido.
-- **Rate limiting distribuído** (Redis, janela atômica via Lua) por API key / sessão / IP.
-- **Idempotência** em 2 níveis: `Idempotency-Key` (cache de resposta no Redis, com detecção de reuso de chave com corpo diferente) **e** _unique constraint_ no banco.
-- **Webhooks assinados com HMAC-SHA256** (esquema anti-replay estilo Stripe) + **defesa anti-SSRF** (bloqueio de IPs privados/loopback/link-local/metadata `169.254.169.254`) + HTTPS obrigatório.
-- **Erros seguros**: exceções internas nunca vazam ao cliente — viram `500` genérico; o detalhe fica só no log com `correlation_id`.
-- **Cabeçalhos de segurança** (CSP, X-Frame-Options, nosniff, Referrer-Policy, HSTS em produção), **CORS restrito** a origens explícitas, `extra="forbid"` em todos os inputs.
-- **Segredos** sempre em `SecretStr`; validador impede subir produção com segredo padrão/fraco.
-- Celery aceita **apenas JSON** (nunca `pickle` — evita RCE por desserialização).
+The Python application separates domain rules, application services, infrastructure adapters and HTTP/WebSocket presentation. See [the application package](src/nexusdata), [processor factory](src/nexusdata/infrastructure/ai/factory.py) and [worker](src/nexusdata/worker).
-### 🎯 Red-team (o sistema foi atacado antes de ser aprovado)
+| Area | Tools |
+| --- | --- |
+| API and validation | Python 3.12+, FastAPI, Pydantic |
+| Persistence | PostgreSQL, SQLAlchemy, Alembic |
+| Background work | Celery, RabbitMQ |
+| Shared state | Redis |
+| Dashboard | React, TypeScript, Vite |
+| Local environment | Docker Compose |
+| Checks | Ruff, Mypy, Pytest, Testcontainers |
-Uma equipe de segurança independente (4 lentes: authz/isolamento, injeção/SSRF,
-cripto/vazamento, DoS/concorrência) tentou derrubar o sistema. **Achados reais
-corrigidos e cobertos por testes de regressão:**
+Qdrant is included in the local Compose environment; the current processor does not implement semantic search.
-| # | Falha | Correção |
-|---|---|---|
-| A | SSRF por **DNS-rebinding** (TOCTOU) no webhook | Resolve 1×, **fixa o IP validado** na conexão (SNI/cert seguem o hostname) |
-| B | **Bypass de rate-limit** por header forjável (buckets ilimitados) | Chave sempre por **IP do socket** (não confia em `X-API-Key`/`Authorization`) |
-| C | Job preso em `PROCESSING` em erro não-`ProcessorError` | `except Exception` amplo roteia p/ retry/falha |
-| D | Redelivery duplicada em `PROCESSING` levantava erro | No-op idempotente para job já em processamento |
-| E | `raw_payload`/corpo sem limite → OOM | Middleware de tamanho de corpo (413) |
-| F | Reserva de idempotência presa por 24h em crash | TTL curto (60s) no placeholder `in_progress` |
-| G | WebSocket sem limite → exaustão de FD | Cap por tenant e global |
-| H | Tenant desativado ainda autenticava (API key) | Auth de API key valida `tenant.is_active` |
-| I | Hardening de produção incompleto | Bloqueia senhas default de DB/RabbitMQ e exige chave de IA |
-| J | Regex de correlation-id aceitava `\n` final | `fullmatch` (defesa contra CRLF) |
+## Local development
-**Tradeoffs residuais conscientes** (documentados, endereçados no roadmap):
-o secret do webhook é reversível por design → **cifrar em repouso (KMS)**; o token
-do WebSocket vai na query string → migrar para **subprotocolo/ticket**; o *dual-write*
-(job `PENDING` + publish) precisa de **Transactional Outbox**; revogação de JWT via
-denylist (`jti`); `/metrics` deve ficar **restrito por rede** em produção.
-
----
-
-## 🚀 Começando (ambiente local)
-
-Pré-requisitos: **Docker** + **Docker Compose**. (Opcional para rodar fora do container: **uv** e Python 3.12+.)
+Prerequisites: Docker with Compose, Python 3.12+, `uv`, and GNU Make with Bash. On Windows, the Makefile expects a Bash-compatible environment.
```bash
-# 1. Configure o ambiente
-cp .env.example .env # ajuste segredos se quiser
-
-# 2. Suba tudo (Postgres, Redis, RabbitMQ, Qdrant, API, Worker, Prometheus, Grafana)
-make up # docker compose up -d --build
-
-# 3. Rode as migrations e popule um tenant de exemplo
+git clone https://github.com/cesaints/nexusdata.git
+cd nexusdata
+cp .env.example .env
+make install
+make up
make migrate
-make seed # cria tenant "acme" + admin@acme.test
-
-# 4. Acesse
-# API .......... http://localhost:8000/docs
-# RabbitMQ ..... http://localhost:15672 (nexus / nexus_dev_password)
-# Grafana ...... http://localhost:3000 (admin / admin)
-# Frontend ..... http://localhost:5173 (make front)
+make seed
```
-### Rodando sem Docker (desenvolvimento)
+Review the example configuration and use a development database. `make seed` writes demonstration data; inspect its source before using it with an existing database. Configuration values belong in the local environment.
+
+The API documentation is served at [localhost:8000/docs](http://localhost:8000/docs). To start the dashboard with the repository's development target:
```bash
-make install # uv sync --all-extras --group dev
-make hooks # instala os git hooks (pre-commit)
-make run # sobe a API com reload
-make worker # em outro terminal: sobe o worker Celery
+make front
```
----
+The dashboard's Vite development server uses [localhost:5173](http://localhost:5173).
-## 📚 Principais endpoints
+The commands above are defined in the [Makefile](Makefile). They were checked against source for this documentation revision; a fresh local setup was not executed during that review.
-| Método | Rota | Auth | Descrição |
-|---|---|---|---|
-| `POST` | `/api/v1/auth/register` | — | Cria tenant + admin |
-| `POST` | `/api/v1/auth/login` | — | Emite access + refresh token |
-| `POST` | `/api/v1/auth/refresh` | — | Renova tokens |
-| `GET` | `/api/v1/auth/me` | JWT/Key | Identidade do principal |
-| `POST` | `/api/v1/documents/process` | JWT/Key | **Ingestão → 202 + job_id** |
-| `GET` | `/api/v1/jobs/{id}` | JWT/Key | Status do job (polling) |
-| `GET` | `/api/v1/jobs` | JWT/Key | Lista jobs (paginado) |
-| `POST` | `/api/v1/api-keys` | Admin | Cria API key (segredo 1x) |
-| `POST` | `/api/v1/webhooks` | Admin | Registra webhook (secret 1x) |
-| `WS` | `/api/v1/ws/jobs?token=…` | JWT | Status em tempo real |
-| `GET` | `/health/ready` · `/metrics` | — | Ops (Prometheus) |
+## API overview
-Exemplo de ingestão idempotente:
+The API routes use the `/api/v1` prefix.
-```bash
-curl -X POST http://localhost:8000/api/v1/documents/process \
- -H "Authorization: Bearer $TOKEN" \
- -H "Idempotency-Key: 7c9e...unique" \
- -H "Content-Type: application/json" \
- -d '{"doc_type":"invoice","raw_payload":{"invoice_number":"NF-123","total_amount":1990}}'
-# → 202 { "job_id": "…", "status": "pending", "idempotent_replay": false }
-```
+| Route | Purpose |
+| --- | --- |
+| `POST /auth/register` | Create a tenant and administrator |
+| `POST /auth/login` | Issue authentication tokens |
+| `POST /auth/refresh` | Refresh authentication |
+| `POST /documents/process` | Submit work and receive a job identifier |
+| `GET /jobs` | List accessible jobs |
+| `GET /jobs/{id}` | Read a job's status |
+| `POST /api-keys` | Create an API key |
+| `POST /webhooks` | Register a webhook |
+| `WS /ws/jobs` | Receive job updates |
----
+Use the running OpenAPI documentation for request schemas and authorization requirements.
-## 🧪 Qualidade & Testes
+## Verification
```bash
-make check # ruff (lint) + mypy (tipos estritos)
-make test # pytest + cobertura (falha se < 80%)
-make test-int # testes de integração com Testcontainers (Postgres/Redis reais)
+make check
+make test-unit
+make test-int
```
-- **Testes unitários** isolam I/O com fakes in-memory dos ports.
-- **Testes de integração** sobem Postgres/Redis reais via **Testcontainers**.
-- **CI** (GitHub Actions): Ruff → Mypy → Pytest (cobertura ≥ 80%) → build da imagem Docker.
+The [CI workflow](.github/workflows/ci.yml) runs lint and type checks, unit tests with an 80% coverage gate, database integration tests, frontend compilation and secret scanning. Integration tests use PostgreSQL through Testcontainers.
----
+See [GitHub Actions](https://github.com/cesaints/nexusdata/actions/workflows/ci.yml) for the result of each revision. The Docker image job runs on pushes to `main` and `develop`, and is skipped on pull requests. Image publication and a reporting-only vulnerability scan do not establish production readiness.
-## 🧠 Decisões arquiteturais (o "porquê")
+This documentation describes the implemented scope. A complete local deployment and load testing remain separate verification steps.
-> **Por que RabbitMQ + Celery em vez de processar no request?**
-> Resiliência e desacoplamento. Se a API reiniciar, a requisição em memória seria perdida; na fila, a mensagem fica **persistida**. Processar inline bloquearia o event loop e esgotaria memória sob carga. Com workers, escalo **ingestão (API)** e **processamento (workers)** de forma independente.
-
-> **Por que Unit of Work + Repository?**
-> Transações atômicas explícitas e queries testáveis/desacopladas do ORM. A integridade (unicidade, idempotência) é garantida por **constraints no banco**, não só por checagens de aplicação — resistente a corridas.
-
-> **Como garanto _exactly-once_ com entrega _at-least-once_?**
-> O worker usa `SELECT … FOR UPDATE` + checagem de estado terminal: entregas duplicadas do mesmo job são **idempotentes**. A `Idempotency-Key` protege a ingestão.
-
-> **Por que o worker mantém um event loop persistente?**
-> Combinar Celery (prefork) com SQLAlchemy/redis assíncronos exige reusar o mesmo loop por processo — evita o clássico *"future attached to a different loop"*.
-
----
-
-## 📁 Estrutura do projeto
-
-```
-nexusdata/
-├── src/nexusdata/
-│ ├── domain/ # Entidades, value objects, exceções, interfaces (puro)
-│ ├── application/ # Casos de uso, DTOs, ports
-│ ├── infrastructure/ # DB, cache, mensageria, IA, segurança, observabilidade
-│ ├── presentation/ # FastAPI: rotas, middlewares, WebSocket, deps
-│ └── worker/ # Celery app + tasks
-├── alembic/ # Migrations versionadas
-├── tests/ # unit · integration
-├── frontend/ # Dashboard React + Vite
-├── docker/ # Dockerfiles
-├── .github/workflows/ # CI/CD
-├── docker-compose.yml
-└── pyproject.toml
-```
+## Known limits and next steps
----
+- Implement real document-processing adapters; the current factory supports `mock`.
+- Add a transactional outbox to address the database-write/queue-publication gap.
+- Encrypt stored webhook secrets using a suitable key-management design.
+- Replace WebSocket query-string tokens with a ticket or subprotocol flow.
+- Add token revocation and refresh-token replay handling.
+- Restrict operational metrics in a deployed environment.
+- Verify deployment configuration and operational behavior before production use.
-## 🗺️ Roadmap (pós-slice)
+Idempotency handles specific replay scenarios; it is not a claim of end-to-end exactly-once processing.
-- [ ] Transactional Outbox + sweeper para publicação garantida (fecha o dual-write)
-- [ ] Cifrar secrets de webhook em repouso (envelope encryption / KMS)
-- [ ] Token do WebSocket via subprotocolo ou ticket de uso único (fora da query string)
-- [ ] Denylist de JWT (revogação via `jti`) + rotação com detecção de replay
-- [ ] Integração real de IA (Claude/OpenAI) + busca semântica (Qdrant)
-- [ ] Terraform (ECS/RDS/ElastiCache) — IaC nível arquiteto
-- [ ] `/metrics` restrito por rede + rate-limit por principal autenticado (sliding window)
+## Project status and rights
----
+This repository is a reference application with documented operational work remaining. No production deployment or load-test result is asserted here.
-
-Construído com foco em resiliência, segurança e clareza arquitetural.
-
+The [Python manifest](pyproject.toml) currently declares `Proprietary`. No standalone license file was present in the reviewed revision.
diff --git a/src/nexusdata/infrastructure/database/unit_of_work.py b/src/nexusdata/infrastructure/database/unit_of_work.py
index 213a539..bb0def1 100644
--- a/src/nexusdata/infrastructure/database/unit_of_work.py
+++ b/src/nexusdata/infrastructure/database/unit_of_work.py
@@ -26,6 +26,11 @@
)
+def _is_unique_violation(error: IntegrityError) -> bool:
+ sqlstate: object = getattr(error.orig, "sqlstate", None)
+ return sqlstate == "23505"
+
+
class SqlAlchemyUnitOfWork:
"""Implementa o port UnitOfWork sobre uma AsyncSession dedicada.
@@ -72,6 +77,8 @@ async def __aexit__(
try:
if exc_type is not None:
await self.session.rollback()
+ if isinstance(exc, IntegrityError) and _is_unique_violation(exc):
+ raise DuplicateEntityError("violação de restrição de unicidade") from exc
finally:
await self.session.close()
self._session = None
@@ -81,7 +88,9 @@ async def commit(self) -> None:
await self.session.commit()
except IntegrityError as err:
await self.session.rollback()
- raise DuplicateEntityError("violação de restrição de unicidade") from err
+ if _is_unique_violation(err):
+ raise DuplicateEntityError("violação de restrição de unicidade") from err
+ raise
async def rollback(self) -> None:
await self.session.rollback()
diff --git a/tests/integration/test_repositories.py b/tests/integration/test_repositories.py
index 898fbef..c1701fc 100644
--- a/tests/integration/test_repositories.py
+++ b/tests/integration/test_repositories.py
@@ -17,6 +17,7 @@
from nexusdata.domain.entities import ApiKey, Document, ProcessingJob, Tenant, User
from nexusdata.domain.exceptions import DuplicateEntityError
from nexusdata.domain.value_objects.enums import ApiKeyScope, JobStatus, Role
+from nexusdata.infrastructure.database import mappers
from nexusdata.infrastructure.database.engine import create_session_factory
from nexusdata.infrastructure.database.models import Base
from nexusdata.infrastructure.database.unit_of_work import (
@@ -62,8 +63,10 @@ async def test_tenant_and_user_crud(uow_factory: SqlAlchemyUnitOfWorkFactory) ->
assert got is not None and got.id == tenant.id
+@pytest.mark.parametrize("error_stage", ["flush", "commit"])
async def test_idempotency_unique_constraint(
uow_factory: SqlAlchemyUnitOfWorkFactory,
+ error_stage: str,
) -> None:
tenant = Tenant(name="T", slug=f"t-{uuid4().hex[:8]}")
doc = Document(tenant_id=tenant.id, submitted_by=uuid4())
@@ -78,9 +81,14 @@ async def test_idempotency_unique_constraint(
# Segundo job com a MESMA idempotency_key → viola a unique parcial.
with pytest.raises(DuplicateEntityError):
async with uow_factory() as uow:
- await uow.jobs.add(
- ProcessingJob(tenant_id=tenant.id, document_id=doc.id, idempotency_key="dup")
+ duplicate = ProcessingJob(
+ tenant_id=tenant.id, document_id=doc.id, idempotency_key="dup"
)
+ if error_stage == "flush":
+ await uow.jobs.add(duplicate)
+ else:
+ # Stage the row without a repository flush: commit must translate its own error.
+ uow.session.add(mappers.job_to_model(duplicate))
await uow.commit()
diff --git a/tests/unit/test_unit_of_work.py b/tests/unit/test_unit_of_work.py
new file mode 100644
index 0000000..a0f2a10
--- /dev/null
+++ b/tests/unit/test_unit_of_work.py
@@ -0,0 +1,102 @@
+"""Error translation and session cleanup at both Unit of Work boundaries."""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock
+from uuid import uuid4
+
+import pytest
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from nexusdata.domain.entities import ProcessingJob
+from nexusdata.domain.exceptions import DuplicateEntityError
+from nexusdata.infrastructure.database.unit_of_work import SqlAlchemyUnitOfWork
+
+pytestmark = pytest.mark.unit
+
+
+class PgConstraintError(Exception):
+ def __init__(self, sqlstate: str | None) -> None:
+ super().__init__("synthetic constraint violation")
+ if sqlstate is not None:
+ self.sqlstate = sqlstate
+
+
+@pytest.fixture
+def session() -> AsyncMock:
+ return AsyncMock(spec=AsyncSession)
+
+
+@pytest.fixture
+def uow(session: AsyncMock) -> SqlAlchemyUnitOfWork:
+ return SqlAlchemyUnitOfWork(MagicMock(return_value=session))
+
+
+@pytest.mark.parametrize("error_stage", ["flush", "commit"])
+@pytest.mark.parametrize("sqlstate", ["23505", "23503", "23502", "23514", None])
+async def test_integrity_error_translation_and_cleanup(
+ session: AsyncMock,
+ uow: SqlAlchemyUnitOfWork,
+ error_stage: str,
+ sqlstate: str | None,
+) -> None:
+ error = IntegrityError("INSERT", {}, PgConstraintError(sqlstate))
+ getattr(session, error_stage).side_effect = error
+ expected = DuplicateEntityError if sqlstate == "23505" else IntegrityError
+
+ with pytest.raises(expected) as caught:
+ async with uow:
+ if error_stage == "flush":
+ await uow.jobs.add(ProcessingJob(tenant_id=uuid4(), document_id=uuid4()))
+ await uow.commit()
+
+ if sqlstate == "23505":
+ assert caught.value.__cause__ is error
+ else:
+ assert caught.value is error
+ session.rollback.assert_awaited()
+ session.close.assert_awaited_once()
+ if error_stage == "flush":
+ session.commit.assert_not_awaited()
+ else:
+ session.commit.assert_awaited_once()
+ with pytest.raises(RuntimeError, match="fora do"):
+ _ = uow.session
+
+
+async def test_successful_commit_closes_without_rollback(
+ session: AsyncMock, uow: SqlAlchemyUnitOfWork
+) -> None:
+ async with uow:
+ await uow.commit()
+ session.commit.assert_awaited_once()
+ session.rollback.assert_not_awaited()
+ session.close.assert_awaited_once()
+
+
+async def test_caught_flush_error_is_not_translated_after_context(
+ session: AsyncMock, uow: SqlAlchemyUnitOfWork
+) -> None:
+ error = IntegrityError("INSERT", {}, PgConstraintError("23505"))
+ session.flush.side_effect = error
+ async with uow:
+ with pytest.raises(IntegrityError) as caught:
+ await uow.jobs.add(ProcessingJob(tenant_id=uuid4(), document_id=uuid4()))
+ assert caught.value is error
+ await uow.rollback()
+ session.rollback.assert_awaited_once()
+ session.close.assert_awaited_once()
+ session.commit.assert_not_awaited()
+
+
+async def test_unrelated_error_is_preserved_and_closes(
+ session: AsyncMock, uow: SqlAlchemyUnitOfWork
+) -> None:
+ error = ValueError("synthetic error")
+ with pytest.raises(ValueError) as caught:
+ async with uow:
+ raise error
+ assert caught.value is error
+ session.rollback.assert_awaited_once()
+ session.close.assert_awaited_once()