Skip to content

Commit 07e857c

Browse files
committed
feat: adiciona Dockerfile, docker-compose, /health e /metrics
1 parent d11d2b8 commit 07e857c

4 files changed

Lines changed: 83 additions & 7 deletions

File tree

Dockerfile

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
FROM python:3.12-slim
2+
3+
LABEL maintainer="Eric Jones Silva <ericjonsilva@outlook.com>"
4+
LABEL description="Bot Report API — API REST para relatórios de execução de bots"
5+
6+
WORKDIR /app
7+
8+
# Instalar dependências primeiro (aproveita cache do Docker)
9+
COPY pyproject.toml ./
10+
RUN pip install --no-cache-dir -e "."
11+
12+
# Copiar código
13+
COPY bot_report_api/ ./bot_report_api/
14+
15+
EXPOSE 8000
16+
17+
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
18+
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
19+
20+
CMD ["uvicorn", "bot_report_api.main:app", "--host", "0.0.0.0", "--port", "8000"]

bot_report_api/main.py

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,16 @@
44
Desenvolvida com FastAPI e Pydantic v2.
55
"""
66

7-
from fastapi import FastAPI
7+
import time
88
from contextlib import asynccontextmanager
99

10+
from fastapi import FastAPI
11+
1012
from bot_report_api.routers import bots, execucoes, relatorios
11-
from bot_report_api.database import inicializar_db
13+
from bot_report_api.database import inicializar_db, listar_bots, listar_execucoes
14+
from bot_report_api.schemas import StatusExecucao
15+
16+
_startup_time = time.time()
1217

1318

1419
@asynccontextmanager
@@ -22,7 +27,8 @@ async def lifespan(app: FastAPI):
2227
title="Bot Report API",
2328
description=(
2429
"API REST para cadastro de bots, registro de execuções e "
25-
"consulta de relatórios de automação."
30+
"consulta de relatórios de automação.\n\n"
31+
"**Documentação:** `/docs` | **OpenAPI JSON:** `/openapi.json`"
2632
),
2733
version="0.1.0",
2834
lifespan=lifespan,
@@ -33,7 +39,32 @@ async def lifespan(app: FastAPI):
3339
app.include_router(relatorios.router, prefix="/relatorios", tags=["Relatórios"])
3440

3541

36-
@app.get("/", tags=["Health"])
42+
@app.get("/health", tags=["Observabilidade"], summary="Health check")
3743
def health_check():
38-
"""Verifica se a API está no ar."""
39-
return {"status": "ok", "versao": "0.1.0"}
44+
"""Verifica se a API está operacional — retorna status, versão e uptime."""
45+
return {
46+
"status": "ok",
47+
"versao": "0.1.0",
48+
"uptime_segundos": round(time.time() - _startup_time, 1),
49+
}
50+
51+
52+
@app.get("/metrics", tags=["Observabilidade"], summary="Métricas da aplicação")
53+
def metricas():
54+
"""Retorna métricas operacionais em tempo real para monitoramento."""
55+
todas_execucoes = listar_execucoes()
56+
return {
57+
"total_bots": len(listar_bots()),
58+
"total_execucoes": len(todas_execucoes),
59+
"execucoes_por_status": {
60+
status.value: sum(1 for e in todas_execucoes if e.status == status)
61+
for status in StatusExecucao
62+
},
63+
"uptime_segundos": round(time.time() - _startup_time, 1),
64+
"versao": "0.1.0",
65+
}
66+
67+
68+
@app.get("/", include_in_schema=False)
69+
def root():
70+
return {"mensagem": "Bot Report API — acesse /docs para a documentação."}

docker-compose.yml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
services:
2+
api:
3+
build: .
4+
container_name: bot-report-api
5+
ports:
6+
- "8000:8000"
7+
environment:
8+
- APP_ENV=development
9+
restart: unless-stopped
10+
healthcheck:
11+
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
12+
interval: 30s
13+
timeout: 10s
14+
retries: 3
15+
start_period: 10s

tests/test_api.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,19 @@ def client():
2020
# ── Health ─────────────────────────────────────────────────────────────────
2121

2222
def test_health_check(client):
23-
response = client.get("/")
23+
response = client.get("/health")
2424
assert response.status_code == 200
2525
assert response.json()["status"] == "ok"
26+
assert "uptime_segundos" in response.json()
27+
28+
29+
def test_metrics(client):
30+
response = client.get("/metrics")
31+
assert response.status_code == 200
32+
dados = response.json()
33+
assert "total_bots" in dados
34+
assert "total_execucoes" in dados
35+
assert "execucoes_por_status" in dados
2636

2737

2838
# ── Bots ───────────────────────────────────────────────────────────────────

0 commit comments

Comments
 (0)