Files
dtf-system/app/worker.py
Cauê Faleiros 5db8661a1a
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 7m37s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m25s
fix: the Kanban says the proof machine before a pull, folder downloads cut by the network wait for the next pass, expected refusals stay out of Sentry (DTF-WEB-16..1K, DTF-API-C)
- 19/1F: the board carries the approved proof's machine; the pull and the
  order's machine field keep to it and say why.
- 17/1E: a network drop while a download or an answer arrives counts as
  unreachable/offline, warned first like the others.
- 16: no folder picker (Safari): said in a line.
- 1A, 1J/1K, 1D, 18: guidance and expected refusals (pull to another machine,
  someone already on the machine, e-mail in use, coupon) are not errors.
- 1B: an empty file is refused on the page.
- API-C: the Tiny's rate limit reaches Sentry only if it repeats.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-25 09:46:26 -03:00

208 lines
9.1 KiB
Python

"""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()
adapters = {'tiny': FakeTiny()}
# Not yet confirmed against the client's account; see app/tiny.py.
if os.environ.get('TINY_ADAPTER') == 'tiny':
from .tiny import TinyOrders
from .cnpj import company
adapters['tiny'] = TinyOrders(names=company)
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<now()-interval '1 day'))
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall()
for row in rows:
# A file this worker may not delete (outside the storage policy's
# prefixes, or a storage refusal) must not stop the cleanup of
# every file after it: it is reported and tried again tomorrow.
try:
storage.discard(row['object_key'],row['multipart_id'],row['complete'])
except ClientError as exc:
logging.error('Cleanup could not delete upload %s (%s): %s', row['id'],
row['object_key'].split('/')[0], exc.response.get('Error',{}).get('Code'))
c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '1 day' WHERE id=%s", (row['id'],))
continue
# A generated PNG's pieces for the Kanban's viewer go with it (item 7).
if row['name'].lower().endswith('.png'):
storage.discard_prefix(f"originals/tiles/{row['id']}/")
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()')
c.execute("DELETE FROM dtf_local.account_signups WHERE created_at<now()-interval '1 day'")
c.execute("DELETE FROM dtf_local.email_changes WHERE created_at<now()-interval '1 day'")
c.execute("DELETE FROM dtf_local.password_resets WHERE expires_at<now()-interval '1 day'")
c.execute('DELETE FROM dtf_local.operator_sessions WHERE expires_at<=now()')
c.execute("DELETE FROM dtf_local.login_attempts WHERE started_at<now()-interval '1 day'")
c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'")
def tick():
"""Deliver at most one outbox job; True when there was one, False otherwise."""
global last_tick
processed = False
with connect() as c:
job = c.execute('SELECT * FROM dtf_local.outbox WHERE delivered_at IS NULL AND available_at <= now() ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1').fetchone()
if job:
processed = True
try:
receipt = adapters[job['provider']].deliver(job['event_key'], job['payload'])
c.execute('UPDATE dtf_local.outbox SET delivered_at=now(), receipt=%s, attempts=attempts+1, last_error=NULL WHERE id=%s', (Jsonb(receipt),job['id']))
except Exception as exc:
delay = min(1800, 2**min(job['attempts']+1, 10))
c.execute("UPDATE dtf_local.outbox SET attempts=attempts+1, last_error=%s, available_at=now() + %s * interval '1 second' WHERE id=%s", (str(exc),delay,job['id']))
# Sentry hears of a refused delivery on its first failure and
# every tenth after, not only Integrações (the Tiny refused
# #42 fourteen times unseen, 2026-11-18). One message
# template, so Sentry keeps it as one issue per kind. A
# passing refusal (the Tiny's rate limit) only from the tenth.
attempt = job['attempts'] + 1
if attempt == 1 and not getattr(exc, 'transient', False) or attempt % 10 == 0:
logging.error('Outbox delivery to %s failed (%s, attempt %s): %s',
job['provider'], job['event_key'], attempt, str(exc)[:500])
last_tick = time.monotonic()
return processed
def drain(limit=50):
"""Deliver up to `limit` outbox jobs in one pass, so a backlog leaves at
once instead of one job per second (Critical Corrections item 9)."""
for _ in range(limit):
if not tick():
return
def tiny_keepalive():
"""Keep a connected Tiny authorised even while no orders are sent.
The refresh token expires unless it is used; access_token() refreshes (and
rotates) only when the access token is about to expire, so asking every few
minutes renews the connection roughly once per access-token lifetime.
"""
global last_tiny_keepalive
if time.monotonic()-last_tiny_keepalive < 600:
return
last_tiny_keepalive = time.monotonic()
from . import tiny
if not tiny.configured():
return
try:
tiny.TinyAuth().access_token()
except tiny.TinyNotConnected:
pass
except Exception:
logging.exception('Tiny connection refresh failed')
def reconcile_payments():
"""Every minute: the payments of open quotes, asked of the provider, so an
approval becomes the order even when its notification never arrives."""
global last_reconcile
if time.monotonic()-last_reconcile < 60:
return
last_reconcile = time.monotonic()
from . import payments
from .runtime import payment
payments.reconcile(connect, payment)
def resolve_names():
"""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
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, db_down_since
delay = 1
while True:
try:
drain()
if time.monotonic()-last_cleanup > 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')
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()