"""Transactional outbox worker. Fake receipts persist; no messages leave the stack.""" import json import logging import os import threading import time from http.server import BaseHTTPRequestHandler, HTTPServer import psycopg from botocore.exceptions import ClientError from psycopg.types.json import Jsonb from . import mail, observability, unpaid from .adapters import FakeTiny, LocalS3Storage, require_runtime from .core.secrets import load as load_secret_files from .core.db import connect from .printjobs import render_loop from .scanning import ClamAV, scan_loop load_secret_files() require_runtime() # Production without the real Tiny (TINY_ADAPTER missing from the stack): # the sends wait and Sentry is told, instead of the simulator marking real # orders delivered with made-up receipts that had to be queued again by hand. HELD = 'Tiny desligado em produção (TINY_ADAPTER não é tiny): o envio espera' class HeldTiny: def deliver(self, event_key, payload): raise RuntimeError(HELD) def tiny_adapter(adapter=None, environment=None): """The Tiny the outbox delivers to: the real one when configured; in production otherwise none (HeldTiny); elsewhere the simulator.""" adapter = os.environ.get('TINY_ADAPTER') if adapter is None else adapter environment = os.environ.get('APP_ENV', 'local') if environment is None else environment if adapter == 'tiny': from .tiny import TinyOrders from .cnpj import company return TinyOrders(names=company) return HeldTiny() if environment == 'production' else FakeTiny() adapters = {'tiny': tiny_adapter()} def release_held(c): """With the real Tiny back, the sends held meanwhile go at once instead of after their back-off.""" return c.execute('''UPDATE dtf_local.outbox SET available_at=now() WHERE provider='tiny' AND delivered_at IS NULL AND last_error=%s''', (HELD,)).rowcount last_tick = 0.0 last_cleanup = 0.0 last_reconcile = 0.0 last_names = 0.0 names_thread = None last_tiny_keepalive = 0.0 db_down_since = None storage = LocalS3Storage() scan_thread = None render_thread = None def cleanup(): """Delete only expired object bytes; retain order/file metadata and history.""" with connect() as c: rows = c.execute("""SELECT * FROM dtf_local.uploads WHERE purged_at IS NULL AND (expires_at<=now() OR (NOT complete AND created_at 60: cleanup() # Approved quotes unpaid for 24 h expire on their own (front 9). with connect() as c: unpaid.expire(c, os.environ.get('PUBLIC_ORIGIN', 'http://localhost')) last_cleanup = time.monotonic() mail.send_pending(connect) tiny_keepalive() reconcile_payments() resolve_names() except psycopg.OperationalError as exc: if db_down_since is None: db_down_since = time.monotonic() logging.warning('Database unavailable, retrying: %s', exc) else: logging.debug('Database still unavailable, retrying in %s s', delay) time.sleep(delay) delay = min(delay * 2, 15) continue except Exception: logging.exception('Local worker tick failed') else: if db_down_since is not None: logging.info('Database back after %s s', int(time.monotonic()-db_down_since)) db_down_since = None delay = 1 time.sleep(1) class Health(BaseHTTPRequestHandler): def do_GET(self): scanner = False try: scanner = bool(scan_thread and scan_thread.is_alive() and ClamAV().ping()) except Exception: pass renderer = bool(render_thread and render_thread.is_alive()) healthy = time.monotonic()-last_tick < 15 and scanner and renderer self.send_response(200 if self.path == '/health' and healthy else 503) self.end_headers() self.wfile.write(json.dumps({'worker': 'ok' if healthy else 'unavailable', 'scanner': 'ok' if scanner else 'unavailable', 'print_files': 'ok' if renderer else 'unavailable'}).encode()) def log_message(self, *args): pass if __name__ == '__main__': observability.init('worker') if isinstance(adapters['tiny'], HeldTiny): logging.error('Worker started in production without the real Tiny: Tiny sends are held') elif not isinstance(adapters['tiny'], FakeTiny): try: with connect() as c: release_held(c) except Exception: logging.exception('Could not release the Tiny sends held while Tiny was off') scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True) scan_thread.start() render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True) render_thread.start() threading.Thread(target=loop, daemon=True).start() HTTPServer(('0.0.0.0',8002),Health).serve_forever()