Corrige pool esgotado e erros do Holmes sem mensagem

- Rota de notas não segura conexão do banco enquanto espera o Holmes
- Contador de chamadas usa conexão própria e curta quando não recebe uma
- Timeout do Holmes sobe de 5s (padrão do httpx) para 30s
- Erros passam a registrar o tipo (timeouts vinham com mensagem vazia) e traceback
- Log também gravado em api.log, inclusive os erros 500 do uvicorn

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ricardo 2026-10-08 14:18:46 -03:00
parent 36f042cbae
commit 006687f250
4 changed files with 115 additions and 76 deletions

View file

@ -10,6 +10,11 @@ from sqlalchemy.pool import PoolProxiedConnection
from app.core.configs import settings
from app.utils.api_tracker import registrar_contador
logger = logging.getLogger("api_podium")
# O padrão do httpx é 5s, pouco pro Holmes em horário de pico
HOLMES_TIMEOUT = httpx.Timeout(30.0, connect=10.0)
_TOKEN_FILE = os.path.join(tempfile.gettempdir(), "holmes_token_cache.json")
async def get_header() -> tuple[dict, str]:
@ -22,7 +27,7 @@ async def _holmes_request(
api_nome: str = "holmes"
for tentativa in range(2):
header, api_nome = await get_header()
async with httpx.AsyncClient() as client:
async with httpx.AsyncClient(timeout=HOLMES_TIMEOUT) as client:
response = await getattr(client, method)(url, headers=header, **kwargs)
return response, api_nome
raise RuntimeError("Holmes: falha de autenticação após retry")
@ -46,12 +51,12 @@ async def get_holmes_process(id_processo: str, conn: PoolProxiedConnection):
return response.json()
except httpx.HTTPStatusError as e:
status = e.response.status_code
erro = str(e)
logging.error(f"Erro na API Holmes (ID {id_processo}): {e}")
erro = f"{type(e).__name__}: {e}"
logger.error(f"Erro na API Holmes (ID {id_processo}): {e}")
return None
except Exception as e:
erro = str(e)
logging.error(f"Erro inesperado ao consultar Holmes: {e}")
erro = f"{type(e).__name__}: {e}"
logger.exception(f"Erro inesperado ao consultar Holmes: {type(e).__name__}: {e}")
return None
finally:
duracao = (time.perf_counter() - inicio) * 1000
@ -86,12 +91,12 @@ async def get_holmes_process_details(id_processo: str, conn: PoolProxiedConnecti
return response.json()
except httpx.HTTPStatusError as e:
status = e.response.status_code
erro = str(e)
logging.error(f"Erro na API Holmes details (ID {id_processo}): {e}")
erro = f"{type(e).__name__}: {e}"
logger.error(f"Erro na API Holmes details (ID {id_processo}): {e}")
return None
except Exception as e:
erro = str(e)
logging.error(f"Erro inesperado ao consultar Holmes details: {e}")
erro = f"{type(e).__name__}: {e}"
logger.exception(f"Erro inesperado ao consultar Holmes details: {type(e).__name__}: {e}")
return None
finally:
duracao = (time.perf_counter() - inicio) * 1000
@ -107,7 +112,7 @@ async def get_holmes_process_details(id_processo: str, conn: PoolProxiedConnecti
)
async def get_holmes_history(id_processo: str, conn: PoolProxiedConnection):
async def get_holmes_history(id_processo: str, conn: PoolProxiedConnection | None = None):
"""
Busca o historico no holmes (importante para pegar o id da ultima task, para avançar futuramente)
Args:
@ -134,12 +139,12 @@ async def get_holmes_history(id_processo: str, conn: PoolProxiedConnection):
return response.json()
except httpx.HTTPStatusError as e:
status = e.response.status_code
erro = str(e)
logging.error(f"Erro na API Holmes (ID {id_processo}): {e}")
erro = f"{type(e).__name__}: {e}"
logger.error(f"Erro na API Holmes (ID {id_processo}): {e}")
return None
except Exception as e:
erro = str(e)
logging.error(f"Erro inesperado ao consultar Holmes: {e}")
erro = f"{type(e).__name__}: {e}"
logger.exception(f"Erro inesperado ao consultar Holmes: {type(e).__name__}: {e}")
return None
finally:
duracao = (time.perf_counter() - inicio) * 1000
@ -171,12 +176,12 @@ async def get_holmes_rateio(id_processo: str, conn: PoolProxiedConnection):
return response.json()
except httpx.HTTPStatusError as e:
status = e.response.status_code
erro = str(e)
logging.error(f"Erro na API Holmes (ID {id_processo}): {e}")
erro = f"{type(e).__name__}: {e}"
logger.error(f"Erro na API Holmes (ID {id_processo}): {e}")
return None
except Exception as e:
erro = str(e)
logging.error(f"Erro inesperado ao consultar Holmes: {e}")
erro = f"{type(e).__name__}: {e}"
logger.exception(f"Erro inesperado ao consultar Holmes: {type(e).__name__}: {e}")
return None
finally:
duracao = (time.perf_counter() - inicio) * 1000
@ -207,12 +212,12 @@ async def get_holmes_dados_tabela(id_processo: str, id_tabela: str, conn: PoolPr
return response.json()
except httpx.HTTPStatusError as e:
status = e.response.status_code
erro = str(e)
logging.error(f"Erro na API Holmes (ID {id_processo}): {e}")
erro = f"{type(e).__name__}: {e}"
logger.error(f"Erro na API Holmes (ID {id_processo}): {e}")
return None
except Exception as e:
erro = str(e)
logging.error(f"Erro inesperado ao consultar Holmes: {e}")
erro = f"{type(e).__name__}: {e}"
logger.exception(f"Erro inesperado ao consultar Holmes: {type(e).__name__}: {e}")
return None
finally:
duracao = (time.perf_counter() - inicio) * 1000
@ -340,12 +345,12 @@ async def buscar_processo(
return {"status": True, "dados": {**dados, "docs": docs, "total": len(docs)}}
except httpx.HTTPStatusError as e:
status = e.response.status_code
erro = str(e)
logging.error(f"Erro na API Holmes (ID {chave}): {e}")
erro = f"{type(e).__name__}: {e}"
logger.error(f"Erro na API Holmes (ID {chave}): {e}")
return {"status": False, "error": e}
except Exception as e:
erro = str(e)
logging.error(f"Erro inesperado ao consultar Holmes: {e}")
erro = f"{type(e).__name__}: {e}"
logger.exception(f"Erro inesperado ao consultar Holmes: {type(e).__name__}: {e}")
return {"status": False, "error": e}
finally:
duracao = (time.perf_counter() - inicio) * 1000
@ -421,12 +426,12 @@ async def buscar_processo_por_chaves(
return {"status": True, "dados": {**dados, "docs": docs, "total": len(docs)}}
except httpx.HTTPStatusError as e:
status = e.response.status_code
erro = str(e)
logging.error(f"Erro na API Holmes (combinacoes {combinacoes}): {e}")
erro = f"{type(e).__name__}: {e}"
logger.error(f"Erro na API Holmes (combinacoes {combinacoes}): {e}")
return {"status": False, "error": e}
except Exception as e:
erro = str(e)
logging.error(f"Erro inesperado ao consultar Holmes: {e}")
erro = f"{type(e).__name__}: {e}"
logger.exception(f"Erro inesperado ao consultar Holmes: {type(e).__name__}: {e}")
return {"status": False, "error": e}
finally:
duracao = (time.perf_counter() - inicio) * 1000
@ -451,7 +456,7 @@ async def action(payload: dict, id_task: str, id_processo: str, conn: PoolProxie
api_nome = "holmes"
try:
async with httpx.AsyncClient() as client:
async with httpx.AsyncClient(timeout=HOLMES_TIMEOUT) as client:
response = await client.post(
url, headers={"api_token": settings.holmes.token}, json=payload
)
@ -461,12 +466,12 @@ async def action(payload: dict, id_task: str, id_processo: str, conn: PoolProxie
return True, response.json()
except httpx.HTTPStatusError as e:
status = e.response.status_code
erro = str(e)
logging.error(f"Erro na API Holmes (ID {id_processo}): {e}")
erro = f"{type(e).__name__}: {e}"
logger.error(f"Erro na API Holmes (ID {id_processo}): {e}")
return False, e
except Exception as e:
erro = str(e)
logging.error(f"Erro inesperado ao consultar Holmes: {e}")
erro = f"{type(e).__name__}: {e}"
logger.exception(f"Erro inesperado ao consultar Holmes: {type(e).__name__}: {e}")
return False, e
finally:
duracao = (time.perf_counter() - inicio) * 1000
@ -502,12 +507,12 @@ async def cria_processo(
return True, response.json()
except httpx.HTTPStatusError as e:
status = e.response.status_code
erro = str(e)
logging.error(f"Erro na API Holmes - Criar Processo ({payload}): {e}")
erro = f"{type(e).__name__}: {e}"
logger.error(f"Erro na API Holmes - Criar Processo ({payload}): {e}")
return False, str(e)
except Exception as e:
erro = str(e)
logging.error(f"Erro inesperado ao criar processo no Holmes: {e}")
erro = f"{type(e).__name__}: {e}"
logger.exception(f"Erro inesperado ao criar processo no Holmes: {type(e).__name__}: {e}")
return False, str(e)
finally:
duracao = (time.perf_counter() - inicio) * 1000
@ -544,7 +549,7 @@ async def enviar_documento(
try:
files = {"file": (nome_arquivo, arquivo, "application/pdf")}
async with httpx.AsyncClient() as client:
async with httpx.AsyncClient(timeout=HOLMES_TIMEOUT) as client:
response = await client.post(
url, headers={"api_token": settings.holmes.token}, files=files
)
@ -554,12 +559,12 @@ async def enviar_documento(
return True, {"task_id": task_id}
except httpx.HTTPStatusError as e:
status = e.response.status_code
erro = str(e)
logging.error(f"Erro ao enviar documento Holmes (ID {id_processo}): {e}")
erro = f"{type(e).__name__}: {e}"
logger.error(f"Erro ao enviar documento Holmes (ID {id_processo}): {e}")
return False, str(e)
except Exception as e:
erro = str(e)
logging.error(f"Erro inesperado ao enviar documento Holmes: {e}")
erro = f"{type(e).__name__}: {e}"
logger.exception(f"Erro inesperado ao enviar documento Holmes: {type(e).__name__}: {e}")
return False, str(e)
finally:
duracao = (time.perf_counter() - inicio) * 1000
@ -612,12 +617,12 @@ async def cancela_processo(
}
except httpx.HTTPStatusError as e:
status = e.response.status_code
erro = str(e)
logging.error(f"Erro ao cancelar processo Holmes (ID {id_processo}): {e}")
erro = f"{type(e).__name__}: {e}"
logger.error(f"Erro ao cancelar processo Holmes (ID {id_processo}): {e}")
return False, str(e)
except Exception as e:
erro = str(e)
logging.error(f"Erro inesperado ao cancelar processo Holmes: {e}")
erro = f"{type(e).__name__}: {e}"
logger.exception(f"Erro inesperado ao cancelar processo Holmes: {type(e).__name__}: {e}")
return False, str(e)
finally:
duracao = (time.perf_counter() - inicio) * 1000