From 8997e22f5e6cd47fe04231da8c7624fe1ccb692f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 5 Oct 2026 12:31:25 -0300 Subject: [PATCH] fix: CNPJ name lookups run on their own thread, so a slow registry never delays orders The worker looked names up inside its main loop, which also sends orders to Tiny and asks Mercado Pago about payments. Without internet, or with the registry slow, five lookups could hold that loop for most of a minute. They now run on a thread of their own, one batch at a time. Co-Authored-By: Claude Opus 5.5 --- app/cnpj.py | 2 +- app/worker.py | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/app/cnpj.py b/app/cnpj.py index cfff324..b72d3d9 100644 --- a/app/cnpj.py +++ b/app/cnpj.py @@ -21,7 +21,7 @@ def digits(value): def fetch(cnpj, transport=None): """The registry's names for one CNPJ. An unknown CNPJ has none, and is not asked again.""" - with httpx.Client(timeout=10, transport=transport) as http: + with httpx.Client(timeout=8, transport=transport) as http: response = http.get(API + cnpj, headers={'Accept': 'application/json', 'User-Agent': 'dtf-sistema'}) if response.status_code == 404: return {'legal_name': None, 'trade_name': None} diff --git a/app/worker.py b/app/worker.py index 0c024e6..28d8192 100644 --- a/app/worker.py +++ b/app/worker.py @@ -24,6 +24,7 @@ last_tick = 0.0 last_cleanup = 0.0 last_reconcile = 0.0 last_names = 0.0 +names_thread = None last_tiny_keepalive = 0.0 storage = LocalS3Storage() scan_thread = None @@ -90,13 +91,21 @@ def reconcile_payments(): payments.reconcile(connect, payment) def resolve_names(): - """Every minute: the company names of a few new customers' CNPJs.""" - global last_names - if time.monotonic()-last_names < 60: + """Every minute: the company names of a few new customers' CNPJs, on a + thread of their own, so a slow registry never holds up orders.""" + global last_names, names_thread + if time.monotonic()-last_names < 60 or (names_thread and names_thread.is_alive()): return last_names = time.monotonic() from . import cnpj - cnpj.resolve(connect) + + def run(): + try: + cnpj.resolve(connect) + except Exception: + logging.exception('CNPJ name lookup failed') + names_thread = threading.Thread(target=run, daemon=True) + names_thread.start() def loop(): global last_cleanup