Files
dtf-system/app/printjobs.py
Cauê Faleiros ba85168c09
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 7m58s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m21s
fix: parts of 10 m are the code's default too, not only the stack's
A stack without PRINT_PART_CM (the local one and CI) cut films in 15 m parts,
4,8 GB decoded, which FlexiPRINT refuses (Marcus, 2026-11-18). The comments
that still said 15 m now say a part.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:03:36 -03:00

450 lines
23 KiB
Python

"""Generating print files in the background, one order item at a time.
A paid order queues one job per item. The worker claims a job, commits the
claim, and renders outside any transaction, so a long render never holds a row
lock or a database connection. A claim past its deadline (the render limit
plus a margin; CLAIM_TIMEOUT for a claim made before deadlines existed) is
assumed to belong to a worker that died and is taken again.
The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a
film longer than a part (10 m): ordinary upload rows owned by an identity derived from the
order, already marked clean, since their only inputs are artwork that passed
the malware scan and the bytes are written here. dtf_local.print_parts lists
them in order. The operator still decides whether they become the final
file; generation never approves anything.
Sheets of several GB are the normal order: a PNG or a PDF is read band by
band, so its size does not matter. Any other file above LARGE_SOURCE_BYTES
is prepared by hand from the original.
"""
import io
import logging
import multiprocessing
import os
import shutil
import tempfile
import time
from queue import Empty
from datetime import timedelta
from decimal import Decimal
from zoneinfo import ZoneInfo
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
import psycopg
from psycopg.types.json import Jsonb
from PIL import Image
from .cart_pricing import needs_designer
from .core.auth import audit
from .core.db import connect
from .printfile import Unsupported
from .printpng import part_cuts, render
from . import proof
from .proof import PROOF_SHEET_CM
from .tiny import purchase_order
LOCAL = ZoneInfo('America/Sao_Paulo')
# A 15 m part takes about 7 min to write on a fast core; a long film, several
# parts. The limit is per part: order #20's 23.6 m film (2026-11-12) ran past a
# single 15 min limit for the whole film.
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '1200'))
CLAIM_MARGIN = timedelta(minutes=3)
CLAIM_TIMEOUT = timedelta(seconds=RENDER_SECONDS) + CLAIM_MARGIN
# A claim is stale once past its deadline.
STALE = 'COALESCE({p}.deadline_at, {p}.claimed_at + %s) < now()'
MAX_ATTEMPTS = 3
LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024)))
# Read band by band, whatever their size.
STREAMED = ('.png', '.pdf')
def render_seconds(item):
"""The render limit of one item: RENDER_SECONDS for each part of its
film, and one more for a film in parts: a cut moved back to a clear band
(#136) can leave one part more than the layout alone counts."""
production = item.get('production') or {}
try:
parts = len(part_cuts(production)) - 1 if production.get('placements') else 1
except (KeyError, TypeError, ValueError, ArithmeticError):
parts = 1
parts = max(1, parts)
return RENDER_SECONDS * (parts + 1 if parts > 1 else 1)
def generated_identity(order_id):
return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}')
def proof_part(heights_cm, original_height_cm, fraction):
"""Which part of a split final holds the finest stroke, and where inside it.
`heights_cm` are the parts' heights in order, `fraction` the stroke's
position on the original film (0 at the top, 1 at the bottom). A single
part returns the same fraction, as before.
"""
heights = [float(height) for height in heights_cm]
if not heights:
return 0, 0.0
position = min(1.0, max(0.0, float(fraction or 0))) * float(original_height_cm)
start = 0.0
for index, height in enumerate(heights):
end = start + height
if position <= end or index == len(heights) - 1:
inside = (position - start) / height if height > 0 else 0.0
return index, min(1.0, max(0.0, inside))
start = end
return len(heights) - 1, 1.0
def png_height_cm(storage, row):
"""A PNG's height in cm at 300 DPI, from its header alone (a Range read)."""
head = storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'],
Range='bytes=0-65535')['Body'].read()
with Image.open(io.BytesIO(head)) as image:
height_px = image.size[1]
return float(Decimal(height_px) * Decimal('2.54') / Decimal(300))
def queue(c, order_id, items, only_missing=False):
"""Queue (or re-queue) generation for every item of an order."""
for index in range(items):
if only_missing:
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}'
WHERE dtf_local.print_files.status IN ('failed','manual') OR
(dtf_local.print_files.status='rendering' AND '''
+ STALE.format(p='dtf_local.print_files') + ')',
(uuid4(), order_id, index, CLAIM_TIMEOUT))
else:
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
ON CONFLICT(order_id,item_index) DO NOTHING''', (uuid4(), order_id, index))
def requeue(c, order_id, items):
"""Generate every item again, a ready one too: after the part size
changed (PART_CM; order #36, 2026-11-17). One rendering now is left alone."""
for index in range(items):
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}',
generation=dtf_local.print_files.generation+1
WHERE dtf_local.print_files.status<>'rendering' ''', (uuid4(), order_id, index))
def claim(c):
return c.execute('''SELECT p.*, o.snapshot, o.number, o.parent_id, o.created_at AS ordered_at FROM dtf_local.print_files p
JOIN dtf_local.orders o ON o.id=p.order_id
WHERE p.status='pending' OR (p.status='rendering' AND ''' + STALE.format(p='p') + ''')
ORDER BY CASE WHEN o.parent_id IS NOT NULL THEN 0 ELSE 1 END, p.created_at
FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
def _render_child(result_queue, job, item, uploads):
"""Render in a killable process: a stuck image decoder cannot hold a card forever."""
from .adapters import LocalS3Storage
try:
result_queue.put(('ready', produce(LocalS3Storage(), job, item, uploads)))
except Unsupported as reason:
result_queue.put(('manual', str(reason)))
except BaseException as exc:
logging.exception('Print file generation failed')
result_queue.put(('error', type(exc).__name__))
def render_with_timeout(job, item, uploads, seconds=RENDER_SECONDS):
ctx = multiprocessing.get_context('spawn')
result_queue = ctx.Queue()
process = ctx.Process(target=_render_child, args=(result_queue, job, item, uploads))
process.start()
try:
process.join(seconds)
if process.is_alive():
process.terminate()
process.join(5)
if process.is_alive():
process.kill()
process.join()
return 'timeout', None
try:
return result_queue.get(timeout=5)
except Empty:
return 'error', f'processo encerrou com código {process.exitcode}'
finally:
result_queue.close()
result_queue.join_thread()
def render_one(storage):
with connect() as c:
job = claim(c)
if not job:
return False
token = uuid4()
item = job['snapshot']['items'][job['item_index']]
seconds = render_seconds(item)
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
deadline_at=now()+%s, attempts=attempts+1,claim_token=%s WHERE id=%s''',
(timedelta(seconds=seconds) + CLAIM_MARGIN, token, job['id']))
job['claim_token'] = token
source_ids = [UUID(u) for u in item['uploads']]
# A format such as CDR needs a human to prepare the full-size final on
# the parent. The child still generates its own 15 cm proof from that PNG,
# or from the part of it that holds the finest stroke when the film was
# cut into parts (item 13).
if job['parent_id']:
finals = c.execute('''SELECT u.id,u.object_key FROM dtf_local.order_files f
JOIN dtf_local.uploads u ON u.id=f.upload_id
LEFT JOIN dtf_local.print_parts p ON p.order_id=f.order_id
AND p.item_index=f.item_index AND p.upload_id=f.upload_id
WHERE f.order_id=%s AND f.item_index=%s AND f.kind='final' AND f.active
AND u.purged_at IS NULL AND u.expires_at>now()
ORDER BY p.part NULLS LAST, f.created_at''',
(job['parent_id'], item['proof_parent_item_index'])).fetchall()
if finals:
source = finals[0]
if len(finals) > 1:
heights = [png_height_cm(storage, row) for row in finals]
index, fraction = proof_part(heights, item['production']['height_cm'],
item.get('proof_y_fraction'))
source = finals[index]
job['proof_fraction'] = fraction
source_ids = [source['id']]
item = {**item, 'uploads': [str(source['id'])]}
job['proof_fallback'] = True
elif needs_designer(job['snapshot']):
job['wait_for_treatment'] = True
# The small pictures the Site sent of each file: where a proof finds
# the colours to sample (app/printpng.py film_scan).
if job['snapshot'].get('proof_of') and not job.get('proof_fallback'):
job['pictures'] = {str(r['upload_id']): bytes(r['data']) for r in c.execute(
'SELECT upload_id,data FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)',
(source_ids,)).fetchall()}
uploads = c.execute('''SELECT id,name,size,object_key,scan_state,purged_at,expires_at,
(expires_at<=now()) AS expired FROM dtf_local.uploads WHERE id=ANY(%s)''',
(source_ids,)).fetchall()
# Every generated file shares its order's artwork retention deadline.
expiry = c.execute('SELECT min(created_at)+interval \'30 days\' AS e FROM dtf_local.uploads WHERE id=ANY(%s)',
(source_ids,)).fetchone()['e']
by_id = {str(row['id']): row for row in uploads}
if job.get('wait_for_treatment'):
finish(job, 'manual', {'reason': 'Ajuste Fino pago: prepare e aprove o PNG completo no pedido pai para gerar a prova.'})
return True
if any(row['size'] > LARGE_SOURCE_BYTES and not row['name'].lower().endswith(STREAMED) for row in uploads):
finish(job, 'manual', {'reason': f'arquivo acima de {LARGE_SOURCE_BYTES // 1048576} MB que não é PNG nem PDF: '
'monte a folha a partir do original'})
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
return True
outcome, result = render_with_timeout(job, item, by_id, seconds)
if outcome == 'manual':
finish(job, 'manual', {'reason': result})
audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
return True
if outcome == 'timeout':
finish(job, 'failed', {'reason': f'Tempo limite de {seconds // 60} min excedido. Gere de novo.'})
audit('print_file_timeout', order=str(job['order_id']), item=job['item_index'])
# The card says so too, but Sentry (and the Vigia) hear of it first.
logging.error('Print file generation timed out after %s min: order #%s item %s',
seconds // 60, job['number'], job['item_index'] + 1)
return True
if outcome == 'error':
final = job['attempts'] + 1 >= MAX_ATTEMPTS
if final:
logging.error('Print file generation failed: order #%s item %s: %s',
job['number'], job['item_index'] + 1, result)
finish(job, 'failed' if final else 'pending', {'error': result,
'reason': 'A geração falhou. Gere de novo.' if final else ''})
return True
scratch, parts, detail = result
stored = []
try:
for path, name in parts:
uid = uuid4()
key = f'originals/{uid}'
storage.store(key, path, 'image/png')
stored.append((uid, name, os.path.getsize(path), key))
store_tiles(storage, os.path.join(scratch, 'tiles', name), uid)
except Exception as exc:
# Storage failing is an attempt like any other, not a claim held for an
# hour. The storage client already waited out a short outage; Sentry
# hears of one that outlasts every attempt, once, not of each retry
# (Sentry DTF-API-A).
final = job['attempts'] + 1 >= MAX_ATTEMPTS
if final:
logging.exception('Storing the print file failed: order #%s item %s', job['number'], job['item_index'] + 1)
else:
logging.warning('Storing the print file failed, retrying: order #%s item %s: %s',
job['number'], job['item_index'] + 1, exc)
finish(job, 'failed' if final else 'pending', {'error': type(exc).__name__})
return True
finally:
shutil.rmtree(scratch, ignore_errors=True)
for part, (uid, _, size, _) in zip(detail['parts'], stored):
part.update(upload_id=str(uid), size=size)
with connect() as c:
current = c.execute('''SELECT 1 FROM dtf_local.print_files WHERE id=%s AND claim_token=%s
AND status='rendering' FOR UPDATE''', (job['id'], job['claim_token'])).fetchone()
if not current:
return True
for uid, name, size, key in stored:
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state,scan_reason,scanned_at)
VALUES(%s,%s,%s,%s,%s,'',true,%s,'clean','generated from scanned artwork',now())''',
(uid, generated_identity(job['order_id']), name, size, key, expiry))
# claimed_at stays: the Prumo report measures generation from the claim.
c.execute('''UPDATE dtf_local.print_files SET status='ready', upload_id=%s, detail=%s,
finished_at=now(),claim_token=NULL WHERE id=%s''', (stored[0][0], Jsonb(detail), job['id']))
c.execute('DELETE FROM dtf_local.print_parts WHERE order_id=%s AND item_index=%s',
(job['order_id'], job['item_index']))
for number, (uid, _, _, _) in enumerate(stored, 1):
c.execute('INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id) VALUES(%s,%s,%s,%s)',
(job['order_id'], job['item_index'], number, uid))
if job['snapshot'].get('proof_of'):
c.execute('''UPDATE dtf_local.order_files SET active=false
WHERE order_id=%s AND item_index=%s AND kind='final' ''',
(job['order_id'], job['item_index']))
c.execute('''INSERT INTO dtf_local.order_files
(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,%s,'final','Prova gerada automaticamente pelo Prumo','Prumo')''',
(uuid4(), job['order_id'], stored[0][0], job['item_index']))
elif not job['parent_id']:
# A Prova OK given while this file was still being generated.
order = c.execute('SELECT * FROM dtf_local.orders WHERE id=%s FOR UPDATE', (job['order_id'],)).fetchone()
if order['proof_ok_at']:
proof.approve_parent(c, order, 'Prumo')
audit('print_file_ready', order=str(job['order_id']), item=job['item_index'], parts=len(stored))
return True
def store_tiles(storage, folder, upload_id):
"""A part's pieces for the Kanban's viewer (item 7), beside the files the
storage policy lets the service write: originals/tiles/<upload>/<level>/<index>.png."""
if not os.path.isdir(folder):
return
for level in sorted(os.listdir(folder)):
for strip in sorted(os.listdir(os.path.join(folder, level))):
storage.store(f'originals/tiles/{upload_id}/{level}/{strip}', os.path.join(folder, level, strip), 'image/png')
def file_prefix(number, item_index, generation=1):
"""How an order's files are named: DTF-23-item-1, the code the Kanban
copies, the footer prints and Tiny keeps (Dropstar, 2026-10-23); after
"Gerar de novo", DTF-23-v2-item-1, so no one takes the new files for the
old ones (Marcus, 2026-11-27, #130)."""
version = f'-v{generation}' if generation and generation > 1 else ''
return f'DTF-{number}{version}-item-{item_index + 1}'
def footer(job, item):
"""The print file's footer line: DROPSTAR · Pedido DTF-123 · Item 1/2 ·
21/10/2026 · 0,90 m, and · ESPELHADO when the artwork is mirrored. The
order is named by its Kanban number, which Tiny keeps; the length is the
one billed."""
count = len(job['snapshot']['items'])
day = job['ordered_at'].astimezone(LOCAL).strftime('%d/%m/%Y')
billed = f"{Decimal(str(item['billed_metres'])):.2f}".replace('.', ',')
proof_of = job['snapshot'].get('proof_of')
if proof_of:
return ' · '.join(['DROPSTAR', f'PROVA do #{proof_of}',
f'Classe {item.get("stroke_class") or "C3"}', day])
fields = ['DROPSTAR', f'Pedido {purchase_order(job["number"])}',
f'Item {job["item_index"] + 1}/{count}', day, f'{billed} m']
# A mirrored artwork (UV only) is named on the sheet, for the room to see
# before printing (Dropstar, 2026-10-23).
if any(source.get('mirrored') for source in item['production']['sources']):
fields.append('ESPELHADO')
return ' · '.join(fields)
def pictures_by_source(item, pictures):
"""The small pictures by source index, as the proof's scan reads them."""
if not pictures:
return None
sources = item['production']['sources']
found = {i: pictures[str(s['upload_id'])] for i, s in enumerate(sources) if str(s['upload_id']) in pictures}
return found or None
def produce(storage, job, item, uploads):
"""Fetch the item's artwork and render it. Returns (folder, [(png path,
name)], evidence); the caller removes the folder."""
if not (item.get('production') or {}).get('placements'):
raise Unsupported('o item não tem montagem: prepare o arquivo à mão')
for upload_id in item['uploads']:
row = uploads.get(upload_id)
if not row or row['scan_state'] != 'clean':
raise Unsupported('um arquivo original está ausente ou não foi liberado pelo antivírus')
if row['purged_at'] or row['expired']:
raise Unsupported('um arquivo original passou do prazo de guarda')
output = tempfile.mkdtemp(prefix='print-')
try:
with tempfile.TemporaryDirectory(prefix='print-') as scratch:
files = {}
for index, upload_id in enumerate(item['uploads']):
local = os.path.join(scratch, f'source-{index}')
storage.fetch(uploads[upload_id]['object_key'], local)
files[index] = (local, uploads[upload_id]['name'])
if job.get('proof_fallback'):
with Image.open(files[0][0]) as final:
width_px, height_px = final.size
width_cm = float(Decimal(width_px) * Decimal('2.54') / Decimal(300))
height_cm = float(Decimal(height_px) * Decimal('2.54') / Decimal(300))
if job.get('proof_fraction') is not None:
# Already relative to the chosen part (proof_part).
fraction = float(job['proof_fraction'])
else:
original_height = float(item['production']['height_cm'])
fraction = min(1, float(item.get('proof_y_fraction') or 0) * original_height / height_cm)
source = {'kind': 'sheet', 'width_cm': width_cm, 'length_cm': height_cm,
'copies': 1, 'rotation_degrees': 0, 'mirrored': False, 'measurement': 'file'}
item = {**item, 'proof_y_fraction': fraction,
'production': {'version': 3, 'film_width_cm': width_cm,
'height_cm': height_cm, 'sources': [source],
'placements': [{'source_index': 0, 'copy_index': 0,
'x_cm': 0, 'y_cm': 0, 'width_cm': width_cm,
'length_cm': height_cm, 'rotation_degrees': 0,
'mirrored': False}]}}
proof_of = job['snapshot'].get('proof_of')
# The child owns its final file; the class names its proof.
prefix = (f'DTF-{job["number"]}-prova-{item.get("stroke_class") or "C3"}' if proof_of
else file_prefix(job['number'], job['item_index'], job.get('generation')))
parts, detail = render(item, files, output, prefix, footer=footer(job, item), tiles=True,
limit_cm=PROOF_SHEET_CM if proof_of else None,
proof_fraction=item.get('proof_y_fraction') if proof_of else None,
pictures=pictures_by_source(item, job.get('pictures')))
except BaseException:
shutil.rmtree(output, ignore_errors=True)
raise
return output, parts, detail
def finish(job, status, detail):
with connect() as c:
c.execute('''UPDATE dtf_local.print_files SET status=%s, detail=%s,
finished_at=CASE WHEN %s='pending' THEN NULL ELSE now() END,
claimed_at=NULL,claim_token=NULL WHERE id=%s AND claim_token=%s AND status='rendering' ''',
(status, Jsonb(detail), status, job['id'], job['claim_token']))
def render_loop(storage):
down_since, delay = None, 2
while True:
try:
if render_one(storage):
continue
except psycopg.OperationalError as exc:
# A restart takes the database away for seconds: say so once.
if down_since is None:
down_since = time.monotonic()
logging.warning('Print render worker: database unavailable, retrying: %s', exc)
time.sleep(delay)
delay = min(delay * 2, 15)
continue
except Exception:
logging.exception('Print render worker tick failed')
if down_since is not None:
logging.info('Print render worker: database back after %s s', int(time.monotonic() - down_since))
down_since, delay = None, 2
time.sleep(2)